Docker容器

容器是Docker的另一个核心概念。简单来说,容器是镜像的一个运行实例。不同的是,镜像是静态的只读文件,而容器带有运行时需要的可写文件层,同时,容器中的应用进程处于运行状态。

一、创建容器

1.1、新建容器

可以使用docker create命令新建一个容器。该命令的使用方式如下:

root@ubuntu:~# docker create --help

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

Create a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network string                 Connect a container to a network (default "default")
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

例如:

root@ubuntu:~# docker create -it ubuntu:18.04
392483f776206979827a9651376eec53adf435b57642edb1d6a465a54adaab94
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
392483f77620        ubuntu:18.04        "/bin/bash"         4 seconds ago       Created                                 practical_proskuriakova

1.2、启动容器

使用docker create命令创建的容器处于停止状态,可以使用docker start命令启动它,该命令的使用方式如下:

root@ubuntu:~# docker start --help

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

Start one or more stopped containers

Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals
      --detach-keys string   Override the key sequence for detaching a container
  -i, --interactive          Attach container's STDIN

例如,启动刚刚创建的容器:

root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
392483f77620        ubuntu:18.04        "/bin/bash"         6 minutes ago       Created                                 practical_proskuriakova
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker start 392
392

可以通过docker ps命令查看一个运行中的容器:

root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
392483f77620        ubuntu:18.04        "/bin/bash"         7 minutes ago       Up 7 seconds                            practical_proskuriakova

1.3、新建并启动容器

除了创建容器后通过start命令来启动,也可以直接新建并启动容器,命令为:docker run。该命令的使用方式如下:

root@ubuntu:~# docker run --help

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

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network string                 Connect a container to a network (default "default")
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

例如,下面的命令输出一个hello world,之后容器自动终止:

root@ubuntu:~# docker run ubuntu:18.04 /bin/echo 'Hello World'
Hello World

下面的命令启动一个bash终端,允许用户进行交互:

root@ubuntu:~# docker run -it ubuntu:18.04 /bin/bash
root@d9fe213dbaba:/#

其中,-t表示让Docker分配一个伪终端(pseudo-tty)并绑定到容器的标准输入上,-i则让容器的标准输入保持打开。在交互模式下,可以通过创建的终端输入命令:

root@d9fe213dbaba:/# pwd
/
root@d9fe213dbaba:/#
root@d9fe213dbaba:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@d9fe213dbaba:/#
root@d9fe213dbaba:/#
root@d9fe213dbaba:/# ps
   PID TTY          TIME CMD
     1 pts/0    00:00:00 bash
    13 pts/0    00:00:00 ps

可以通过ctrl+d或输入exit命令退出容器:

root@b54c6700c2f5:/# exit
exit

1.4、守护态运行

更多的时候,需要让docker容器在后台以守护态(daemon)形式运行,此时可以通过添加-d参数实现。例如,下面的命令会在后台运行容器:

root@ubuntu:~# docker run -d ubuntu:18.04 /bin/sh -c "while true;do echo hello world; sleep 1; done"
7a17b402c6f13247e9d50a4bbd46994974e92d695df5f2a2bbabd211f114aa29

容器启动后会返回一个唯一id,可以通过docker ps或docker container ls命令查看容器信息:

root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
6e2147d9b059        ubuntu              "/bin/sh -c 'while t…"   14 seconds ago      Up 13 seconds                           elastic_hypatia
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS               NAMES
6e2147d9b059        ubuntu              "/bin/sh -c 'while t…"   About a minute ago   Up About a minute                       elastic_hypatia

1.5、查看容器输出

可以通过docker logs命令获取容器的输出信息,该命令的使用方式如下:

root@ubuntu:~# 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)

例如:

root@ubuntu:~# docker logs 7a1
hello world
hello world
hello world
hello world
hello world
hello world
......

2、停止容器

2.1、暂停容器

可以使用docker pause命令来暂停一个运行中的容器。该命令的使用方式如下:

root@ubuntu:~# docker pause --help

Usage:  docker pause CONTAINER [CONTAINER...]

Pause all processes within one or more containers

例如:

root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
7a17b402c6f1        ubuntu:18.04        "/bin/sh -c 'while t…"   19 minutes ago      Up 19 minutes                           objective_euler
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker pause 7a1
7a1
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS               NAMES
7a17b402c6f1        ubuntu:18.04        "/bin/sh -c 'while t…"   19 minutes ago      Up 19 minutes (Paused)                       objective_euler

处于paused状态的容器,可以使用docker unpause命令恢复到运行状态。docker unpause命令的使用方式如下:

