Docker basic Command Line Tips and Tricks

29/12/2020
Docker is an Open Source project for developers and system administrators to build, ship, and run distributed applications on laptops, data center VMs, or the cloud. Using the Docker, you can easily deploy and scale web apps , databases, and back-end services without depending on a particular stack. Before you go with docker, you will need to learn some important docker command to run docker and utilize it.

In this tutorial, I will explain some important docker commands. I will explain some hands-on experience in how they are used and what they do.

Requirements

  • A fresh server with Ubuntu 18.04 installed.
  • A root password is set up on your server.

Update your System

First, it is recommended to update your system to the latest stable version. You can do it by running the following command:

apt-get update -y
apt-get upgrade -y

Once your system is up-to-date, restart the system to apply the changes.

Install Docker

Next, you will need to install Docker CE on your server. By default, the latest version of Docker is not available in the Ubuntu 18.04 server default repository.

So, you will need to add the repository for that.

First, download and add Docker CE GPG key with the following command:

wget https://download.docker.com/linux/ubuntu/gpg
apt-key add gpg

Next, add the Docker CE repository to APT with the following command:

nano /etc/apt/sources.list.d/docker.list

Add the following line:

deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable

Save and close the file, when you are finished. Then, update the repository with the following command:

apt-get update -y

Once the repository is updated, install Docker CE with the following command:

apt-get install docker-ce -y

After installing Docker CE, check the Docker service with the following command:

systemctl status docker

List Docker Commands

Let’s start with seeing all available commands docker have.

You can list all available docker command by running the following command:

docker –help

You should see the following output:

Management Commands:
builder     Manage builds
config      Manage Docker configs
container   Manage containers
engine      Manage the docker engine
image       Manage images
network     Manage networks
node        Manage Swarm nodes
plugin      Manage plugins
secret      Manage Docker secrets
service     Manage services
stack       Manage Docker stacks
swarm       Manage Swarm
system      Manage Docker
trust       Manage trust on Docker images
volume      Manage volumes

Commands:
attach      Attach local standard input, output, and error streams to a running container
build       Build an image from a Dockerfile
commit      Create a new image from a container’s changes
cp          Copy files/folders between a container and the local filesystem
create      Create a new container
diff        Inspect changes to files or directories on a container’s filesystem
events      Get real time events from the server
exec        Run a command in a running container
export      Export a container’s filesystem as a tar archive
history     Show the history of an image
images      List images
import      Import the contents from a tarball to create a filesystem image
info        Display system-wide information
inspect     Return low-level information on Docker objects
kill        Kill one or more running containers
load        Load an image from a tar archive or STDIN
login       Log in to a Docker registry
logout      Log out from a Docker registry
logs        Fetch the logs of a container
pause       Pause all processes within one or more containers
port        List port mappings or a specific mapping for the container
ps          List containers
pull        Pull an image or a repository from a registry
push        Push an image or a repository to a registry
rename      Rename a container
restart     Restart one or more containers
rm          Remove one or more containers
rmi         Remove one or more images
run         Run a command in a new container
save        Save one or more images to a tar archive (streamed to STDOUT by default)
search      Search the Docker Hub for images
start       Start one or more stopped containers
stats       Display a live stream of container(s) resource usage statistics
stop        Stop one or more running containers
tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
top         Display the running processes of a container
unpause     Unpause all processes within one or more containers
update      Update configuration of one or more containers
version     Show the Docker version information
wait        Block until one or more containers stop, then print their exit codes

To check system-wide information on docker, run:

docker info

You should see the following output:

Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 18.09.6
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge host macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: bb71b10fd8f58240ca47fbb579b9d1028eea7c84
runc version: 2b18fe1d885ee5083ef9f0838fee39b62d653e30
init version: fec3683
Security Options:
apparmor
seccomp
Profile: default
Kernel Version: 4.15.0-20-generic
Operating System: Ubuntu 18.04 LTS
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 1.455GiB
Name: ubuntu1804
ID: X5ES:6AX3:NNO4:7OUD:ID2H:NB5W:UHYV:QBPF:DTHM:2KWY:W3F7:ATNT
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
Product License: Community Engine

