【Docker】Container 常用命令

Posted by 西维蜀黍 on 2020-05-23, Last Modified on 2022-02-12

Docker 启动

Docker 是服务器—-客户端架构。命令行运行docker命令的时候,需要本机有 Docker 服务。如果这项服务没有启动,可以用下面的命令启动:

# service 命令的用法
$ sudo service docker start

# systemctl 命令的用法
$ sudo systemctl start docker

container 管理

查看当前 container - docker ps

# 查看当前运行的容器
$ docker ps
# 查看全部容器(包括曾经运行,但现在已经被停止的)
$ docker ps -a

启动已新建过的容器 - docker start

docker run命令是新建并启动容器,每运行一次,就会新建一个容器。同样的命令运行两次,就会生成两个一模一样的容器文件。如果希望重复使用已经创建过的容器(而不是再创建一个容器),就要使用docker start命令,它用来启动已经新建、但已经停止运行的容器。

  • 这意味着如果此前没有通过docker run 来新建,则无法通过 docker start 来启动。
$ docker start [containerID/container_name]

比如这里docker start -i ubuntu2docker start -i 9aaa62cc0621是完全等效的。

以交互模式启动(以当前bash作为该容器的bash):

$ docker start -i [containerID]

See https://docs.docker.com/engine/reference/commandline/start/

删除 container - docker rm

# 删除一个或多个容器。
$ docker rm [OPTIONS] containID [containID...]

停止运行 container - docker kill

对于那些不会自动终止的容器,必须使用手动终止。

# 杀掉一个运行中的容器
$ dokcer kill containID [containID...]
 
# 或者也可以使用
$ docker stop [containID]

两者的区别是:docker container kill命令终止容器运行,相当于向容器里面的主进程发出 SIGKILL 信号。而docker container stop命令也是用来终止容器运行,相当于向容器里面的主进程发出 SIGTERM 信号,然后过一段时间再发出 SIGKILL 信号。

应用程序收到 SIGTERM 信号以后,可以自行进行收尾清理工作,但也可以不理会这个信号。如果收到 SIGKILL 信号,就会强行立即终止,那些正在进行中的操作会全部丢失。

总结一句,docker container kill可以理解为强制结束容器(丢失全部正在进行的操作),而docker container stop会在保存完所有正在进行的操作后,再结束容器。

在 container 中执行命令 - docker exec

docker exec 命令用于进入一个正在运行的 Docker 容器,或者在容器内执行一个命令(在默认情况下,在执行完成后不继续停留在容器中)。

  • --user=<user>, --user=root
# 在特定容器执行 pwd,在执行完成后不继续停留在容器中
$ docker container exec [containerID] pwd

# e.g.,
$ docker container exec 4acf9613dfa5 pwd
/var/www/html

因为,如果在通过 docker run命令新建容器的时候,没有使用-it参数,则新建容器后,就不会停留在改容器的shell (而且,在不加任何参数的情况下,容器会直接退出)。

因此,如果希望进入容器的shell,需要先将容器启动起来,否则 docker exec 会失败。

# 当前并没有任何正在运行的容器
$ docker ps -a
CONTAINER ID   IMAGE                                 COMMAND       CREATED              STATUS                          PORTS     NAMES
ca04f7c95fea   ubuntu                                "/bin/bash"   About a minute ago   Exited (0) About a minute ago             bold_khayyam

$ docker exec ca04f7c95fea pwd
Error response from daemon: Container ca04f7c95fea07ad5b7d93351a208eff1c817031ae28bc9d543bd57a67578a37 is not running

进入正在运行的container shell

$ docker ps -a
CONTAINER ID   IMAGE                                 COMMAND    CREATED          STATUS                     PORTS     NAMES
d73e96d5ec37   homeassistant/home-assistant:stable   "/init"    25 minutes ago   Up 25 minutes                        homeassistant

$ docker exec -it homeassistant bash
bash-5.0#

See https://docs.docker.com/engine/reference/commandline/exec/ for details.

docker logs

Fetch the logs of a container

The docker logs --follow command will continue streaming the new output from the container’s STDOUT and STDERR.

docker stats

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

