Docker(四):使用容器

Docker 专栏收录该内容
5 篇文章 1 订阅

容器是镜像的一个运行实例。

一,创建容器

1.新建容器

命令docker create [OPTIONS] IMAGE [COMMAND] [ARG...]新建一个容器。
其中OPTIONS主要包括如下几大类:与容器运行模式相关、与容器环境配置相关、与容器资源限制和安全保护相关:

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
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --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
      --domainname string              Container NIS domain name
      --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
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --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 network                Connect a container to a network
      --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)
      --platform string                Set platform if server is multi-platform capable
      --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
      --pull string                    Pull image before creating ("always"|"missing"|"never") (default "missing")
      --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
xiaolu@DangFuLin:~$ docker create -it ubuntu:latest
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
da7391352a9b: Downloading                                                                                               14428a6d4bcd: Download complete                                                                                         2c2d948710f2: Download complete                                                                                         latest: Pulling from library/ubuntu
da7391352a9b: Pull complete                                                                                             14428a6d4bcd: Pull complete                                                                                             2c2d948710f2: Pull complete                                                                                             Digest: sha256:c95a8e48bf88e9849f3e0f723d9f49fa12c5a00cfc6e60d2bc99d87555295e4c
Status: Downloaded newer image for ubuntu:latest
2f4127e7e27d48b3d57936e48f9e22633a52ef5f3f82fdb57c1e8b69e80159b7

xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED              STATUS    PORTS     NAMES
2f4127e7e27d   ubuntu:latest   "/bin/bash"   About a minute ago   Created             stupefied_hermann

2.启动容器

新建的容器处于停止状态,可以使用docker start IMAGE命令来启动它。

xiaolu@DangFuLin:~$ docker ps -a	#查看所有容器
CONTAINER ID   IMAGE           COMMAND       CREATED         STATUS    PORTS     NAMES
2f4127e7e27d   ubuntu:latest   "/bin/bash"   7 minutes ago   Created             stupefied_hermann
xiaolu@DangFuLin:~$ docker start 2f4127e7e27d
2f4127e7e27d
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED         STATUS         PORTS     NAMES
2f4127e7e27d   ubuntu:latest   "/bin/bash"   9 minutes ago   Up 4 seconds             stupefied_hermann
  • STATUS已发生变化

3.新建并启动容器

除了创建容器后通过start命令来启动,也可以直接使用命令docker run [OPTIONS] IMAGE [COMMAND] [ARG...]新建并启动容器。
其中OPTIONS

  • -a stdin: 指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;
  • -d: 后台运行容器,并返回容器ID;
  • -i: 以交互模式运行容器,通常与 -t 同时使用;
  • -P: 随机端口映射,容器内部端口随机映射到主机的端口
  • -p: 指定端口映射,格式为:主机(宿主)端口:容器端口
  • -t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用;
  • –name=“nginx-lb”: 为容器指定一个名称;
  • –dns 8.8.8.8: 指定容器使用的DNS服务器,默认和宿主一致;
  • –dns-search example.com: 指定容器DNS搜索域名,默认和宿主一致;
  • -h “mars”: 指定容器的hostname;
  • -e username=“ritchie”: 设置环境变量;
  • –env-file=[]: 从指定文件读入环境变量;
  • –cpuset=“0-2” or --cpuset=“0,1,2”: 绑定容器到指定CPU运行;
  • -m :设置容器使用内存最大值;
  • –net=“bridge”: 指定容器的网络连接类型,bridge/host/none/container: 四种;
  • –link=[]: 添加链接到另一个容器;
  • –expose=[]: 开放一个端口或一组端口;
  • –volume , -v: 绑定一个卷
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED         STATUS         PORTS     NAMES
2f4127e7e27d   ubuntu:latest   "/bin/bash"   9 minutes ago   Up 4 seconds             stupefied_hermann
xiaolu@DangFuLin:~$ docker run ubuntu /bin/echo 'Hello world'
Hello world

