运行容器
用法
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Options(常用选项)
名字,简写 | 默 | Description | 描述(中文) |
---|---|---|---|
--net | Connect a container to a network | 把容器连接到网络 | |
--name | Assign a name to the container | 定义容器的名字 | |
--network | Connect a container to a network | 把容器连接到网络 | |
--restart | no | Restart policy to apply when a container exits | 当容器退出时适用的重启策略(具体参数见下表) |
--rm | Automatically remove the container when it exits | 当容器退出的时候自动删除 | |
--volume , -v | Bind mount a volume | 绑定挂载一个数据卷 | |
--workdir , -w | Working directory inside the container | 设置容器内部的工作目录 | |
--interactive , -i | Keep STDIN open even if not attached | ||
--tty , -t | Allocate a pseudo-TTY | ||
--detach , -d | Run container in background and print container ID | 后台运行容器并且打印容器ID | |
--env , -e | Set environment variables | 设置容器的环境变量 | |
--env-file | Read in a file of environment variables | 读取文件里面的环境变量到容器 | |
--expose | Expose a port or a range of ports | 暴露一个端口或者是一个端口区间 | |
--publish , -p | Publish a container’s port(s) to the host | 发布一个容器的端口到宿主主机 | |
--publish-all , -P | Publish all exposed ports to random ports | 将所有暴露的端口发布到随机端口 | |
完整命令表
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
-a
-a, --attach=[] Attach to STDIN, STDOUT or STDERR
如果在执行 run 命令时没有指定 -a,那么 docker 默认会挂载所有标准数据流,包括输入输出和错误。你可以特别指定挂载哪个标准流。
docker run -a stdin -a stdout -i -t centos:8.2.2004 /bin/bash
只挂载标准输入输出
-t
只有-t参数
可以输入命令,但是命令没有任何反应,exit
和CTRL+P+Q
都无法退出,只能退出宿主机来强制退出
-i
只有-i参数
可以输入命令,命令可以生效,但是祝你写一行命令,exit
可以退出,但CTRL+P+Q
无法退出。
所以结合上面两种情况得知-i和-t一般是连用的,即-it
使用示例
访问主机设备
docker run -t -i --rm ubuntu bash
root@bc338942ef20:/# mount -t tmpfs none /mnt
mount: permission denied
上述示例不会工作,因为默认是不允许容器访问宿主机设备的,需要访问设备是需要加上--privileged
,如下所示
$ docker run -t -i --privileged ubuntu bash
root@50e3f57e16e6:/# mount -t tmpfs none /mnt
root@50e3f57e16e6:/# df -h
Filesystem Size Used Avail Use% Mounted on
none 1.9G 0 1.9G 0% /mnt
设置工作目录
docker run -w /path/to/dir/ -i -t ubuntu pwd
-w
会设置默认执行命令的目录,如果设置的这个目录在容器里面不存在,那么容器会自动创建这个目录。
挂载数据卷
- 添加数据卷
/data
,会在容器中自动创建。
docker run -it --name nginx-web --hostname=nginx-web -v /data nginx:1.21.0 /bin/bash
进入容器查看
root@nginx-web:/# cd /data
root@nginx-web:/data# df -lh
Filesystem Size Used Avail Use% Mounted on
overlay 38G 5.6G 33G 15% /
tmpfs 64M 0 64M 0% /dev
tmpfs 2.0G 0 2.0G 0% /sys/fs/cgroup
shm 64M 0 64M 0% /dev/shm
/dev/mapper/centos-root 38G 5.6G 33G 15% /data # 自动创建/data目录
tmpfs 2.0G 0 2.0G 0% /proc/asound
tmpfs 2.0G 0 2.0G 0% /proc/acpi
tmpfs 2.0G 0 2.0G 0% /proc/scsi
tmpfs 2.0G 0 2.0G 0% /sys/firmware
docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash
- 挂载宿主机目录
/doesnt/exist
到容器的/foo
目录上
- 当
/doesnt/exist
目录和/foo
目录都不存在时,docker会分别在宿主机和容器分别创建这两个目录。- 当在
/doesnt/exist
目录中创建或者修改一个文件时,/foo
目录也会跟着创建或者修改那个文件,反之也是一样的。- docker官方文档原文: When the host directory of a bind-mounted volume doesn’t exist, Docker will automatically create this directory on the host for you. In the example above, Docker will create the
/doesnt/exist
folder before starting your container.
设置容器只读
-read-only
选项可以设置容器的文件系统为只读,这样无法修改和新建容器里面的文件
docker run --read-only -v /icanwrite busybox touch /icanwrite/here
设置暴露端口
--expose
选项可以暴露端口,但是注意并不是把端口绑定发布在宿主机上(此功能需要-p选项),当发布端口以后就可以在docker ps
里面看到,以便提醒开发者某些端口可能是需要被发布在宿主机上的。
$ docker run -itd --name debian-demo --expose=22 --expose=3306 -p 1096:22 debian
91b174ec342edfbfd077af01aeb8ccba158008aab1cab2be23e399061429500f
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
91b174ec342e debian "bash" 4 seconds ago Up 3 seconds 3306/tcp, 0.0.0.0:1096->22/tcp, :::1096->22/tcp
上面可以看到容器暴露了22端口和3306端口,22端口映射到宿主机1096端口,而3306未被映射到宿主机。
发布(端口)
-p, --publish
发布端口到宿主机上,选项后面还要跟上参数[ip地址]宿主机端口:容器端口/[协议]
。
$ docker run -p 127.0.0.1:80:8080/tcp ubuntu bash
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8b03f83a90cd nginx "/docker-entrypoint.…" 5 seconds ago Up 4 seconds 127.0.0.1:8087->80/tcp nginx-demo
上述命令是绑定容器的tcp的8080端口,然后发布到宿主机的127.0.0.1(环回IP)的80端口上
- 不仅可以绑定tcp端口,还可以绑定udp端口和sctp端口。
- 发布如果带着主机IP的话,表示在127.0.0.1上发布,但是如果是想外网访问的话是不可以访问的。
- 如果想让任意网络访问,那么不写宿主机IP地址即可。
设置主机名
-h, --hostname
可以设置容器主机名
[root@localhost opt]# docker run -it --hostname=web --rm centos:7.9.2009 /bin/bash
[root@web /]# 进入容器后
https://zhuanlan.zhihu.com/p/433827521