root@ubuntu:~# docker unpause --help

Usage:  docker unpause CONTAINER [CONTAINER...]

Unpause all processes within one or more containers

例如:

root@ubuntu:~# docker unpause 7a1
7a1
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
7a17b402c6f1        ubuntu:18.04        "/bin/sh -c 'while t…"   22 minutes ago      Up 22 minutes                           objective_euler

2.2、终止容器

可以使用docker stop命令来终止一个运行中的容器。该命令的使用方式如下:

root@ubuntu:~# docker stop --help

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

Stop one or more running containers

Options:
  -t, --time int   Seconds to wait for stop before killing it (default 10)

例如:

root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
7a17b402c6f1        ubuntu:18.04        "/bin/sh -c 'while t…"   31 minutes ago      Up 31 minutes                           objective_euler
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker stop 7a1
7a1

此时,执行docker container prune命令会自动清除掉所有处于停止状态的容器:

root@ubuntu:~# docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
7a17b402c6f13247e9d50a4bbd46994974e92d695df5f2a2bbabd211f114aa29
d9fe213dbabaabe7d9361e80c39b1366d9601f0e4eb3b26f801b14ced1929ea0
a2406f04642b725041c357d013aa58a28197d5676b3100f614c4e6460f34055a

Total reclaimed space: 519B

处于停止状态的容器,可以通过docker [container] 命令重新启动:

2.3、重新启动容器

docker restart命令会将一个运行状态的容器先终止,然后再重新启动,该命令的使用方式如下:

root@ubuntu:~# docker restart --help

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

Restart one or more containers

Options:
  -t, --time int   Seconds to wait for stop before killing the container (default 10)

三、进入容器

在使用-d参数时,容器启动后会进入后台,用户无法看到容器中的信息,也无法进行操作。这时如果需要进入容器进行操作,可以使用attach或exec命令。

3.1、attach命令

该命令的使用方式如下:

root@ubuntu:~# 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)

例如:

root@ubuntu:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              18.04               47b19964fb50        4 weeks ago         88.1MB
root@ubuntu:~#
root@ubuntu:~# docker run -itd ubuntu:18.04
3ff7a10cbb1dc96217230f35f2225d4b567531deb8447dd781e951e085354cc1
root@ubuntu:~#
root@ubuntu:~# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
3ff7a10cbb1d        ubuntu:18.04        "/bin/bash"         13 seconds ago      Up 12 seconds                           eloquent_tharp
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker attach 3ff
root@3ff7a10cbb1d:/#
root@3ff7a10cbb1d:/#
root@3ff7a10cbb1d:/#

使用attach命令有时候并不方便:当多个窗口同时attach到同一个容器的时候,多个窗口会同步显示;当某个窗口因命令阻塞时,其他窗口也不能操作了。

3.2、exec命令

从Docker 1.3.0开始,Docker提供了一个更加方便的exec命令,可以在运行的容器内直接执行任意命令。该命令的使用方式如下:

root@ubuntu:~# 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

例如,启动一个容器,并启动一个bash:

root@ubuntu:~# docker start 3ff
3ff
root@ubuntu:~#
root@ubuntu:~# docker exec -it 3ff /bin/bash
root@3ff7a10cbb1d:/#

四、删除容器

可以使用docker rm命令来删除一个容器,该命令的使用方式如下:

root@ubuntu:~# docker rm --help

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

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove the volumes associated with the container

例如,下面的命令用于删除一个容器:

root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
3ff7a10cbb1d        ubuntu:18.04        "/bin/bash"         8 minutes ago       Exited (0) 4 seconds ago                       eloquent_tharp
root@ubuntu:~#
root@ubuntu:~# docker rm 3ff
3ff
root@ubuntu:~#
root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

如果删除一个运行中的容器会提示如下错误:

Error response from daemon: You cannot remove a running container 6b9f7161defd53241b466e61ee9854e8c632522f8207db96bb3efbae4bfab55d. Stop the container before attempting removal or force remove

此时可以指定-f强制删除:

root@ubuntu:~# docker rm -f 6b9f7161defd
6b9f7161defd

五、导入和导出容器

有时需要将容器从一个系统迁移到另一个系统,此时可以使用Docker的导入和导出功能,这也是Docker自身提供的一个重要特性。

5.1、导出容器

导出容器是指,导出一个已经创建的容器到一个文件,不管此时这个容器是否处于运行状态。可以使用docker export命令,该命令的使用方式为:

root@ubuntu:~# docker export --help