xiaolu@DangFuLin:~$ docker run -it ubuntu:latest /bin/bash
root@1ecb285a4509:/# pwd
/
root@1ecb285a4509:/# ls -l
total 48
lrwxrwxrwx   1 root root    7 Nov  6 01:21 bin -> usr/bin
drwxr-xr-x   2 root root 4096 Apr 15  2020 boot
drwxr-xr-x   5 root root  360 Dec 17 09:40 dev
drwxr-xr-x   1 root root 4096 Dec 17 09:40 etc
drwxr-xr-x   2 root root 4096 Apr 15  2020 home
lrwxrwxrwx   1 root root    7 Nov  6 01:21 lib -> usr/lib
lrwxrwxrwx   1 root root    9 Nov  6 01:21 lib32 -> usr/lib32
lrwxrwxrwx   1 root root    9 Nov  6 01:21 lib64 -> usr/lib64
lrwxrwxrwx   1 root root   10 Nov  6 01:21 libx32 -> usr/libx32
drwxr-xr-x   2 root root 4096 Nov  6 01:21 media
drwxr-xr-x   2 root root 4096 Nov  6 01:21 mnt
drwxr-xr-x   2 root root 4096 Nov  6 01:21 opt
dr-xr-xr-x 157 root root    0 Dec 17 09:40 proc
drwx------   2 root root 4096 Nov  6 01:25 root
drwxr-xr-x   1 root root 4096 Nov 25 22:25 run
lrwxrwxrwx   1 root root    8 Nov  6 01:21 sbin -> usr/sbin
drwxr-xr-x   2 root root 4096 Nov  6 01:21 srv
dr-xr-xr-x  11 root root    0 Dec 15 03:37 sys
drwxrwxrwt   2 root root 4096 Nov  6 01:25 tmp
drwxr-xr-x   1 root root 4096 Nov  6 01:21 usr
drwxr-xr-x   1 root root 4096 Nov  6 01:25 var

整个运行的过程中,docker在后台运行的标准操作为:
·检查本地是否存在指定的镜像,不存在就从公有仓库下载;
·利用镜像创建一个容器,并启动该容器;
·分配一个文件系统给容器,并在只读的镜像层外面挂载一层可读写层;
·从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中去;
·从网桥的地址池配置一个IP地址给容器;
·执行用户指定的应用程序;
·执行完毕后容器被自动终止。

按Ctrl+d或输入exit命令来退出容器:

root@1ecb285a4509:/# exit
exit
  • 对于所创建的bash容器,当用户使用exit命令退出bash进程之后,容器也会自动退出

命令docker container wait CONTAINER [CONTAINER...]:Block until one or more containers stop, then print their exit codes

容器有时也会因命令无法正常执行而退出,默认情况下,常见错误代码包括:
·125:Docker daemon执行出错,例如指定了不支持的Docker命令参数;
·126:所指定命令无法执行,例如权限出错;
·127:容器内命令无法找到。

4.守护态运行

我们之前使用的带 -i 参数的run命令运行的都是交互模式的容器,而能长时间在后台稳定运行的容器就是守护式容器,即容器在后台以守护Daemonized形式运行,这需要使用 -d 参数。

xiaolu@DangFuLin:~$ docker run -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done"
078513b6383947292227d5bcdae6f6cfc960ab18e0215bf2487767513982063a

xiaolu@DangFuLin:~$ docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS          PORTS     NAMES
078513b63839   ubuntu          "/bin/sh -c 'while t…"   40 seconds ago   Up 39 seconds             interesting_solomon
2f4127e7e27d   ubuntu:latest   "/bin/bash"              3 hours ago      Up 3 hours                stupefied_hermann

5.查看容器输出

命令docker logs [OPTIONS] CONTAINER获取容器的输出信息。
其中OPTIONS

  • -f : 跟踪日志输出
  • –since :显示某个开始时间的所有日志
  • -t : 显示时间戳
  • –tail :仅列出最新N条容器日志
  • –details:打印详细信息
  • -until string:输出某个时间之前的日志
xiaolu@DangFuLin:~$ docker logs -f -t  c02432ad4a7e
2020-12-17T12:09:29.626258900Z hello world
2020-12-17T12:09:33.627488300Z hello world
2020-12-17T12:09:37.628312000Z hello world
2020-12-17T12:09:41.630218700Z hello world
2020-12-17T12:09:45.632400700Z hello world

二,停止容器

1.暂停容器

命令docker pause CONTAINER [CONTAINER...]