Column name Description
CONTAINER ID and Name the ID and name of the container
CPU % and MEM % the percentage of the host’s CPU and memory the container is using
MEM USAGE / LIMIT the total memory the container is using, and the total amount of memory it is allowed to use
NET I/O The amount of data the container has sent and received over its network interface
BLOCK I/O The amount of data the container has read to and written from block devices on the host
PIDs the number of processes or threads the container has created

Running docker stats on all running containers against a Linux daemon.

$ docker stats

CONTAINER ID        NAME                                    CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
b95a83497c91        awesome_brattain                        0.28%               5.629MiB / 1.952GiB   0.28%               916B / 0B           147kB / 0B          9
67b2525d8ad1        foobar                                  0.00%               1.727MiB / 1.952GiB   0.09%               2.48kB / 0B         4.11MB / 0B         2
e5c383697914        test-1951.1.kay7x1lh1twk9c0oig50sd5tr   0.00%               196KiB / 1.952GiB     0.01%               71.2kB / 0B         770kB / 0B          1
4bda148efbc0        random.1.vnc8on831idyr42slu578u3cr      0.00%               1.672MiB / 1.952GiB   0.08%               110kB / 0B          578kB / 0B          2

$ docker stats [<container_id>]

docker inspect

Return low-level information on Docker objects

Usage

$ docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Get an instance’s IP address

For the most part, you can pick out any field from the JSON in a fairly straightforward manner.

$ docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $INSTANCE_ID

Get an instance’s MAC address

$ docker inspect --format='{{range .NetworkSettings.Networks}}{{.MacAddress}}{{end}}' $INSTANCE_ID

Get an instance’s log path

$ docker inspect --format='{{.LogPath}}' $INSTANCE_ID

Get an instance’s image name

$ docker inspect --format='{{.Config.Image}}' $INSTANCE_ID

List all port bindings

You can loop over arrays and maps in the results to produce simple text output:

$ docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' $INSTANCE_ID

Find a specific port mapping

The .Field syntax doesn’t work when the field name begins with a number, but the template language’s index function does. The .NetworkSettings.Ports section contains a map of the internal port mappings to a list of external address/port objects. To grab just the numeric public port, you use index to find the specific port map, and then index 0 contains the first object inside of that. Then we ask for the HostPort field to get the public address.

