Complete operation commands of Docker's container, image and image Warehouse Center

Keywords: Linux Operation & Maintenance Docker

This article introduces the operation parameters of Docker, including the operation commands for container, image and registry.

Tips: This article comes from Learn Docker + K8S from BAT technical experts special column.

1. Container operation

Common operation commands related to Docker and container are as follows:

run

docker run is used to start a container through an image. This can be regarded as the core command for operating the docker container. There are as many as 91 parameters. The user manual is as follows:

[root@emr-header-1 ~]# docker run --help

Usage:	docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

For example, we start a centos image

[root@xxx ~]# docker run -ti centos:latest /bin/bash
[root@b16716790a3f /]#

centos:latest is IMAGE in Usage, and COMMAND is / bin/bash. Then -ti assign a terminal for interactive input.

We mainly introduce several important parameters below.

--interactive is equivalent to - i and accepts stdin input;

--tty is equal to - t, and a tty is assigned, which is generally used with i;

--Name sets a name for the container;

--Add host sets the hosts file for the container in the format host:ip;

--env environment variable setting;

--expose exposed ports;

--hostname sets the host name of the container;

--link container is related to the network and connected to other containers;

--CPU quota sets the CPU limit;

--Memory sets the memory limit that the container can use.

attach

docker attach allows us to enter the interior of a running container. The principle of this command is to assign stdin, stdout and stderr to a running container.

[root@xxx ~]# docker attach --help

Usage:	docker attach [OPTIONS] CONTAINER

Attach local standard input, output, and error streams to a running container

Options:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)

It should be noted that if you want to exit after docker attach, you cannot use exit, and the original container will exit if you use exit. We can use Ctrl + C to exit.

exec

The docker exec command can also achieve the purpose of attach. The purpose of the exec command is to execute a command in a running container. The principle of this command is actually very simple. At the Linux kernel level, it is equivalent to forking a process, and then setting the same NameSpace as the container. If we specify - ti in OPTIONS, we can enter a running container and execute the command. Because this is a fork out process, you can exit.

[root@emr-header-1 ~]# docker exec --help

Usage:	docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container

ps

docker ps can be used to list the information of all running containers, and support some parameters similar to filter.

[root@xxx ~]# docker ps --help

Usage:	docker ps [OPTIONS]

List containers

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes

kill

docker kill is used to kill one or a group of container s.

[root@xxx ~]# docker kill --help

Usage:	docker kill [OPTIONS] CONTAINER [CONTAINER...]

Kill one or more running containers

Options:
  -s, --signal string   Signal to send to the container (default "KILL")

logs

Docker logs is used to obtain the docker logs.

[root@xxx ~]# docker logs --help

Usage:	docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)

top

The docker top command is sometimes useful. We want to see which process runs the container on the host. After all, the essence of container is a process, which we will discuss in detail later.

[root@xxx ~]# docker top --help

Usage:	docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

2. Mirror operation

Common operation commands related to mirroring are as follows:

  • Images: lists all local images;
  • Build: build the image through dockerfile;
  • commit: generate a new image of all changes in the container;
  • History: view the history of the image;
  • Save: save the image as a tar package;
  • Import: import a new image through the tar package;
  • load: import the image through tar package or flag input;
  • rmi: delete the local image;
  • Tag: tag the image.

images

docker images will display all local non hidden images, and the intermediate dependent images will be hidden by default.