To check docker version, run:

docker version

You should see the following output:

Client:
Version:           18.09.6
API version:       1.39
Go version:        go1.10.8
Git commit:        481bc77
Built:             Sat May  4 02:35:57 2019
OS/Arch:           linux/amd64
Experimental:      false
 
Server: Docker Engine – Community
Engine:
Version:          18.09.6
API version:      1.39 (minimum version 1.12)
Go version:       go1.10.8
Git commit:       481bc77
Built:            Sat May  4 01:59:36 2019
OS/Arch:          linux/amd64
Experimental:     false

Downloading Docker Image

First of all, You will need to pull docker image because containers are built using docker image.

There are many images already available on docker website. You can found any image through a search.

For example to search Ubuntu 18.04 image, Run

docker search ubuntu:18.04

You should see the following images available on docker website:

NAME                             DESCRIPTION          STARS       OFFICIAL     AUTOMATED
ercircle/ubuntu_server       java1.8,tomcat1.9,mysql 5.7 ubuntu:18.04 mys…   1   [OK]
willimar/ubuntu-aspnet-core  The base ubuntu:18.04 image with apt-transpo…   1
matrix1986/rust              rust build, run with ubuntu:18.04               0
arnow117/ubuntu_base         essential binaries under Ubuntu:18.04           0   [OK]
nologinb/java8               My variant of oracle java8 based on ubuntu:1…   0   [OK]
sensat/ubuntu                Packaged ubuntu:18.04 with relevant dependen…   0
sashr/get_iplayer            Container with Ubuntu:18.04 and get_iplayer:…   0
rocm/dev-ubuntu-18.04        Docker image based on Ubuntu:18.04 with the …   0
glitchylabs/docker-bitcoin-nicehash-miner  This project is an easy to use nichhash mine…  
0 [OK]
chockemeyer/dhcpd                DHCPD container on ubuntu:18.04 basis           0
devtty1er/binaryninja-version    Unmodified ubuntu:18.04 image tagged to mirr…   0
vkalvaitis/protobuf-compiler     Compile protobuf files on docker. Based on u…   0
skyblue1294/docker_pyku_python3  PYKU_python3 Analysis frame, based on ubuntu…   0 [OK]
edwintye/sklearn36-ubuntu        A small image with scikit-learn (and pandas)…   0 [OK]
puzza007/curl_docker             ubuntu:18.04 plus curl master                   0[OK]
cldx/sshd                        SSH daemon on Ubuntu:18.04                      0
shlagevuk/minergate_cli          Simple image based on ubuntu:18.04 with mine…   0 [OK]
durobun/ubntpy                         Ubuntu:18.04 + Python:3.7                       0
ntnetx/php7.0-apache                   PHP 7.0 Install -> ubuntu:18.04 + Apache + m…   0
vadimzenin/ubuntu-tools-min            Ubuntu with required minimum set of tools ba…   0
0x4ec7/ubuntu-python                   python installed on ubuntu:18.04                0
voltaireilustrisimo/my-shell           ubuntu:18.04 with tools                         0
dejef/u_min_app                        Ubuntu:18.04 with frozen python app             0
ktdfly/ubuntest                        ubuntu:18.04 python3 dnsutils curl wget ssh …   0
xamtasia/ubuntu-asp-net-core-hosting   ASP Net Core on Ubuntu with Hosting (Latest …   0

Next, Download the latest version of Ubuntu with the following command:

docker pull ubuntu

The output looks some thing like this:

Using default tag: latest
latest: Pulling from library/ubuntu
6abc03819f3e: Downloading [==========================>    ]  25.36MB/28.86MB
6abc03819f3e: Pull complete
05731e63f211: Pull complete
0bd67c50d6be: Pull complete
Digest: sha256:f08638ec7ddc90065187e7eabdfac3c96e5ff0f6b2f1762cf31a4f49b53000a5

Status: Downloaded newer image for ubuntu:latest

Listing  Images

Once the download has been finished, You can list all available images on your system by running the following command:

docker images

The output looks some thing like this:

REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
ubuntu              latest       7698f282e524        2 weeks ago         69.9MB

Running Docker Container

Now, to setup a basic ubuntu-18.04 container with a bash shell, you just run one command. docker run will run a command in a new container.

docker run -i -t ubuntu /bin/bash

You’re now using a bash shell inside of a ubuntu docker container. To disconnect, or detach, from the shell without exiting use the escape sequence Ctrl-p + Ctrl-q.

Listing  Containers

By default, you can use the following command to list all running containers:

docker ps

You can see the running container in the following output:

CONTAINER ID   IMAGE    COMMAND     CREATED    STATUS     PORTS      NAMES

ff2deb4f97b1 ubuntu "/bin/bash" a minute ago  Up a minute  gifted_wiles

You can also list both  running and non-running containers by running the following command:

docker ps -l

Sometimes container stops  due to its process ending or you stopping it explicitly. In this situation you can run container again with container ID.

docker start "container ID"

Note: You can find container ID using docker ps command.

Stoping Container

To stop a container’s process, run:

docker stop "container ID"

Saving Container

If you would like to save the changes you have made with a container, use commit command to save it as an image.

docker commit "container ID" image_name

For example, create new-ubuntu image from ubuntu with the following command:

docker commit ff2deb4f97b1 new-ubuntu

Now, run the following command to see a newly created image:

docker images

You should see the following output:

REPOSITORY        TAG             IMAGE ID           CREATED          SIZE
new-ubuntu       latest          625f32622cbd      15 seconds ago    69.9MB
ubuntu           latest          7698f282e524      2 weeks ago       69.9MB

This command turns your container to an image. You can roll back the container whenever you need.

Attach Docker Container

If we want to attach into a running container, Docker allows you to interact with running containers using the attach command.

You can use attach command with the container ID. The container id can be fetched using the command “docker ps”.

docker attach "container ID"

Inspect Docker Container

You can check every information about a Docker Container using the inspect command with container ID.

docker inspect "container ID"

Stop and Delete all Containers

To stop all running containers, Run:

docker stop $(docker ps -a -q)

To delete all existing containers, Run:

docker rm $(docker ps -a -q)

To delete all existing images, Run:

docker rmi $(docker images -q -a)

Check Docker Log

If you run docker container as a daemon then it may be useful to know what appears on the console output of the running container. The docker logs command retrieves logs present at the time of execution.

You can use docker log command with container ID.

docker logs -f "container ID"

Conclusion

I hope you have now enough knowledge to work around with Docker command line. You can now easily start, stop, delete container and image using Docker cli. You can also did many stuff using Docker cli. For more information, you can refer Docker official doc at https://docs.docker.com/engine/reference/commandline/docker/

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Arch Linux Docker Tutorial

What Is Docker? If you read technology news websites, you’ve most likely heard about Docker and all the wonderful things...
28/12/2020

Install Docker on Debian 9

How to Install and Use Docker on Debian 9 Stretch Docker is a containerization system like LXC for virtualizing Linux operating...
28/12/2020

Networking and Storage for Docker Containers

Networking and Storage for Docker Containers The first thing people look for after running Apache in a container is how...
28/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

SỰ KHÁC BIỆT GIỮA RESIDENTIAL PROXY VÀ PROXY DATACENTER
17/02/2024

Mua Proxy v6 US Private chạy PRE, Face, Insta, Gmail
07/01/2024

Mua shadowsocks và hướng dẫn sữ dụng trên window
05/01/2024

Tại sao Proxy Socks lại được ưa chuộng hơn Proxy HTTP?
04/01/2024

Mua thuê proxy v4 nuôi zalo chất lượng cao, kinh nghiệm tránh quét tài khoản zalo
02/01/2024