深入了解Docker(2) - Cli命令1

目录

深入了解Docker(1) 环境搭建
深入了解Docker(2) - Cli命令1
深入了解Docker(3) - Cli命令2

第二章 Docker 操作命令

2.1 常用命令

2.1.1 attach

将当前Docker Clinet所在 tty 终端上的 stdin、stdout、stderr(或这三者的任意组合),连接到正在运行的容器。这样,就好像直接在容器中执行命令一样。查看官网文档

# docker run -d --name topdemo ubuntu /usr/bin/top -b
# docker attach --sig-proxy=false topdemo
# docker rm -f topdemo
  • 下载镜像 ubuntu ,命名为topdemo,并以-d后台方式运行。为防止容器运行完毕退出,以批处理方式执行top -b命令。
  • 使用 attach 命令,连接到正在运行的容器。
  • 使用 rm -f 命令,强制删除正在运行的容器topdemo

小技巧:top -b 命令能够执行top的batch模式,在此模式下可以不和tty绑定。

查看镜像列表,发现已经增加了一个 ubuntu 镜像:

# docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              1d622ef86b13        5 weeks ago         73.9MB
hello-world         latest              bf756fb1ae65        4 months ago        13.3kB

# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
d707c8af6864        ubuntu              "/usr/bin/top -b"   5 minutes ago       Exited (0) 4 minutes ago                       topdemo
19f4db6db14f        hello-world         "/hello"            14 hours ago        Exited (0) 14 hours ago                        magical_almeida
9cee21753a37        hello-world         "/hello"            14 hours ago        Exited (0) 14 hours ago                        amazing_galois

小技巧:使用--sig-proxy=false参数,防止用Ctrl-C退出时容器随之停止。

代理信号选项(--sig-proxy),设置attach命令是否代理信号给容器。

当使用attach连接到容器时,如果按下了CTRL-c组合键,那么将发送SIGKILL信号到容器(可以参考docker kill命令),将造成容器退出。可以使用--sig-proxy参数(默认值为true),将这个参数值设置为false,使attach命令不再代理信号给容器。

如果容器是使用-it选项启动的,那就可以使用CTRL-p CTRL-q按键序列,断开这次连接而不发送信号,使容器继续保持运行状态。

重定义分离组合键(--detach-keys="<sequence>")选项。当容器内运行的应用使用的功能组合键,和attach命令定义的几个组合键冲突时,可以使用这个选项重定义组合键。

注意 rm、rmi命令的差异

  rm          Remove one or more containers
  rmi         Remove one or more images

2.1.2 cp

用于容器和主机之间的文件和目录的双向传输 官网介绍

语法:

# 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)<br>
                    归档模式(复制所有UID / GID信息)
-L, --follow-link   Always follow symbol link in SRC_PATH
                    总是跟在源地址符号链接
  • docker cp命令类似于UNIX中的cp -a选项,递归复制目录下的所有子目录和文件,文件的所有者设置为目标的用户和组。
  • 被操作的容器可以是在运行状态,也可以是停止状态
  • 不能复制/proc, /sys, /dev, tmpfs和容器中mount的路径下的文件
  • -表示通过标准输入/输出设备以流的方式读取或写入tar文件

举例:

将主机/www/runoob目录拷贝到容器96f7f14e99ab的/www目录下。

docker cp /www/runoob 96f7f14e99ab:/www/

将主机/www/runoob目录拷贝到容器96f7f14e99ab中,目录重命名为www。

docker cp /www/runoob 96f7f14e99ab:/www

将容器96f7f14e99ab的/www目录拷贝到主机的/tmp目录中。

docker cp  96f7f14e99ab:/www /tmp/

docker cp 命令,符合 linux cp 命令的操作经验。如复制到容器的一个不存在的目录下,也会报错:

# docker cp /tmp/ttt/111 ubuntu:/tmp/ttt/
no such directory

docker cp命令复制SRC_PATH的内容到DEST_PATH。如果SRC_PATH或DEST_PATH指定了破折号-,可以从STDIN读取tar归档文件或输出到STDOUT。例如:

[root@51yunwei ~]# docker cp /tmp/ttt/111 ubuntu:/tmp/a.txt
[root@51yunwei ~]# docker cp ubuntu:/tmp/a.txt - >/tmp/1.tar
[root@51yunwei ~]# tar tvf /tmp/1.tar
-rw-r--r-- 0/0            1055 2020-05-31 22:55 a.txt