xiaolu@DangFuLin:~$ docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS          PORTS     NAMES
c02432ad4a7e   ubuntu          "/bin/sh -c 'while t…"   5 minutes ago    Up 5 minutes              suspicious_chatterjee
078513b63839   ubuntu          "/bin/sh -c 'while t…"   11 minutes ago   Up 11 minutes             interesting_solomon
2f4127e7e27d   ubuntu:latest   "/bin/bash"              3 hours ago      Up 3 hours                stupefied_hermann
xiaolu@DangFuLin:~$ docker pause 078513b63839
078513b63839
xiaolu@DangFuLin:~$ docker pause c02432ad4a7e
c02432ad4a7e
xiaolu@DangFuLin:~$ docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS                   PORTS     NAMES
c02432ad4a7e   ubuntu          "/bin/sh -c 'while t…"   6 minutes ago    Up 6 minutes (Paused)              suspicious_chatterjee
078513b63839   ubuntu          "/bin/sh -c 'while t…"   12 minutes ago   Up 12 minutes (Paused)             interesting_solomon
2f4127e7e27d   ubuntu:latest   "/bin/bash"              3 hours ago      Up 3 hours                         stupefied_hermann
  • status中显示处于paused,可用命令docker unpause CONTAINER[CONTAINER...]来恢复到运行状态

2.终止容器

命令docker stop [OPTIONS] CONTAINER [CONTAINER...]终止一个运行中的容器。

命令会首先向容器发送SIGTERM信号,等待一段超时时间后(默认为10秒),再发送SIGKILL信号来终止容器:

xiaolu@DangFuLin:~$ docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS                   PORTS     NAMES
c02432ad4a7e   ubuntu          "/bin/sh -c 'while t…"   10 minutes ago   Up 10 minutes (Paused)             suspicious_chatterjee
078513b63839   ubuntu          "/bin/sh -c 'while t…"   15 minutes ago   Up 15 minutes (Paused)             interesting_solomon
2f4127e7e27d   ubuntu:latest   "/bin/bash"              3 hours ago      Up 3 hours                         stupefied_hermann
xiaolu@DangFuLin:~$ docker stop c02432ad4a7e
c02432ad4a7e
xiaolu@DangFuLin:~$ docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS                   PORTS     NAMES
078513b63839   ubuntu          "/bin/sh -c 'while t…"   16 minutes ago   Up 16 minutes (Paused)             interesting_solomon
2f4127e7e27d   ubuntu:latest   "/bin/bash"              3 hours ago      Up 3 hours                         stupefied_hermann

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

xiaolu@DangFuLin:~$ docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
c02432ad4a7e51a8e0170d61d83a5948da4a10e60efd25de883eda7751892fd5
078513b6383947292227d5bcdae6f6cfc960ab18e0215bf2487767513982063a
1ecb285a450934a290b04838bcb7f98a83eaa5901cc08cbec1e8cbbe3b6e3e7b
189d32e822722b2f5efe683fed853275b6563325109ba63939a4d33b9905ef30

Total reclaimed space: 15B

命令docker kill [OPTIONS] CONTAINER [CONTAINER...]默认使用-s选项直接发送SIGKILL信号来强行终止容器。

而命令docker start [OPTIONS] CONTAINER [CONTAINER...]就可以用于重新启动处于终止状态的容器:

xiaolu@DangFuLin:~$ docker start ce554267d7a4
ce554267d7a4
xiaolu@DangFuLin:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ce554267d7a4 ubuntu:latest "/bin/sh -c 'while t 4 minutes ago Up 5 seconds determined_pike

命令docker restart [OPTIONS] CONTAINER [CONTAINER...]会将一个运行态的容器先终止,然后再重新启动。

三,进入容器

前面提到守护式容器是运行在后台的,但有时候还是需要进入容器进行操作。

1.attach命令

命令docker attach [OPTIONS] CONTAINER
其中OPTIONS

  • –detach-keys[=[]]:指定退出attach模式的快捷键序列,默认是CTRL-p CTRL-q;
  • –no-stdin=true|false:是否关闭标准输入,默认是保持打开;
  • –sig-proxy=true|false:是否代理收到的系统信号给应用进程,默认为true。
xiaolu@DangFuLin:~$ docker run -itd ubuntu:latest
f19849d8832768e6e22a39310dbf9ccba4deff6d8c6c1eb72fe3f7f90267d016
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED          STATUS          PORTS     NAMES
f19849d88327   ubuntu:latest   "/bin/bash"   47 seconds ago   Up 46 seconds             great_montalcini