[root@xxx ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
busybox             1-musl              ff04c2bddacb        3 days ago          1.44MB
busybox             1-glibc             ad06ec8ab37b        3 days ago          5.2MB
busybox             1-uclibc            b534869c81f0        3 days ago          1.22MB
busybox             latest              b534869c81f0        3 days ago          1.22MB
busybox             1.24-glibc          54df49495ae4        3 years ago         4.18MB
busybox             1-ubuntu            d34ea343a882        3 years ago         4.35MB
busybox             1.21-ubuntu         d34ea343a882        3 years ago         4.35MB
busybox             1.21.0-ubuntu       d34ea343a882        3 years ago         4.35MB
busybox             1.23                a84c36ecc374        4 years ago         1.1MB
busybox             1.23.2              a84c36ecc374        4 years ago         1.1MB

This is the default display of docker images, but sometimes we need to display more information, such as Digest, or filter out some images, so we can add parameters. Let's take a look at the complete function of docker images.

[root@xxx ~]# docker images --help

Usage:	docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show numeric IDs
  • The all parameter displays all images, including intermediate dependent images;
  • Digest displays digest;
  • filter filters the image;
  • No TRUNC will truncate some output columns by default, and this parameter will be displayed in full.
  • quiet displays only the digital ID of the image.
  • The format parameter is output in the form of a Go template, which simply specifies the output column. This description is not very intuitive. We can take a simple example as follows. The ID and Repository are the specified output columns.
[root@xxx ~]# docker images --format "{{.ID}}: {{.Repository}}"
ff04c2bddacb: busybox
ad06ec8ab37b: busybox
b534869c81f0: busybox
b534869c81f0: busybox

In addition to ID and Repository, all the columns supported by Docker are as follows:

PlaceholderDescription
.IDMirror ID
.RepositoryImage repo is actually the image name
.TagMirror tag
.DigestMirror digest
.CreatedSinceHow long after the mirror is created
.CreatedAtCreation time of the image
.SizeMirrored disk size

build

In Docker, we can build an image using docker build through a Dockerfile. We will have a special section to expand this one later, which will be skipped here for the time being.

commit

As mentioned above, we can build an image through a Dockerfile, but sometimes we make some changes to the container during use, such as installing some dependent packages. We want to save these changes to form a new image. At the same time, we don't want to write Dockerfile, or we don't have the previous Dockerfile. At this time, we can persist a container environment into an image through docker commit. Let's first take a look at the usage specification of docker commit.

[root@xxx ~]# docker commit --help

Usage:	docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

Options:
  -a, --author string    Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)

If we want to commit a container, we can first find the id of the container we want to commit through docker ps.

[root@xxx ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
d7bb841d9811        legendtkl:v2.1   "/bin/bash"         About a minute ago   Up About a minute   22/tcp              vigorous_chaplygin

Then execute commit.

[root@xxx ~]# docker commit d7bb841d9811 legendtkl:v2.2

Then, execute docker images to see the image of our new commit.

history

Use docker history to view the history of the image, for example. The following commands are described in detail in the Dockerfile section.

[root@emr-header-1 ~]# docker history a84c36ecc374
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
a84c36ecc374        4 years ago         /bin/sh -c #(nop) CMD ["sh"]                    0B
<missing>           4 years ago         /bin/sh -c #(nop) ADD file:6cccb5f0a3b394711...   1.1MB
[root@emr-header-1 ~]# docker history 243b193cdf70
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
243b193cdf70        3 hours ago                                                         0B
e104690ec93c        2 weeks ago         /bin/sh -c #(nop)  CMD []                       0B
<missing>           2 weeks ago         /bin/sh -c #(nop)  ENTRYPOINT ["/legendtkl...   0B
<missing>           2 weeks ago         /bin/sh -c #(nop) WORKDIR /app                  0B
<missing>           2 weeks ago         /bin/sh -c #(nop) COPY file:cede62805de63bfa...   30kB
<missing>           2 weeks ago         /bin/sh -c #(nop) COPY file:c95d0f15f9cd8538...   18.6MB
<missing>           5 weeks ago         /bin/sh -c mkdir -p /app                        0B
<missing>           4 years ago         /bin/sh -c #(nop) CMD ["/sbin/init"]            1.05MB
<missing>           4 years ago         /bin/sh -c #(nop) EXPOSE 22/tcp                 1.05MB
<missing>           4 years ago         /bin/sh -c sh /tmp/install/run.sh               260MB
<missing>           4 years ago         /bin/sh -c #(nop) ADD dir:31ce6fc92887bd109f...   1.05MB
<missing>           4 years ago                                                         2.31GB              Imported from http://10.137.67.190/download/os/AliOS5U7-x86-64.tgz

save

There is such a scenario. Sometimes we need to import the local image of one machine to another machine. Of course, you can push the image to the image warehouse center first, and then pull another machine. However, sometimes, due to the security of the image or the large image, it is not very suitable for this push and then pull scenario. Then we can export the image into a compressed file first, and then import the compressed file to another machine. Exporting images to compressed files is what docker save does.

[root@xxx ~]# docker save --help

Usage:	docker save [OPTIONS] IMAGE [IMAGE...]

Save one or more images to a tar archive (streamed to STDOUT by default)

Options:
  -o, --output string   Write to a file, instead of STDOUT

The default is to output to stdout. Of course, you can also specify the output file through the - o parameter. Then we can export it in the following two ways.

docker save busybox:latest > busybox-latest.tar

perhaps

docker save busybox:latest -o busybox-latest.tar

import

docker import and the following load are used to import images from compression. The use method is also relatively simple.

[root@emr-header-1 ~]# docker import --help

Usage:	docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]