docker cp 命令是一个重要的容器操作命令,因此cp命令的安全问题是值得额外关注的。更多内容,请参考 这篇文章

2.1.3 create

docker create 命令,以image为模板,创建容器但不启动。create时,在容器的最上层添加一个读写层,以保存容器的所有数据变化。也就是说,docker create命令干的活比较少,主要是准备container的layer和配置文件,以备容器启动所需。官网介绍

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)
        I/O阻塞权重
      --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的时间长度(微秒)
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
        容器每次被CPU调度时的权重
      --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)
        容器运行在哪几个CPU
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
      --device list                    Add a host device to the container
        JSON格式,用于将主机设备挂载到容器中
      --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
      --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

Create命令是用来创建和初始化容器的,所以有很多选项。常用的有如下几个:

-i, --interactive                    Keep STDIN open even if not attached
    将host的stdin和容器的stdin相连。通常情况下,-t和-i是配合使用的
-p, --publish list                   Publish a container's port(s) to the host
    把容器的端口映射到主机端口上
-P, --publish-all                    Publish all exposed ports to random ports
    容器需要暴露的端口会映射到主机一个随机端口上(49153-65535),之后可以使用docker port查看端口
-v, --volume list                    Bind mount a volume
    将主机的文件或目录挂载到容器中

--name string                    Assign a name to the container
    给容器命名
$ docker create -v /tmp/111:/tmp/ttt --name demo ubuntu

关于create、run这类容器命令,后面会有专门的章节,结合容器安全、网络、资源限制等内容,进行综合讲解。官网介绍

2.1.4 diff

查看容器不同层数据的差异。此命令没有选项。

符号 描述
A 创建了文件或目录
D 删除了文件或目录
C 修改了文件或目录
# docker diff ubuntu
C /tmp
A /tmp/a.txt
C /root
A /root/.bash_history

2.1.5 events

容器运行时,尤其是以-d方式后台运行时,我们难以得知容器内部运行情况。Docker提供了三种方式查看,分别是:

  • 挂载(attach)
  • 日志(logs)
  • 事件(events)

events就是获取容器报告的事件。查看官网文档

  • Docker容器向Docker Daemin报告事件:
    attach, commit, copy, create, destroy, detach, die, exec_create, exec_detach, exec_start, export, health_status, kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update
  • Docker镜像报告如下事件:delete, import, load, pull, push, save, tag, untag
  • Docker数据卷报告如下事件:create, mount, unmount, destroy
  • Docker网络报告如下事件:create, connect, disconnect, destroy
  • Docker daemon报告如下事件:reload
[root@51yunwei ~]# docker events --help

Usage:  docker events [OPTIONS]
Get real time events from the server 从服务器获取实时事件

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Format the output using the given Go template
      --since string    Show all events created since timestamp
      --until string    Stream events until this timestamp

--filter 选项接收key=value这样的形式,目前支持:
container (container=) event (event=) image (image=) plugin (experimental) (plugin=) label (label= or label==) type (type=) volume (volume=) network (network=) daemon (daemon=)

--since 选项除了接受Unix时间戳,也可以接受RFC3339规定的格式。从Docker1.8之后,也支持-10m, 1h30m这样的Go duration时间表达式。

例子:

[root@51yunwei ~]# docker events --since '2020-06-06' --until '1h'
2020-06-06T11:25:00.843043072+08:00 container create 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (image=ubuntu, name=ubuntu)
2020-06-06T11:25:00.959641717+08:00 network connect e333859e7adf0f72e473d0dfd22db7c74a8d975eab15da0931520023e4c8894e (container=03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8, name=bridge, type=bridge)
2020-06-06T11:25:01.586802990+08:00 container start 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (image=ubuntu, name=ubuntu)
2020-06-06T11:26:45.329491141+08:00 container exec_create: /bin/bash  03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=11c60dab0d4dc64c42e2736ad13c5bcb1b35b4a6e0aca5fdb34278acb913163b, image=ubuntu, name=ubuntu)
2020-06-06T11:26:45.330006863+08:00 container exec_start: /bin/bash  03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=11c60dab0d4dc64c42e2736ad13c5bcb1b35b4a6e0aca5fdb34278acb913163b, image=ubuntu, name=ubuntu)
2020-06-06T11:26:58.551552382+08:00 container exec_die 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=11c60dab0d4dc64c42e2736ad13c5bcb1b35b4a6e0aca5fdb34278acb913163b, exitCode=0, image=ubuntu, name=ubuntu)
2020-06-06T11:31:28.686457564+08:00 container extract-to-dir 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (image=ubuntu, name=ubuntu)
2020-06-06T11:31:53.648076154+08:00 container exec_create: /bin/bash  03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=f76dcb2b0049af57476568b289d584fef040995c91c55d375860240f52c6bad9, image=ubuntu, name=ubuntu)
2020-06-06T11:31:53.648440299+08:00 container exec_start: /bin/bash  03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=f76dcb2b0049af57476568b289d584fef040995c91c55d375860240f52c6bad9, image=ubuntu, name=ubuntu)
2020-06-06T11:32:49.966793668+08:00 container exec_die 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=f76dcb2b0049af57476568b289d584fef040995c91c55d375860240f52c6bad9, exitCode=0, image=ubuntu, name=ubuntu)
2020-06-06T11:33:21.410475774+08:00 container extract-to-dir 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (image=ubuntu, name=ubuntu)
2020-06-06T11:33:26.392194766+08:00 container exec_create: /bin/bash  03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=59679a87b775e5393284f08f413ffea371709f29ec31d3d2e18053d3776281de, image=ubuntu, name=ubuntu)
2020-06-06T11:33:26.392513681+08:00 container exec_start: /bin/bash  03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=59679a87b775e5393284f08f413ffea371709f29ec31d3d2e18053d3776281de, image=ubuntu, name=ubuntu)
2020-06-06T11:33:57.556935518+08:00 container exec_die 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (execID=59679a87b775e5393284f08f413ffea371709f29ec31d3d2e18053d3776281de, exitCode=0, image=ubuntu, name=ubuntu)
2020-06-06T12:01:59.651466865+08:00 container extract-to-dir 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (image=ubuntu, name=ubuntu)
2020-06-06T12:02:25.758208565+08:00 container archive-path 03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8 (image=ubuntu, name=ubuntu)
[root@51yunwei ~]# docker events --since '2020-06-01T00:00' --until '2020-06-01T23:59' -f 'event=kill'
2020-06-01T00:01:02.351941973+08:00 container kill fd8612fc14e2193cc99baa53d2f9575b1f824d01b9926427565eb44fe05175d0 (image=ubuntu, name=topdemo, signal=2)
2020-06-01T00:11:15.877200815+08:00 container kill ed114953a1486dbbf8b46b3c5c6e83305e28b628074a3e14712a5e7e7e04829c (image=ubuntu, name=topdemo, signal=9)
[root@51yunwei ~]# docker events --since '2020-06-01' --until '1h' -f 'event=kill'
2020-06-01T00:01:02.351941973+08:00 container kill fd8612fc14e2193cc99baa53d2f9575b1f824d01b9926427565eb44fe05175d0 (image=ubuntu, name=topdemo, signal=2)
2020-06-01T00:11:15.877200815+08:00 container kill ed114953a1486dbbf8b46b3c5c6e83305e28b628074a3e14712a5e7e7e04829c (image=ubuntu, name=topdemo, signal=9)

--format 是新增加的选项,使用这个选项可以指定一个Golang模板替代默认输出格式。如果格式串制定为{{json .}},则输出一个标准的json串,这将有利于后续处理,例如将输出采集到ElasticSearch集群中进行分析处理。

[root@51yunwei ~]# docker events --since '2020-06-06' --until '1h' --format '{{json .}}' | jq
{
  "status": "create",
  "id": "03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8",
  "from": "ubuntu",
  "Type": "container",
  "Action": "create",
  "Actor": {
    "ID": "03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8",
    "Attributes": {
      "image": "ubuntu",
      "name": "ubuntu"
    }
  },
  "scope": "local",
  "time": 1591413900,
  "timeNano": 1591413900843043000
}
{
  "Type": "network",
  "Action": "connect",
  "Actor": {
    "ID": "e333859e7adf0f72e473d0dfd22db7c74a8d975eab15da0931520023e4c8894e",
    "Attributes": {
      "container": "03b22680693f62416d436d76a51991621c2a05a02ff3e790866c417c294f48a8",
      "name": "bridge",
      "type": "bridge"
    }
  },
  "scope": "local",
  "time": 1591413900,
  "timeNano": 1591413900959641600
}
......
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269