xiaolu@DangFuLin:~$ docker attach f19849d88327
root@f19849d88327:/# echo "hello world!"
hello world!
root@f19849d88327:/# exit
exit

xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED         STATUS                     PORTS     NAMES
f19849d88327   ubuntu:latest   "/bin/bash"   2 minutes ago   Exited (0) 3 seconds ago             great_montalcini

当多个窗口同时attach到同一个容器的时候,所有窗口都会同步显示,如果某个窗口因命令阻塞,其他窗口也无法执行操作了。

2.exec命令

命令docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
其中OPTIONS

  • -d,–detach:在容器中后台执行命令;
  • –detach-keys="":指定将容器切回后台的按键;
  • -e,–env=[]:指定环境变量列表;
  • -i,–interactive=true|false:打开标准输入接受用户输入命令,默认值为false;
  • –privileged=true|false:是否给执行命令以高权限,默认值为false;
  • -t,–tty=true|false:分配伪终端,默认值为false;
  • -u,–user="":执行命令的用户名或ID。
xiaolu@DangFuLin:~$ docker start f19849d88327
f19849d88327
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED         STATUS         PORTS     NAMES
f19849d88327   ubuntu:latest   "/bin/bash"   7 minutes ago   Up 3 seconds             great_montalcini

xiaolu@DangFuLin:~$ docker exec -it f19849d88327 /bin/bash
root@f19849d88327:/# echo "I'm back!"
I'm back!
root@f19849d88327:/# exit
exit

四,删除容器

命令docker rm [OPTIONS] CONTAINER [CONTAINER...]用于删除容器。
其中OPTIONS

  • -f,–force=false:是否强行终止并删除一个运行中的容器;
  • -l,–link=false:删除容器的连接,但保留容器;
  • -v,–volumes=false:删除容器挂载的数据卷。
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED          STATUS          PORTS     NAMES
f19849d88327   ubuntu:latest   "/bin/bash"   25 minutes ago   Up 17 minutes             great_montalcini
xiaolu@DangFuLin:~$ docker stop f19849d88327
f19849d88327
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE           COMMAND       CREATED          STATUS                     PORTS     NAMES
f19849d88327   ubuntu:latest   "/bin/bash"   25 minutes ago   Exited (0) 2 seconds ago             great_montalcini
xiaolu@DangFuLin:~$ docker rm f19849d88327
f19849d88327
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

五,导入和导出容器

容器时镜像运行的实例,所以我们用多层镜像构建容器后,还需要再另一个系统中使用这个容器,就需要先将这个容器导出,再导入到目标系统。

1.导出容器

命令docker export [OPTIONS] file|URL|- [REPOSITORY[:TAG]]导出容器。
其中OPTIONS

  • -o, --output string Write to a file, instead of STDOUT
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
xiaolu@DangFuLin:~$ docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    f643c72bc252   3 weeks ago   72.9MB
xiaolu@DangFuLin:~$ docker run -it ubuntu /bin/bash
root@d382be03c37d:/# touch test
root@d382be03c37d:/# ls -l
total 48
lrwxrwxrwx   1 root root    7 Nov  6 01:21 bin -> usr/bin
drwxr-xr-x   2 root root 4096 Apr 15  2020 boot
drwxr-xr-x   5 root root  360 Dec 17 15:31 dev
drwxr-xr-x   1 root root 4096 Dec 17 15:31 etc
drwxr-xr-x   2 root root 4096 Apr 15  2020 home
lrwxrwxrwx   1 root root    7 Nov  6 01:21 lib -> usr/lib
lrwxrwxrwx   1 root root    9 Nov  6 01:21 lib32 -> usr/lib32
lrwxrwxrwx   1 root root    9 Nov  6 01:21 lib64 -> usr/lib64
lrwxrwxrwx   1 root root   10 Nov  6 01:21 libx32 -> usr/libx32
drwxr-xr-x   2 root root 4096 Nov  6 01:21 media
drwxr-xr-x   2 root root 4096 Nov  6 01:21 mnt
drwxr-xr-x   2 root root 4096 Nov  6 01:21 opt
dr-xr-xr-x 156 root root    0 Dec 17 15:31 proc
drwx------   2 root root 4096 Nov  6 01:25 root
drwxr-xr-x   1 root root 4096 Nov 25 22:25 run
lrwxrwxrwx   1 root root    8 Nov  6 01:21 sbin -> usr/sbin
drwxr-xr-x   2 root root 4096 Nov  6 01:21 srv
dr-xr-xr-x  11 root root    0 Dec 15 03:37 sys
-rw-r--r--   1 root root    0 Dec 17 15:31 test
drwxrwxrwt   2 root root 4096 Nov  6 01:25 tmp
drwxr-xr-x   1 root root 4096 Nov  6 01:21 usr
drwxr-xr-x   1 root root 4096 Nov  6 01:25 var
root@d382be03c37d:/# exit
exit
xiaolu@DangFuLin:~$ docker ps -as
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
d382be03c37d   ubuntu    "/bin/bash"   49 seconds ago   Exited (0) 6 seconds ago             distracted_hermann