Import the contents from a tarball to create a filesystem image

Options:
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Set commit message for imported image

For example, to import the image tar package exported above, you can use the following command.

[root@emr-header-1 ~]# docker import busybox-latest.tar
sha256:1278080eee0524c6ca5c1de63ea439deb0e6d62035549cca9dbd4d9129e38655

load

Import the image through the tar package. The usage is.

[root@xxx ~]# docker load --help

Usage:	docker load [OPTIONS]

Load an image from a tar archive or STDIN

Options:
  -i, --input string   Read from tar archive file, instead of STDIN
  -q, --quiet          Suppress the load output

For example, if I want to import the image compressed package exported above, I can complete it through the following command.

$ [root@xxx ~]# docker load -i busybox-latest.tar
Loaded image: busybox:latest

rmi

docker rmi can be used to delete images. The usage is as follows:

[root@xxx ~]# docker rmi --help

Usage:	docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents

We can directly use IMAGE name + tag or IMAGE ID to know IMAGE. We can see that the above description document also supports two parameters:

  • Force: force deletion;
  • No prune: do not delete the unlabeled parent image.

tag

docker tag can be used to tag the image. The target image can use image name + tag or image ID, as follows:

docker tag busybox:v1 busybox:v2

perhaps

docker tag <image_id> busybox:v2

3. Mirror warehouse operation

There are four important operation commands related to the image warehouse:

  • login: log in to the image warehouse;
  • logout: log out of the image warehouse;
  • Pull: pull the image from the image warehouse;
  • Push: to push an image to the image warehouse, you need to login first.

login

login is easy to use. We can directly look at the instructions through help, as follows:

root@xxx # docker login --help

Usage:	docker login [OPTIONS] [SERVER]

Log in to a Docker registry

Options:
  -p, --password string   Password
      --password-stdin    Take the password from stdin
  -u, --username string   Username

As shown above, docker login [OPTION] [SERVER], where SERVER is the warehouse address and OPTION is the user name and password. For example, if I want to log in to Alibaba cloud Hangzhou image warehouse, I can do the following:

$ docker login -u legendtkl -p <password> registry.cn-hangzhou.aliyuncs.com

However, it is generally not recommended to display the password directly on the command line so that other users can see it directly through history. Therefore, we generally omit the - p parameter and enter the password on the keyboard, as follows:

$ docker login -u legendtkl registry.cn-hangzhou.aliyuncs.com
Password: 

logout

logout is relatively simple. You don't need any parameters. You can directly connect to the warehouse address, as shown below.

root@xxx # docker logout --help

Usage:	docker logout [SERVER]

Log out from a Docker registry

pull

Pulling an image is also relatively simple, as shown below

root@xxx # docker pull --help

Usage:	docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)

We can pull the image of the specified version by adding Tag or Digest after the image name. If it is not specified, we can pull the image of the latest Tag. So what are Tag and Digest?

We can understand that tag and digest are unique identifiers of the mirrored version. Tag can be understood as the tag in Git. Digest is the summary of the image file, which is generally the value calculated by sha256 hash. Of course, when we normally pull, we always specify tag, and rarely specify digest. For example:

docker pull busybox:1.23
docker pull busybox@sha256:2824fe048727a69da66cf1be00cebd3bb9cfe1f238473693aa9358b411208527

One thing to note is that try not to use the latest Tag. As the name suggests, the latest label indicates the latest image. In other words, it will change. This situation can never be used in the production environment.

When we see the pulled image, we also have two parameters: all tags and disable content trust. The first parameter will download all the labels of the image, which is generally not used. The second parameter is used to skip the verification of the image.

push

push the image to the warehouse. The parameters are similar to pull. It should be noted that if the pushed image already exists in the warehouse, the existing image will be overwritten.

root@xxx # docker push --help

Usage:	docker push [OPTIONS] NAME[:TAG]

Push an image or a repository to a registry

Options:
      --disable-content-trust   Skip image signing (default true)

4. Summary

This article introduces the common commands of docker, including container, image and image warehouse center. Of course, due to the large number of docker commands and parameters, it can not be fully displayed here, but if you master the above commands, you will basically have no problem using docker.

Posted by hopelessX on Sun, 26 Sep 2021 17:30:32 -0700