Usage:  docker export [OPTIONS] CONTAINER

Export a container's filesystem as a tar archive

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

例如:

root@ubuntu:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              18.04               47b19964fb50        4 weeks ago         88.1MB
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker create ubuntu:18.04
05865612f4bb0e5941709ec98bbe24aea9963e932674bf74938c1960607bb849
root@ubuntu:~#
root@ubuntu:~# docker export -o ubuntu_18.04.tar 058

之后,可以将导出的tar文件传输到其他机器上,然后通过导入命令导入到系统,实现容器的迁移。

5.2、导入容器

导出的文件可以使用如下docker import命令导入变成镜像,该命令的使用方式如下:

root@ubuntu:~# 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

可以通过-c选项在导入的同时执行对容器进行修改的Dockerfile指令。

例如,将导出的ubuntu_18.04.tar文件导入到系统中:

root@ubuntu:~# docker import ubuntu_18.04.tar test:1.0
sha256:2ab4b4c91d977108f9ffe52f1bb9e86049c04c459ad764463bb7bcf51cc11b39
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
test                1.0                 2ab4b4c91d97        3 seconds ago       69.8MB
ubuntu              18.04               47b19964fb50        4 weeks ago         88.1MB

前面学习过使用docker load来导入镜像文件,与docker import十分相似。实际上,既可以使用docker load命令来导入镜像存储文件到本地镜像库,也可以使用docker import命令来导入一个容器快照到本地镜像库。二者的区别是:容器快照文件将丢弃所有的历史记录和元数据信息(即仅保存容器当时的快照状态),而镜像存储文件将保存完整记录,体积更大。此外,从容器快照文件导入时可以重新指定标签等元数据信息。

六、查看容器

6.1、查看容器详情

查看容器详情可以使用docker inspect命令。该命令的使用方式如下:

root@ubuntu:~# docker inspect --help

Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes if the type is container
      --type string     Return JSON for specified type

例如,查看某容器的具体信息,会以JSON格式返回包含容器ID、创建时间、路径、状态、镜像、配置等在内的各项信息:

root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
05865612f4bb        ubuntu:18.04        "/bin/bash"         27 minutes ago      Created                                 relaxed_sammet
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker inspect 058
[
    {
        "Id": "05865612f4bb0e5941709ec98bbe24aea9963e932674bf74938c1960607bb849",
        "Created": "2019-03-09T07:52:47.223262729Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "created",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "0001-01-01T00:00:00Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:47b19964fb500f3158ae57f20d16d8784cc4af37c52c49d3b4f5bc5eede49541",
        "ResolvConfPath": "",
        "HostnamePath": "",
        "HostsPath": "",
        "LogPath": "",
        "Name": "/relaxed_sammet",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/b2398fb966604f885cae8283b9ca7765df9c6a662c62979f622ec0c261f8e1c6-init/diff:/var/lib/docker/overlay2/19935341c475a04227fc7c9bf8b7cd0d36f4d2d5ec9ccf7a6ef8e1e96335ca22/diff:/var/lib/docker/overlay2/b7cb3e3de242813c52dc16ddaceee2457dc8dfca7485e37ac27b53052df478d8/diff:/var/lib/docker/overlay2/4c2826b582058dad2a6fe53c9df3bd1dd770f0fe520b4eb5666077e331a1c429/diff:/var/lib/docker/overlay2/9d76188495a8498dace358a0ba5fd489d9cefbbf95aaeb1cae5aa0c5ad94c251/diff",
                "MergedDir": "/var/lib/docker/overlay2/b2398fb966604f885cae8283b9ca7765df9c6a662c62979f622ec0c261f8e1c6/merged",
                "UpperDir": "/var/lib/docker/overlay2/b2398fb966604f885cae8283b9ca7765df9c6a662c62979f622ec0c261f8e1c6/diff",
                "WorkDir": "/var/lib/docker/overlay2/b2398fb966604f885cae8283b9ca7765df9c6a662c62979f622ec0c261f8e1c6/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "05865612f4bb",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "ArgsEscaped": true,
            "Image": "ubuntu:18.04",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "",
                    "EndpointID": "",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

6.2、查看容器内进程

查看容器内进程可以使用docker top命令,该命令类似于Linux中的top命令,会打印出容器内的进程信息,使用方式如下:

root@ubuntu:~# docker top --help

Usage:  docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

例如:

root@ubuntu:~# docker run -itd ubuntu:18.04 /bin/bash
315708ee6e7d6f8c5c733bef1aa5ca7a64cd14f667a66db1f71576692e503647
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker top 315
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                6844                6827                0                   00:24               pts/0               00:00:00            /bin/bash

6.3、查看统计信息

查看统计信息可以使用docker stats命令,会显示CPU、内存、存储、网络等统计信息,该命令的使用方式如下:

root@ubuntu:~# docker stats --help

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

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

例如:

root@ubuntu:~# docker stats
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT   MEM %               NET I/O             BLOCK I/O           PIDS
315708ee6e7d        adoring_buck        0.00%               408KiB / 1.936GiB   0.02%               3.37kB / 0B         0B / 0B             1


七、其他容器命令

7.1、复制文件

docker cp命令支持在容器和主机之间复制文件。该命令的使用方式如下:

root@ubuntu:~# docker cp --help

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
        docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH

例如,将本地的data目录复制到容器的/tmp目录下:

root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
892a12a5a44b        cef201641cc5        "/bin/bash"         17 minutes ago      Up 14 minutes                           gifted_lichterman
root@ubuntu:~#
root@ubuntu:~# ll
total 70668
drwx------  4 root root     4096 Mar  1 23:59 ./
drwxr-xr-x 24 root root     4096 Feb 24 02:33 ../
-rw-------  1 root root    22207 Feb 28 05:08 .bash_history
-rw-r--r--  1 root root     3106 Oct 22  2015 .bashrc
drwx------  2 root root     4096 Feb 24 02:25 .cache/
drwxr-xr-x  2 root root     4096 Mar  1 23:59 data/
-rw-r--r--  1 root root      148 Aug 17  2015 .profile
-rw-------  1 root root 72299008 Feb 28 05:06 ubuntu.tar
-rw-r--r--  1 root root      170 Feb 24 02:30 .wget-hsts
root@ubuntu:~#
root@ubuntu:~# docker cp data 892a12a5a44b:/tmp
root@ubuntu:~#
root@ubuntu:~# docker exec -it 892a12a5a44b /bin/bash
root@892a12a5a44b:/#
root@892a12a5a44b:/# ll /tmp
total 12
drwxrwxrwt 1 root root 4096 Mar  2 08:06 ./
drwxr-xr-x 1 root root 4096 Mar  2 07:48 ../
drwxr-xr-x 2 root root 4096 Mar  2 07:59 data/
root@892a12a5a44b:/#

7.2、查看变更

docker diff命令用于查看容器内文件系统的变更,该命令使用方式为:

root@ubuntu:~# docker diff --help

Usage:  docker diff CONTAINER

Inspect changes to files or directories on a container's filesystem

例如,查看容器内的数据修改:

root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
892a12a5a44b        cef201641cc5        "/bin/bash"         19 minutes ago      Up 17 minutes                           gifted_lichterman
root@ubuntu:~#
root@ubuntu:~# docker diff 892a12a5a44b
C /root
A /root/.bash_history
C /tmp
A /tmp/data

7.3、查看端口映射

docker port命令可以查看容器的端口映射情况。格式为:

root@ubuntu:~# docker port --help

Usage:  docker port CONTAINER [PRIVATE_PORT[/PROTO]]

List port mappings or a specific mapping for the container

例如:

root@ubuntu:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
892a12a5a44b        cef201641cc5        "/bin/bash"         24 minutes ago      Up 21 minutes                           gifted_lichterman
root@ubuntu:~#
root@ubuntu:~#
root@ubuntu:~# docker port 892a12a5a44b

7.4、更新配置

docker update命令可以更新容器的一些运行时配置,格式为:

root@ubuntu:~# docker update --help

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

Update configuration of one or more containers

Options:
      --blkio-weight uint16        Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --cpu-period int             Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int              Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int          Limit the CPU real-time period in microseconds
      --cpu-rt-runtime int         Limit the CPU real-time runtime in microseconds
  -c, --cpu-shares int             CPU shares (relative weight)
      --cpus decimal               Number of CPUs
      --cpuset-cpus string         CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string         MEMs in which to allow execution (0-3, 0,1)
      --kernel-memory bytes        Kernel memory limit
  -m, --memory bytes               Memory limit
      --memory-reservation bytes   Memory soft limit
      --memory-swap bytes          Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --restart string             Restart policy to apply when a container exits

例如,限制总配额为1秒,容器所占用的时间为10%:

root@ubuntu:~# docker update --cpu-quota 1000000 892a12a5a44b
892a12a5a44b
root@ubuntu:~#
root@ubuntu:~# docker update --cpu-period 1000000 892a12a5a44b
892a12a5a44b

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值