xiaolu@DangFuLin:~$ docker export -o newubuntu.tar d382be03c37d
xiaolu@DangFuLin:~$ docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                     PORTS     NAMES
d382be03c37d   ubuntu    "/bin/bash"   3 minutes ago   Exited (0) 2 minutes ago             distracted_hermann

xiaolu@DangFuLin:~$ docker export -o newubuntu.tar d382be03c37d

xiaolu@DangFuLin:~$ ls -l
total 73520
-rw------- 1 xiaolu xiaolu 75280896 Dec 17 23:34 newubuntu.tar

2.导入容器

命令docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]导入一个容器快照到本地镜像库。
其中OPTIONS

  • -c, --change list Apply Dockerfile instruction to the created image
  • -m, --message string Set commit message for imported image --platform string Set platform if server is multi-platform capable

将刚刚导出的容器再导入:

xiaolu@DangFuLin:~$ docker import  newubuntu.tar nerubuntu
sha256:7566782e2e1b3024361c590b5570240422a10a146948862bb9b92220caf93022
xiaolu@DangFuLin:~$ docker images
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
nerubuntu    latest    7566782e2e1b   35 seconds ago   72.9MB
ubuntu       latest    f643c72bc252   3 weeks ago      72.9MB

导入后是镜像,再 run 或者 start 就行。

这似乎很眼熟? 是docker load命令?对,前者导入容器到本地镜像库同时容器快照文件将丢弃所有的历史记录和元数据信息,后者但如镜像到本地镜像库而镜像存储文件将保存完整记录,体积更大。

六,查看容器

1.查看容器详情

命令docker inspect [OPTIONS] NAME|ID [NAME|ID...]查看容器详情。