$ docker inspect --format='{{(index (index .NetworkSettings.Ports "8787/tcp") 0).HostPort}}' $INSTANCE_ID
$ docker inspect 0cc7ee926183
[
    {
        "Id": "0cc7ee92618327fd86dca63d1f5bfc05ab94a6a3949aeaa4c6c7d4384e26ac1f",
        "Created": "2021-08-11T15:21:55.289699141Z",
        "Path": "/init",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 15273,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-08-11T15:21:55.624956864Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:bb5991beae34e028b73c8385d0071e82efdb9f5ab71292e974a59f491627f956",
        "ResolvConfPath": "/var/lib/docker/containers/0cc7ee92618327fd86dca63d1f5bfc05ab94a6a3949aeaa4c6c7d4384e26ac1f/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/0cc7ee92618327fd86dca63d1f5bfc05ab94a6a3949aeaa4c6c7d4384e26ac1f/hostname",
        "HostsPath": "/var/lib/docker/containers/0cc7ee92618327fd86dca63d1f5bfc05ab94a6a3949aeaa4c6c7d4384e26ac1f/hosts",
        "LogPath": "/var/lib/docker/containers/0cc7ee92618327fd86dca63d1f5bfc05ab94a6a3949aeaa4c6c7d4384e26ac1f/0cc7ee92618327fd86dca63d1f5bfc05ab94a6a3949aeaa4c6c7d4384e26ac1f-json.log",
        "Name": "/homeassistant",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": [
            "0c5a80e63dfed8c73f27f2356f273bf4b2281cc5f92c50b879a6980a2411ca5a"
        ],
        "HostConfig": {
            "Binds": [
                "/etc/localtime:/etc/localtime:ro",
                "/home/sw/ha_config:/config"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "host",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "unless-stopped",
                "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"
            ],
            "Init": true
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/9654b766e57d0ab508bae2ec8ad332481b84dd3b25f36b61c6b4385f129189ff-init/diff:/var/lib/docker/overlay2/fb405d381d0cf165d349eac3aa161ab2a37244f9c17a550e13fc9d7577f8bc9b/diff:/var/lib/docker/overlay2/59e940bcbc1dd11a318a6cd75d7ed7dac6a57f61388d95768e6e86b3bfeb8e8b/diff:/var/lib/docker/overlay2/4c6125640ffb5264fa0c8e449edfdf91d83b2f24954a72a853e35a67a2415c7c/diff:/var/lib/docker/overlay2/10a9e1dc33ce636dcf890bdd71b169052f19b979172be9a22a0bcac1b907a943/diff:/var/lib/docker/overlay2/4a29ff493bbff71c043b31599f99850614c47a9cb3a573bce90afc50367c1c8f/diff:/var/lib/docker/overlay2/bb42f17f66a7308ededefcc32314f431f889d902f606f731d4e0cd552201473f/diff:/var/lib/docker/overlay2/c579126460d037ede4a6c9addfa9d12bf0a498e7127c2d666d473a4df83fd94b/diff:/var/lib/docker/overlay2/4e06b38b95e5771b3a3383671e738a07af0105c7e33c9fc3312baf9cff646b16/diff:/var/lib/docker/overlay2/bc3018e91a94a05d5ab1c754c1236e780b1378ae101f9c54c34534802718fe81/diff:/var/lib/docker/overlay2/a5d83954c59663471f4662b5f9ad23bb1f36c40252799f3ddb49a75fca273b0b/diff:/var/lib/docker/overlay2/4db6198a899c35fef2aae9cf9558adf4deba26a71682abef6f3e5c636d44aac3/diff:/var/lib/docker/overlay2/f234006b9e73c57d51f49728f1e9da78840f9931bd7c73746fd14ce8fd29fef5/diff:/var/lib/docker/overlay2/b91f7ed1a2a8e1c73d7a510db207433786e661d474be76ecb0bdd752e60c7137/diff:/var/lib/docker/overlay2/02b6afc7905e00fc88cecc0b39c65947807b612e777a35339b470ccf0d6b61ed/diff:/var/lib/docker/overlay2/afe988f97a291f0a0ac7c2b9520534755514807cd526d244a8e3003915c8473e/diff:/var/lib/docker/overlay2/58b571501bf9502ffd67932fc45a8f2efa7f3f447c4426a1b95f27c4c987b5dc/diff:/var/lib/docker/overlay2/30c6497f6e49ef71a18090dd71d5df4f33177288cc1fffd55668b8649e13c52a/diff:/var/lib/docker/overlay2/3f8cfba48bd0c6104d4ceeb78f3f805cf364e13e990f15f5312d441686239050/diff:/var/lib/docker/overlay2/a7595bf9cfb2e7e6c1838e57ff61a2d2e8218b292ce5d132cf59fdf6a3a55e5a/diff:/var/lib/docker/overlay2/d24c3a397e15eddea3fc0a8ad53b6b4e9da3545be8048c82777cffe8c6426a86/diff:/var/lib/docker/overlay2/9f6c5b7cc32a91a5180d44c83119255459062604b7b8924cf4cda0c2bce50157/diff",
                "MergedDir": "/var/lib/docker/overlay2/9654b766e57d0ab508bae2ec8ad332481b84dd3b25f36b61c6b4385f129189ff/merged",
                "UpperDir": "/var/lib/docker/overlay2/9654b766e57d0ab508bae2ec8ad332481b84dd3b25f36b61c6b4385f129189ff/diff",
                "WorkDir": "/var/lib/docker/overlay2/9654b766e57d0ab508bae2ec8ad332481b84dd3b25f36b61c6b4385f129189ff/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/etc/localtime",
                "Destination": "/etc/localtime",
                "Mode": "ro",
                "RW": false,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/home/sw/ha_config",
                "Destination": "/config",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "Truenasubuntusw",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "LANG=C.UTF-8",
                "S6_BEHAVIOUR_IF_STAGE2_FAILS=2",
                "S6_CMD_WAIT_FOR_SERVICES=1",
                "WHEELS_LINKS=https://wheels.home-assistant.io/alpine-3.13/amd64/",
                "S6_SERVICES_GRACETIME=220000"
            ],
            "Cmd": null,
            "Image": "homeassistant/home-assistant:stable",
            "Volumes": null,
            "WorkingDir": "/config",
            "Entrypoint": [
                "/init"
            ],
            "OnBuild": null,
            "Labels": {
                "io.hass.arch": "amd64",
                "io.hass.base.arch": "amd64",
                "io.hass.base.image": "homeassistant/amd64-base:3.13",
                "io.hass.base.name": "python",
                "io.hass.base.version": "2021.07.1",
                "io.hass.type": "core",
                "io.hass.version": "2021.8.6",
                "org.opencontainers.image.authors": "The Home Assistant Authors",
                "org.opencontainers.image.created": "2021-08-11 04:08:24+00:00",
                "org.opencontainers.image.description": "Open-source home automation platform running on Python 3",
                "org.opencontainers.image.documentation": "https://www.home-assistant.io/docs/",
                "org.opencontainers.image.licenses": "Apache License 2.0",
                "org.opencontainers.image.source": "https://github.com/home-assistant/core",
                "org.opencontainers.image.title": "Home Assistant",
                "org.opencontainers.image.url": "https://www.home-assistant.io/",
                "org.opencontainers.image.version": "2021.8.6"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "4d0e1a18b4e83b8dc61019b3000884628e06c362bac7407e236f07c7799a6af3",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/default",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "host": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "87b0d2a3b19b24dd93ce8342657d213fd64831eae38935cb62d3f98e62c73478",
                    "EndpointID": "dea5a15a876dfd2bf2c2755161e49c5562fc9f26daaba24a379a124adee2c4ab",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

Refer to https://docs.docker.com/engine/reference/commandline/inspect/

docker history

$ docker history 9dfc442be98c
IMAGE          CREATED        CREATED BY                                      SIZE      COMMENT
9dfc442be98c   5 weeks ago    /bin/sh -c #(nop)  CMD ["--config.file=/etc/…   0B
<missing>      5 weeks ago    /bin/sh -c #(nop)  ENTRYPOINT ["/bin/prometh…   0B
<missing>      5 weeks ago    /bin/sh -c #(nop) WORKDIR /prometheus           0B
<missing>      5 weeks ago    /bin/sh -c #(nop)  VOLUME [/prometheus]         0B
<missing>      5 weeks ago    /bin/sh -c #(nop)  EXPOSE 9090                  0B
<missing>      5 weeks ago    /bin/sh -c #(nop)  USER nobody                  0B
<missing>      5 weeks ago    |2 ARCH=amd64 OS=linux /bin/sh -c mkdir -p /…   996B
<missing>      5 weeks ago    |2 ARCH=amd64 OS=linux /bin/sh -c ln -s /usr…   70B
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY file:08342a6c25db256a…   129kB
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY file:e56be853b56584e3…   3.65kB
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY file:141c5dcfe0148c05…   11.4kB
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY dir:fb3645c7e168b5a4c…   19.5kB
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY dir:6111a57e3d623c34c…   9.04kB
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY file:5c98bdcb5916b0c8…   926B
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY file:e68620d8d025896c…   87.5MB
<missing>      5 weeks ago    /bin/sh -c #(nop) COPY file:5992df8e3ff851fc…   98.5MB
<missing>      5 weeks ago    /bin/sh -c #(nop)  ARG OS=linux                 0B
<missing>      5 weeks ago    /bin/sh -c #(nop)  ARG ARCH=amd64               0B
<missing>      5 weeks ago    /bin/sh -c #(nop)  LABEL maintainer=The Prom…   0B
<missing>      3 months ago   /bin/sh -c #(nop) COPY dir:bb5589ed25434b0b5…   1.44MB
<missing>      3 months ago   /bin/sh -c #(nop)  MAINTAINER The Prometheus…   0B
<missing>      3 months ago   /bin/sh -c #(nop)  CMD ["sh"]                   0B
<missing>      3 months ago   /bin/sh -c #(nop) ADD file:dc794c2febce9ec5b…   1.24MB

Container 管理 Misc

文件管理

上传文件

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

比如,docker cp /root/test.txt ecef8319d2c8:/root/的意思是将当前操作系统(CentOS)家目录(root)下的文件test.txt拷贝到容器id为ecef8319d2c8的家目录(root)文件夹下。

下载文件

$ docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH

比如docker cp ecef8319d2c8:/root/test.txt /root/

共享文件

在Docker和宿主机之间共享文件:

$ docker run -it -v [宿主机文件夹]:[Dokcer中的目标文件夹] [image源] /bin/bash

比如docker run -it -v /Users/weishi/Downloads/:/share ubuntu /bin/bash,就将宿主机下的/Users/weishi/Downloads/关联到Docker容器中的/share了。

资源使用管理

查看docker容器CPU、内存、网络使用情况

$ docker stats

查看docker镜像和容器磁盘使用情况

By default the command will just show a summary of the data used:

$ docker system df

TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              5                   2                   16.43 MB            11.63 MB (70%)
Containers          2                   0                   212 B               212 B (100%)
Local Volumes       2                   1                   36 B                0 B (0%)

A more detailed view can be requested using the -v, --verbose flag:

$ docker system df -v

Images space usage:

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE                SHARED SIZE         UNIQUE SIZE         CONTAINERS
my-curl             latest              b2789dd875bf        6 minutes ago       11 MB               11 MB               5 B                 0
my-jq               latest              ae67841be6d0        6 minutes ago       9.623 MB            8.991 MB            632.1 kB            0
<none>              <none>              a0971c4015c1        6 minutes ago       11 MB               11 MB               0 B                 0
alpine              latest              4e38e38c8ce0        9 weeks ago         4.799 MB            0 B                 4.799 MB            1
alpine              3.3                 47cf20d8c26c        9 weeks ago         4.797 MB            4.797 MB            0 B                 1

Containers space usage:

CONTAINER ID        IMAGE               COMMAND             LOCAL VOLUMES       SIZE                CREATED             STATUS                      NAMES
4a7f7eebae0f        alpine:latest       "sh"                1                   0 B                 16 minutes ago      Exited (0) 5 minutes ago    hopeful_yalow
f98f9c2aa1ea        alpine:3.3          "sh"                1                   212 B               16 minutes ago      Exited (0) 48 seconds ago   anon-vol

Local Volumes space usage:

NAME                                                               LINKS               SIZE
07c7bdf3e34ab76d921894c2b834f073721fccfbbcba792aa7648e3a7a664c2e   2                   36 B
my-named-vol                                                       0                   0 B
  • SHARED SIZE is the amount of space that an image shares with another one (i.e. their common data)
  • UNIQUE SIZE is the amount of space that is only used by a given image
  • SIZE is the virtual size of the image, it is the sum of SHARED SIZE and UNIQUE SIZE

设置 Container 自动启动

To configure the restart policy for a container, use the --restart flag when using the docker run command. The value of the --restart flag can be any of the following:

Flag Description
no Do not automatically restart the container. (the default)
on-failure Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

The following example starts a Redis container and configures it to always restart unless it is explicitly stopped or Docker is restarted.

$ docker run -d --restart unless-stopped redis

This command changes the restart policy for an already running container named redis.

$ docker update --restart unless-stopped redis

And this command will ensure all currently running containers will be restarted unless stopped.

$ docker update --restart unless-stopped $(docker ps -q)

网络管理

Refer to https://swsmile.info/post/docker-container-network/

View Docker Events - docker events

Use docker events to get real-time events from the server. These events differ per Docker object type. Different event types have different scopes. Local scoped events are only seen on the node they take place on, and swarm scoped events are seen on all managers.

Only the last 1000 log events are returned. You can use filters to further limit the number of events returned.

Example

You’ll need two shells for this example.

Shell 1: Listening for events:

$ docker events

Shell 2: Start and Stop containers:

$ docker create --name test alpine:latest top
$ docker start test
$ docker stop test

Shell 1: (Again .. now showing events):

2017-01-05T00:35:58.859401177+08:00 container create 0fdb48addc82871eb34eb23a847cfd033dedd1a0a37bef2e6d9eb3870fc7ff37 (image=alpine:latest, name=test)
2017-01-05T00:36:04.703631903+08:00 network connect e2e1f5ceda09d4300f3a846f0acfaa9a8bb0d89e775eb744c5acecd60e0529e2 (container=0fdb...ff37, name=bridge, type=bridge)
2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)

To exit the docker events command, use CTRL+C.

Ref https://docs.docker.com/engine/reference/commandline/events/

Reference