author: aming
email: jikcheng@163.com
title: 操作Docker 容器
creation_date: 2023-02-03 09:42
Last modified date: 2023-02-06 20:04
tags: 操作Docker 容器
File Folder with relative path: reading notes/doc/Docker技术入门与实战
remark:
other:
本章背景知识
1、容器是镜像的一个运行实例。
2、容器和镜像不同的是,镜像是静态的只读文件,而容器带有运行时需要的可写文件层。
3、容器和虚拟机不同的是,容器是独立运行的一个 (或一组) 应用。以及必须的运行环境。
本章主要介绍容器重要操作,包括创建容器、启动容器、终止一个容器、进入容器内执行操作、删除容器和导入导出容器实现容器迁移等。
docker create 命令
1、概述。
docker create
命令用于新建一个容器, 但是不会运行它。
2、语法大纲。
$ 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
--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
3、参数简介。
Create 命令与容器运行模式相关的选项
参数 | 说明 | |
---|---|---|
-a,–attach=[] | 是否绑定到标准输入、输出和错误。 | |
-d,–detach=true\false | 是否在后台运行容器,默认为否。 | |
–detach-keys=“” | 从 attach 模式退出的快捷键。 | |
–entrypoint=“” | 镜像存储在入口命令时,会覆盖为新的命令。 | |
–expose=[] | 指定容器会暴露出来的端口或端口范围。 | |
–group-add=[] | 运行容器的用户组。 | |
-i,–interactive=true/flase | 保持标准输入打开,默认为 false。 | |
–ipc=“” | 容器 IPC 命令空间,可以为其他容器或主机。 | |
–isolation=“default” | 容器使用的隔离机制。 | |
–log-driver=“json-file” | 指定容器的日志启动类型,可以为 json-file、syslog、journald、gelf、fluentd、awslogs、splunk、etwlogs、gcplogs 或 none。 | |
–log-opt=[] | 传递给日志驱动的选项。 | |
–net=“bridge” | 指定容器的网络模式,包括 bridge、none、其他容器内网络、host 的网络或者某个现有网络等。 | |
–net-alias=[] | 容器在网络中的别名。 | |
-P,–publish-all=true/false | 通过 NAT 机制将容器标记暴露的端口自动映射到本地的临时端口。 | |
-p,–publish=[] | 指定如何映射到本地主机端口,例如-p 11234-12234; 1234-2234 。 | |
–pid=host | 容器的 PID 命名空间。 | |
–userns=“” | 启用 userns-remap 时配置用户命名空间的模式。 | |
–uts=host | 容器的 PID 命名空间。 | |
–restart=“no” | 容器的重启策略,包括 no、on-faulure[: max-retry]、always、unless-stopped 等。 | |
–rm=true\false | 容器退出后是否自动删除,不能跟-d 同时使用。 | |
–tmpfs=[] | 挂载临时文件系统到容器。 | |
-v,–volume[= [[HOST-DIR:]]] | 挂载主机上的文件卷到容器内。 | |
–volume-driver=“” | 挂载文件卷的驱动类型。 | |
–volumes-from=[] | 从其他容器挂载卷。 | |
-w,–workdir=“” | 容器内的默认工作目录。 | |
编者注:restart 参数。 |
参数 | 说明 |
---|---|
on-faulure[: max-retry] | 表示容器的退出状态码非 0 (非正常退出),自动重启。3 是自动重启的次数。超过 3 次则不重启。 |
always | 表示容器退出时,docker 会总是自动重启这个容器。 |
unless-stopped | 表示容器退出时总是重启,但是不考虑 docker 守护进程运行时就已经停止的容器。 |
no | 默认值,容器退出时,docker 不自动重启容器。 |
Create 命令与容器环境和配置相关的选项
选项 | 说明 |
---|---|
–add-host=[] | 在容器内添加一个主机名到 IP 地址的映射关系(通过/etc/hosts 文件) |
–device=[] | 映射物理机上的设备到容器内。 |
–dns-search=[] | DNS 搜索域。 |
–dns-opt=[] | 自定义的 DNS 选项。 |
–dns=[] | 自定义的 DNS 服务器。 |
-e,–env=[] | 指定容器内环境变量。 |
–env-file=[] | 从文件中读取环境变量到容器内。 |
-h,–hostname=“” | 指定容器内的主机名。 |
–ip=“” | 指定容器的 IPv4 地址。 |
–ip6=“” | 指定容器的 IPv6 地址。 |
–link=[name or id: alias ] | 链接到其他容器。 |
–mac-address=“” | 指定容器的 Mac 地址。 |
–name=“” | 指定容器的别名。 |
Create 命令与容器资源限制和安全保护相关的选项
参数 | 说明 |
---|---|
–blkio-weight=10~1000 | 容器读写块设备的 I/O 性能权重,默认为 0。 |
–blkio-weight-device=[DEVICE_NAME: WEIGHT ] | 指定各个块设备的 I/O 性能权重。 |
–cpu-shares=0 | 允许容器使用 CPU 资源的相对权重,默认一个容器能用满一个核的 CPU。 |
–cap-add=[] | 增加容器的 Linux 指定安全能力。 |
–cap-drop=[] | 移除容器的 Linux 指定安全能力。 |
–cgroup-parent=“” | 容器 cgroups 限制的创建路径。 |
–cidfile=“” | 指定容器的进程 ID 号写到文件。 |
–cpu-period=0 | 限制容器在 CFS 调度器下的 CPU 占用时间片。 |
–cpuset-cpus=“” | 限制容器能使用那些 CPU 核心。 |
–cpuset-mem=“” | NUMA 架构下使用哪些核心的内存。 |
–cpu-quota=0 | 限制容器在 CFS 调度器下的 CPU 配额。 |
–device-read-bps=[] | 挂载设备的读吞吐率(以 bps 为单位)限制。 |
–device-write-iops=[] | 挂载设备的写速率(以每秒 i/o 次数为单位)限制。 |
–kernel-memory=“” | 限制容器内应用使用的内存,单位可以使 b、k、m 或 g。 |
–memory-reservation=“” | 当系统中内存过低是,容器会被强制限制内存到给定值,默认情况下等于内存限制值。 |
–memory-swap=“LIMIT” | 限制容器使用内存和交换区的总大小。 |
–oom-kil-disable=true/false | 内存耗尽(Out-Of-=Memory)时是否杀死容器。 |
–oom-score-adj=“” | 调整容器的内存耗尽参数。 |
–pids-limit=“” | 限制容器的 pid 个数。 |
–privileged=true/false | 是否给容器高权限,这意味着容器内应用将不受权限限制,一般不推荐。 |
–read-only=true/false | 是否让容器内的文件系统只读。 |
–security-opt=[] | 指定一些安全参数,包括权限、安全能力、apparmor 等。 |
–stop-signal=SIGTERM | 指定停止容器的系统信息。 |
–shm-size=“” | /dev/shm 的大小。 |
–sig-proxy=true/false | 是否代理收到的信号给应用,默认为 true,不能代理 SIGCHLD、SIGSTOP 和 SIGKILL 信号。 |
–memory-swappiness=“0~100” | 调整容器的内存交换区 |
-u,–user=“” | 指定在容器内指定命令的用户。 |
–ulimit=[] | 通过 ulimit 来限制最大文件书、最大进程数等。 |
其他比较重要的选项还包括:
参数 | 说明 |
---|---|
–label=[] | 以键值对方式指定容器的标签信息; |
label-file=[] | 从文件中读取标签信息。 |
4、创建一个容器
$ docker create -it --name="kcp_centos" centos:7.2.1511
docker start 命令
1 、概述。
docker start启动一个容器。
2 、语法大纲。
[root@node1 ~]# 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
3、参数简介。
参数 | 说明 |
---|---|
-a, --attach | 获取容器的标准错误和标准输出。 |
–detach-keys string | 指定退出 attach 模式的快捷键序列,默认是 CTRL-p CTRL-q |
-i, --interactive | 开标准输入接受用户输入命令,默认为 false。 |
4、启动一个容器
$ docker start kcp_centos
docker stop 命令
1、概述。
docker stop
停止一个容器。
2、语法大纲。
$ 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)
3、参数简介。
参数 | 说明 |
---|---|
-t, --time int | 在 kill 之前等待时间(单位为秒)。 |
4、停止一个容器。
$ docker stop kcp_centos;
docker rm 命令
1、概述。
1、使用 docker rm
命令来删除处于终止或退出状态的容器。
2、使用 docker rm -f
命令可以强制终止并删除一个运行中的容器。
2、语法大纲。
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 anonymous volumes associated with the container
3、参数简介。
参数 | 说明 |
---|---|
-f, --force | 强制删除正在运行的容器(使用 KILL 信号量)。 |
-l, link=false | 删除容器的连接,但保留容器。 |
-v,–volumes=false: | 删除容器挂载的数据卷。 |
4、删除一个容器。
1、可以使用容器名称删除。
2、可以使用容器 ID 删除。
$ docker rm kcp_centos
docker run 命令
1、概述。
docker run
新建并启动容器。
2、语法大纲。
$ 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
--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)
-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
--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 running ("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
--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
3、参数简介。
1、大部分选项同 docker create
命令。
2、docker run 多了一个 -d
选项。
参数 | 说明 |
---|---|
-d | 在后台运行容器和打印容器 ID。 |
4、docker run 后台运行的标准步骤。
当利用 docker run
来创建并启动容器时,Docker 在后台运行的标准操作包括:
(1)检查本地是否存在指定的镜像,不存在就从公有仓库下载;
(2)利用镜像创建一个容器,并启动该容器;
(3)分配一个文件系统给容器,并在只读的镜像层外面挂载一层可读写层;
(4)从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中;
(5)从网桥的地址池配置一个 IP 地址给容器;
(6)执行用户指定的应用程序;
(7)执行完毕后容器被自动终止。
5、新建并启动一个容器。
docker run -d -it --name="kcp_centos" centos:7.2.1511 /bin/sh -c "while true; do echo hello world; sleep 1; done"
docker attach 命令
1、概述。
docker attach
命令将容器的标准输入,标准输出,标准错误,打印到当前宿主机的终端。
2、语法大纲。
$ 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)
3、参数简介。
参数 | 说明 |
---|---|
–detach-keys string | 指定退出 attach 模式的快捷键序列,默认是 CTRL-p CTRL-q。 |
–no-stdin | 否关闭标准输入,默认是保持打开。 |
–sig-proxy | 否代理收到的系统信号给应用进程,默认为true |
4、打印容器终端信息
$ docker attach kcp_centos
编者注:
1、使用先按 CTRL + P
后立即按住 CTRL + Q
退出 attach。
2、在生产环境中同时使用 attach 命令连接到同一个容器时候,所有窗口都会同步显示。这样多有不便。为了解决这个问题,新增了 docker exec
命令。
dokcer exec 命令
1、概述。
dokcer exec
可以不进入容器,直接执行任意命令。
2、语法大纲。
$ 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
--env-file list Read in a file of 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
3、参数简介。
参数 | 说明 | |
---|---|---|
-d, --detach | 分离模式:在后台运行命令。 | |
–detach-keys string | 指定退出 attach 模式的快捷键序列,默认是 CTRL-p CTRL-q。 | |
-e, --env list | 设置环境变量。 | |
–env-file list | 从一个文件中读取环境变量。 | |
i, --interactive | 打开标准输入接受用户输入命令,默认为 false; | |
–privileged | 否给执行命令以高权限,默认为 false; | |
-t, --tty | 分配伪终端,默认为 false; | |
-u, --user string | 执行命令的用户名或 ID。 | |
-w, --workdir string | 指定容器的工作目录。 | |
编者注:再生产环境下,尽量使用 docker exec 命令,因为这种操作不影响当前其他应用。 |
4、进入创建的容器中,并启动一个 bash:
$ docker exec -it kcp_centos /bin/bash
root@971ff7ed7baf:/#
通过指定 it
方式可以保持标准输入代开,并且分配一个伪终端。推荐通过 docker exec
命令操作容器。
docker export 命令
1、概述。
某些时候,需要将容器从一个系统迁移到另外一个系统,此时可以使用 Docker 的导入和导出功能。
2、语法大纲。
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
3、参数说明。
参数 | 说明 |
---|---|
-o, --output string | 指定导出的 tar 文件名。 |
4、导出容器为 tar 包。
$ docker export -o kcp_centos.tar kcp_centos
docker import 命令
1、概述。
导出的文件又可以使用docker import
命令导入变成镜像
2、语法大纲。
$ 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
--platform string Set platform if server is multi-platform capa
3、参数说明。
参数 | 说明 |
---|---|
-c, --change list | 通过Dockerfile来创建镜像 。 |
-m, --message string | 提交注释信息。 |
–platform string | 设置平台兼容性。 |
4、导入容器。
编者注:注意导入 tar 包后,产生的不是一个容器而是一个镜像。
$ docker import kcp_centos.tar kcp_centos:v1.2
$ docker images
docker ps 命令
1、概述。
用于列出容器清单。
2、语法大纲。
docker ps --help
Usage: docker ps [OPTIONS]
List containers
Options:
-a, --all Show all containers (default shows just running)
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print containers using a Go template
-n, --last int Show n last created containers (includes all states) (default -1)
-l, --latest Show the latest created container (includes all states)
--no-trunc Don't truncate output
-q, --quiet Only display container IDs
-s, --size Display total file sizes
3、参数说明。
参数 | 说明 |
---|---|
-a, --all | 显示所有容器 (默认显示刚刚运行) 。 |
-f, --filter filter | 根据提供的条件过滤输出。 |
-n, --last int | 显示最后创建的容器 (包括所有状态) 。 |
–latest, -l | 显示最新创建的容器 (包括所有状态)。 |
--no-trunc | 不要截断输出。 |
–quiet, -q | 只显示数字 ID 。 |
–size, -s | 显示文件大小。 |
4、示例显示所有容器
1、显示正在运行、暂停、停止等运行状态的容器清单。
[root@node1 ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2、 返回信息的说明。
字段 | 说明 |
---|---|
CONTAINER ID | 容器 ID。 |
IMAGE | 使用的镜像。 |
COMMAND | 启动容器时运行的命令。 |
CREATED | 容器的创建时间。 |
STATUS | 容器状态。 |
编者注:STATUS 状态有 7 种。
- created(已创建)
- restarting(重启中)
- running(运行中)
- removing(迁移中)
- paused(暂停)
- exited(停止)
- dead(死亡)
创建容器
创建一个容器
1、创建一个有端口映射、主机名、逻辑卷挂载的容器。
$ docker create -h node111 -p 2222:22 -p 12345:54321 -it --ip="172.17.0.111" -v /opt:/opt --name="kcp_centos01" centos:7.2.1511
$ docker ps -a
命令说明
选项 | 说明 |
---|---|
-i | 打开标准输入接受用户输入命令,默认为 false。 |
-t | 分配伪终端,默认为 false 。 |
–name | 指定容器的别名为:“kcp_centos”。 |
–ip | 指定容器的 IP 地址为:172.17.0.111 |
-p | 将容器的 22 端口映射到宿主机的 2222 端口。将容器的 54321 端口映射为主机的 12345 端口。 |
-h | 指定容器内部的主机名称。 |
-v | 挂载主机 /opt 目录到容器目录 /opt 。 |
启动容器
1、docker start 命令用于启动容器并进入容器内部。
docker start -i kcp_centos01
创建并运行容器
除了创建容器后通过 start
命令来启动,也可以直接新建并启动容器。等价于 docker create
命令,再执行 docker star
t 命令。
示例 1:下面的命令输出一个"Hello World",之后容器自动终止:
1、查看当前容器运行情况。
docker ps
2、创建容器并运行。
$ docker run -h node112 -p 2223:22 -p 12346:54321 -it --ip="172.17.0.112" -v /opt:/opt --name="kcp_cenots02" centos:7.2.1511 /bin/echo "Hello world"
示例 2:启动一个 bash 终端,允许用户进行交互:
1、查看当前容器运行情况。
docker ps
2、创建容器并运行。
$ docker run -h node113 -p 2224:22 -p 12347:54321 -it --ip="172.17.0.113" -v /opt:/opt --name="kcp_centos03" centos:7.2.1511 /usr/bin/bash
--------------------------------------output:-------------------------------
[root@934b669e41e1 /]# pwd
/
[root@934b669e41e1 /]# ls
anaconda-post.log bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@934b669e41e1 /]# ps
PID TTY TIME CMD
1 pts/0 00:00:00 bash
17 pts/0 00:00:00 ps
示例 3:Docker 容器守护进程形式运行
1、查看当前容器运行情况。
docker ps
2、以守护进程方式启动容器。
$ docker run -d -h node114 -p 2225:22 -p 12348:54321 -it --ip="172.17.0.114" -v /opt:/opt --name="kcp_centos04" centos:7.2.1511 /bin/sh -c "while true; do echo hello world; sleep 1; done"
示例 4:Docker 容器开机自启。
1、查看当前容器运行情况。
docker ps
2、以守护进程方式启动容器。
$ docker run -d -h node114 -p 2225:22 -p 12348:54321 -it --ip="172.17.0.114" -v /opt:/opt --restart=always --name="kcp_centos04" centos:7.2.1511 /bin/sh -c "while true; do echo hello world; sleep 1; done"
容器自动重启
开机自启
docker update --restart=always kcp_centos04
自动重启
docker update --restart=unless-stopped kcp_centos04
失败重启
docker update --restart=on-failure:3 kcp_centos04
取消自启
docker update --restart=no kcp_centos04
暂停容器
1、查看当前容器运行情况。
docker ps -f name="kcp_centos04"
2、暂停容器。
dokcer pause kcp_centos04
取消暂停容器
dokcer unpause kcp_centos04
重启容器
docker restart kcp_centos04
查看容器日志
查看日志。
docker logs kcp_centos04
追加输出日志
docker logs -f kcp_centos04
查看容器进程
docker top daemon_dwayne
查看容器状态
docker stats
docker stats <contanier ID>
停止容器
正常停止容器
docker stop kcp_centos04
强制停止容器
docker kill kcp_centos04
导入和导出容器
导出容器
$ docker export -o kcp_centos.tar kcp_centos
导入容器
查看容器
查看容器可以使用 docker ps
命令,以下列出常用用法。
显示所有正在运行的容器。
只显示当前正在运行的容器清单。
[root@node1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
根据状态过滤
1、根据 STATUS 状态,筛选已退出的容器
$ docker ps -a --filter 'exited=0'
2、根据 STATUS 状态,筛选正在运行的容器。
$ docker ps --filter status=running
3、根据 STATUS 状态,筛选暂停的容器。
$ docker ps --filter status=paused
根据标签过滤
1 、启动 kcp_centos01 容器,并打标签为蓝色。
$ docker run -d --name=kcp_cenots1 --label color=blue centos:7.2.1511
2、筛选有 color
标签的容器。
$ docker ps --filter "label=color"
3、筛选 color
标签为 blue
的容器
$ docker ps --filter label=color=blue" -a
根据名称过滤
$ docker ps --filter "name=centos" -a
根据镜像过滤
1、根据镜像名称筛选容器。
docker ps --filter ancestor=centos:7.2.1511 -a
2、根据镜像 ID 筛选容器。
$ docker ps --filter ancestor=9aec5c5fe4ba
删除容器
正常删除容器
docker stop kcp_centos04
docker rm kcp_centos04
强制删除容器
docker rm -f kcp_centos04
批量删除全部容器
sudo docker rm `sudo docker ps -a -q`