xiaolu@DangFuLin:~$ docker container inspect d382be03c37d
[
    {
        "Id": "d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1",
        "Created": "2020-12-17T15:31:00.047002Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-12-17T15:31:00.3573238Z",
            "FinishedAt": "2020-12-17T15:31:42.7408665Z"
        },
        "Image": "sha256:f643c72bc25212974c16f3348b3a898b1ec1eb13ec1539e10a103e6e217eb2f1",
        "ResolvConfPath": "/var/lib/docker/containers/d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1/hostname",
        "HostsPath": "/var/lib/docker/containers/d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1/hosts",
        "LogPath": "/var/lib/docker/containers/d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1/d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1-json.log",
        "Name": "/distracted_hermann",
        "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,
            "CgroupnsMode": "host",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "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,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "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/066c0b436495c1c6213351833a3306ca7ff7e6ebd91807f56334d07dafc9d38b-init/diff:/var/lib/docker/overlay2/50c844914759200ac411d7f83956bab11bc00be4c30d373049e8b6ce8f17b7f4/diff:/var/lib/docker/overlay2/373152b066ca40900221dd3e4af67e7e0482ac3b1db0e7a6c95890504c1ac3bf/diff:/var/lib/docker/overlay2/8387ac20796b0c6f48c758398a589fb0f42e54c1efb30a11d143776c34b7369d/diff",
                "MergedDir": "/var/lib/docker/overlay2/066c0b436495c1c6213351833a3306ca7ff7e6ebd91807f56334d07dafc9d38b/merged",
                "UpperDir": "/var/lib/docker/overlay2/066c0b436495c1c6213351833a3306ca7ff7e6ebd91807f56334d07dafc9d38b/diff",
                "WorkDir": "/var/lib/docker/overlay2/066c0b436495c1c6213351833a3306ca7ff7e6ebd91807f56334d07dafc9d38b/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d382be03c37d",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "ubuntu",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "c8d11227beb86f08988e1c51aa1fabe7eeadca61b223ae91398eaf2e5d1cee13",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/c8d11227beb8",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "295d7679580b737c9c73a399ad885f5a6263a0b8670a1420cb962997b2deebf5",
                    "EndpointID": "",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

2.查看容器内进程

命令docker top CONTAINER [ps OPTIONS]查看容器内进程。

xiaolu@DangFuLin:~$ docker container top d382be03c37d
Error response from daemon: Container d382be03c37dd603656942e6cea7178e1295ec5a418c01a841efa7bcc993dbb1 is not running
xiaolu@DangFuLin:~$ docker start d382be03c37d
d382be03c37d

xiaolu@DangFuLin:~$ docker container top d382be03c37d
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                15535               15513               0                   23:56               pts/0               00:00:00            /bin/bash

3.查看统计信息

命令docker stats [OPTIONS] [CONTAINER...]查看统计信息。
其中OPTIONS

  • -a,-all:输出所有容器统计信息,默认仅在运行中;
  • -format string:格式化输出信息;
  • -no-stream:不持续输出,默认会自动更新持续实时结果;
  • -no-trunc:不截断输出信息。
xiaolu@DangFuLin:~$ docker stats -a --no-stream
CONTAINER ID   NAME                 CPU %     MEM USAGE / LIMIT   MEM %     NET I/O   BLOCK I/O   PIDS
d382be03c37d   distracted_hermann   0.00%     0B / 0B             0.00%     0B / 0B   0B / 0B     0

七,其他容器命令

1.复制文件

命令docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH在容器和主机之间复制文件。
其中OPTIONS

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

将之前导出的容器文件从本地复制到容器中:

xiaolu@DangFuLin:~$ docker cp newubuntu.tar d382be03c37d:/tmp/

xiaolu@DangFuLin:~$ docker exec -it d382be03c37d /bin/bash
root@d382be03c37d:/# ls -l
total 48
lrwxrwxrwx   1 root root    7 Nov  6 01:21 bin -> usr/bin
drwxr-xr-x   2 root root 4096 Apr 15  2020 boot
drwxr-xr-x   5 root root  360 Dec 17 15:56 dev
drwxr-xr-x   1 root root 4096 Dec 17 15:31 etc
drwxr-xr-x   2 root root 4096 Apr 15  2020 home
lrwxrwxrwx   1 root root    7 Nov  6 01:21 lib -> usr/lib
lrwxrwxrwx   1 root root    9 Nov  6 01:21 lib32 -> usr/lib32
lrwxrwxrwx   1 root root    9 Nov  6 01:21 lib64 -> usr/lib64
lrwxrwxrwx   1 root root   10 Nov  6 01:21 libx32 -> usr/libx32
drwxr-xr-x   2 root root 4096 Nov  6 01:21 media
drwxr-xr-x   2 root root 4096 Nov  6 01:21 mnt
drwxr-xr-x   2 root root 4096 Nov  6 01:21 opt
dr-xr-xr-x 155 root root    0 Dec 17 15:56 proc
drwx------   1 root root 4096 Dec 17 15:31 root
drwxr-xr-x   1 root root 4096 Nov 25 22:25 run
lrwxrwxrwx   1 root root    8 Nov  6 01:21 sbin -> usr/sbin
drwxr-xr-x   2 root root 4096 Nov  6 01:21 srv
dr-xr-xr-x  11 root root    0 Dec 15 03:37 sys
-rw-r--r--   1 root root    0 Dec 17 15:31 test
drwxrwxrwt   1 root root 4096 Dec 17 16:08 tmp
drwxr-xr-x   1 root root 4096 Nov  6 01:21 usr
drwxr-xr-x   1 root root 4096 Nov  6 01:25 var
root@d382be03c37d:/# cd tmp
root@d382be03c37d:/tmp# ls -l
total 73520
-rw------- 1 1000 1000 75280896 Dec 17 15:34 newubuntu.tar

2.查看变更

命令dockers container diff查看容器内文件系统的变更。

xiaolu@DangFuLin:~$ docker container diff d382be03c37d
C /root
A /root/.bash_history
A /test
C /tmp
A /tmp/newubuntu.tar

3.查看端口映射

命令docker container port可以查看容器的端口映射情况。

xiaolu@DangFuLin:~$ docker container port test
9000/tcp -> 0.0.0.0:9000
  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值