【DOCKER】docker run的-d,-v等参数用处

本文详细解读了Docker run命令的各个选项,包括-d参数实现后台运行,-v用于数据卷挂载,-p和-P的区别,以及通过示例演示如何配置容器网络和环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0.引用

ref1

docker ps的详解

表格和文本的记录版本 

1.手册查询内容

[root@master cpu]# 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
[root@master cpu]# 

2.-d

后台运行

3.-v

绑定一个数据卷

4.-p(小写)

指定要映射的IP和端口,但是在一个指定端口上只可以绑定一个容器. 支持的格式有 hostPort:containerPortip:hostPort:containerPort、 ip::containerPort

5.-P(大写)

Docker会随机映射一个 49000~49900 的端口到内部容器开放的网络端口.

6.一个样例

docker run  -v /usr/ToolsAPIDir:/ToolsAPIDir1 -d -p 5005:5004 -it toolsapi:v8 python3 tools_api.py

-v 本地目录:容器目录,挂载主机的本地目录 /usr/ToolsAPIDir 目录到容器的/ToolsAPIDir1 目录,本地目录的路径必须是绝对路径

-d 后台运行容器

-p 5005:5004指定主机的5005端口映射到容器的5004端口

-it  toolsapi:v8 以交互模式运行 toolsapi:v8启动的容器

python3 tools_api.py 启动api.py文件,这样可以不需要再Dockfile中指定 CMD命令,或者覆盖Dockfile中的CMD命令

### 关于 `docker run -d` 参数的用法 `docker run` 是用于启动一个新的容器并执行指定命令的核心指令之一。其中 `-d` 参数表示以后台模式运行容器,即容器将以分离模式(detached mode)运行,不会占用当前终端[^1]。 以下是有关 `-d` 参数的具体说明: - 当使用 `-d` 参数时,Docker 会以后台方式运行容器,并返回容器 ID 到标准输出流。 - 这种模式适合运行长期服务的任务,例如 Web 服务器或数据库实例。 #### 示例代码 以下是一个典型的例子,展示如何通过 `-d` 参数以后台模式运行容器: ```bash docker run -d --name my_container nginx ``` 上述命令的作用如下: - `-d`: 表示以分离模式运行容器。 - `--name my_container`: 给容器命名,名称为 `my_container`。 - `nginx`: 使用官方 Nginx 镜像来启动容器。 如果需要传递额外的环境变量或其他配置选项,可以结合其他参数一起使用。例如: ```bash docker run -d --name my_container -e TZ=Asia/Shanghai your_image ``` 此命令中,`-e TZ=Asia/Shanghai` 设置了一个名为 `TZ` 的环境变量,值为 `Asia/Shanghai`[^4]。 #### 后台运行的特点 当容器以后台模式运行时,可以通过以下方法查看其状态: - 查看正在运行的容器列表:`docker ps` - 查看所有容器(包括停止的):`docker ps -a` - 日志查看:`docker logs <container_id>` 可帮助调试后台运行中的问题。 需要注意的是,在某些场景下,即使指定了 `-d` 参数,但如果容器内的进程退出,则容器也会自动停止。因此,确保镜像中有持久化任务非常重要[^2]。 --- ### 注意事项 1. 如果希望与容器进行交互操作,通常不建议单独使用 `-d` 参数,而是配合 `docker attach` 或者 `docker exec` 来实现进一步管理。 2. 对于短期任务或者一次性脚本执行,推荐省略 `-d` 并直接观察输出结果。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值