github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/cli/docs/reference/commandline/run.md (about) 1 --- 2 title: "run" 3 description: "The run command description and usage" 4 keywords: "run, command, container" 5 --- 6 7 # run 8 9 ```markdown 10 Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] 11 12 Run a command in a new container 13 14 Options: 15 --add-host value Add a custom host-to-IP mapping (host:ip) (default []) 16 -a, --attach value Attach to STDIN, STDOUT or STDERR (default []) 17 --blkio-weight value Block IO (relative weight), between 10 and 1000 18 --blkio-weight-device value Block IO weight (relative device weight) (default []) 19 --cap-add value Add Linux capabilities (default []) 20 --cap-drop value Drop Linux capabilities (default []) 21 --cgroupns string Cgroup namespace to use 22 'host': Run the container in the Docker host's cgroup namespace 23 'private': Run the container in its own private cgroup namespace 24 '': Use the default Docker daemon cgroup namespace specified by the `--default-cgroupns-mode` option 25 --cgroup-parent string Optional parent cgroup for the container 26 --cidfile string Write the container ID to the file 27 --cpu-count int The number of CPUs available for execution by the container. 28 Windows daemon only. On Windows Server containers, this is 29 approximated as a percentage of total CPU usage. 30 --cpu-percent int Limit percentage of CPU available for execution 31 by the container. Windows daemon only. 32 The processor resource controls are mutually 33 exclusive, the order of precedence is CPUCount 34 first, then CPUShares, and CPUPercent last. 35 --cpu-period int Limit CPU CFS (Completely Fair Scheduler) period 36 --cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota 37 -c, --cpu-shares int CPU shares (relative weight) 38 --cpus NanoCPUs Number of CPUs (default 0.000) 39 --cpu-rt-period int Limit the CPU real-time period in microseconds 40 --cpu-rt-runtime int Limit the CPU real-time runtime in microseconds 41 --cpuset-cpus string CPUs in which to allow execution (0-3, 0,1) 42 --cpuset-mems string MEMs in which to allow execution (0-3, 0,1) 43 -d, --detach Run container in background and print container ID 44 --detach-keys string Override the key sequence for detaching a container 45 --device value Add a host device to the container (default []) 46 --device-cgroup-rule value Add a rule to the cgroup allowed devices list 47 --device-read-bps value Limit read rate (bytes per second) from a device (default []) 48 --device-read-iops value Limit read rate (IO per second) from a device (default []) 49 --device-write-bps value Limit write rate (bytes per second) to a device (default []) 50 --device-write-iops value Limit write rate (IO per second) to a device (default []) 51 --disable-content-trust Skip image verification (default true) 52 --dns value Set custom DNS servers (default []) 53 --dns-option value Set DNS options (default []) 54 --dns-search value Set custom DNS search domains (default []) 55 --domainname string Container NIS domain name 56 --entrypoint string Overwrite the default ENTRYPOINT of the image 57 -e, --env value Set environment variables (default []) 58 --env-file value Read in a file of environment variables (default []) 59 --expose value Expose a port or a range of ports (default []) 60 --group-add value Add additional groups to join (default []) 61 --health-cmd string Command to run to check health 62 --health-interval duration Time between running the check (ns|us|ms|s|m|h) (default 0s) 63 --health-retries int Consecutive failures needed to report unhealthy 64 --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default 0s) 65 --health-start-period duration Start period for the container to initialize before counting retries towards unstable (ns|us|ms|s|m|h) (default 0s) 66 --help Print usage 67 -h, --hostname string Container host name 68 --init Run an init inside the container that forwards signals and reaps processes 69 -i, --interactive Keep STDIN open even if not attached 70 --io-maxbandwidth string Maximum IO bandwidth limit for the system drive (Windows only) 71 (Windows only). The format is `<number><unit>`. 72 Unit is optional and can be `b` (bytes per second), 73 `k` (kilobytes per second), `m` (megabytes per second), 74 or `g` (gigabytes per second). If you omit the unit, 75 the system uses bytes per second. 76 --io-maxbandwidth and --io-maxiops are mutually exclusive options. 77 --io-maxiops uint Maximum IOps limit for the system drive (Windows only) 78 --ip string IPv4 address (e.g., 172.30.100.104) 79 --ip6 string IPv6 address (e.g., 2001:db8::33) 80 --ipc string IPC namespace to use 81 --isolation string Container isolation technology 82 --kernel-memory string Kernel memory limit 83 -l, --label value Set meta data on a container (default []) 84 --label-file value Read in a line delimited file of labels (default []) 85 --link value Add link to another container (default []) 86 --link-local-ip value Container IPv4/IPv6 link-local addresses (default []) 87 --log-driver string Logging driver for the container 88 --log-opt value Log driver options (default []) 89 --mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33) 90 -m, --memory string Memory limit 91 --memory-reservation string Memory soft limit 92 --memory-swap string Swap limit equal to memory plus swap: '-1' to enable unlimited swap 93 --memory-swappiness int Tune container memory swappiness (0 to 100) (default -1) 94 --mount value Attach a filesystem mount to the container (default []) 95 --name string Assign a name to the container 96 --network-alias value Add network-scoped alias for the container (default []) 97 --network string Connect a container to a network 98 'bridge': create a network stack on the default Docker bridge 99 'none': no networking 100 'container:<name|id>': reuse another container's network stack 101 'host': use the Docker host network stack 102 '<network-name>|<network-id>': connect to a user-defined network 103 --no-healthcheck Disable any container-specified HEALTHCHECK 104 --oom-kill-disable Disable OOM Killer 105 --oom-score-adj int Tune host's OOM preferences (-1000 to 1000) 106 --pid string PID namespace to use 107 --pids-limit int Tune container pids limit (set -1 for unlimited) 108 --privileged Give extended privileges to this container 109 -p, --publish value Publish a container's port(s) to the host (default []) 110 -P, --publish-all Publish all exposed ports to random ports 111 --pull string Pull image before running ("always"|"missing"|"never") (default "missing") 112 --read-only Mount the container's root filesystem as read only 113 --restart string Restart policy to apply when a container exits (default "no") 114 Possible values are : no, on-failure[:max-retry], always, unless-stopped 115 --rm Automatically remove the container when it exits 116 --runtime string Runtime to use for this container 117 --security-opt value Security Options (default []) 118 --shm-size bytes Size of /dev/shm 119 The format is `<number><unit>`. `number` must be greater than `0`. 120 Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes), 121 or `g` (gigabytes). If you omit the unit, the system uses bytes. 122 --sig-proxy Proxy received signals to the process (default true) 123 --stop-signal string Signal to stop a container (default "SIGTERM") 124 --stop-timeout int Timeout (in seconds) to stop a container 125 --storage-opt value Storage driver options for the container (default []) 126 --sysctl value Sysctl options (default map[]) 127 --tmpfs value Mount a tmpfs directory (default []) 128 -t, --tty Allocate a pseudo-TTY 129 --ulimit value Ulimit options (default []) 130 -u, --user string Username or UID (format: <name|uid>[:<group|gid>]) 131 --userns string User namespace to use 132 'host': Use the Docker host user namespace 133 '': Use the Docker daemon user namespace specified by `--userns-remap` option. 134 --uts string UTS namespace to use 135 -v, --volume value Bind mount a volume (default []). The format 136 is `[host-src:]container-dest[:<options>]`. 137 The comma-delimited `options` are [rw|ro], 138 [z|Z], [[r]shared|[r]slave|[r]private], 139 [delegated|cached|consistent], and 140 [nocopy]. The 'host-src' is an absolute path 141 or a name value. 142 --volume-driver string Optional volume driver for the container 143 --volumes-from value Mount volumes from the specified container(s) (default []) 144 -w, --workdir string Working directory inside the container 145 ``` 146 147 ## Description 148 149 The `docker run` command first `creates` a writeable container layer over the 150 specified image, and then `starts` it using the specified command. That is, 151 `docker run` is equivalent to the API `/containers/create` then 152 `/containers/(id)/start`. A stopped container can be restarted with all its 153 previous changes intact using `docker start`. See `docker ps -a` to view a list 154 of all containers. 155 156 For information on connecting a container to a network, see the ["*Docker network overview*"](https://docs.docker.com/network/). 157 158 ## Examples 159 160 ### <a name="name"></a> Assign name and allocate pseudo-TTY (--name, -it) 161 162 ```console 163 $ docker run --name test -it debian 164 165 root@d6c0fe130dba:/# exit 13 166 $ echo $? 167 13 168 $ docker ps -a | grep test 169 d6c0fe130dba debian:7 "/bin/bash" 26 seconds ago Exited (13) 17 seconds ago test 170 ``` 171 172 This example runs a container named `test` using the `debian:latest` 173 image. The `-it` instructs Docker to allocate a pseudo-TTY connected to 174 the container's stdin; creating an interactive `bash` shell in the container. 175 In the example, the `bash` shell is quit by entering 176 `exit 13`. This exit code is passed on to the caller of 177 `docker run`, and is recorded in the `test` container's metadata. 178 179 ### <a name="cidfile"></a> Capture container ID (--cidfile) 180 181 ```console 182 $ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test" 183 ``` 184 185 This will create a container and print `test` to the console. The `cidfile` 186 flag makes Docker attempt to create a new file and write the container ID to it. 187 If the file exists already, Docker will return an error. Docker will close this 188 file when `docker run` exits. 189 190 ### <a name="privileged"></a> Full container capabilities (--privileged) 191 192 ```console 193 $ docker run -t -i --rm ubuntu bash 194 root@bc338942ef20:/# mount -t tmpfs none /mnt 195 mount: permission denied 196 ``` 197 198 This will *not* work, because by default, most potentially dangerous kernel 199 capabilities are dropped; including `cap_sys_admin` (which is required to mount 200 filesystems). However, the `--privileged` flag will allow it to run: 201 202 ```console 203 $ docker run -t -i --privileged ubuntu bash 204 root@50e3f57e16e6:/# mount -t tmpfs none /mnt 205 root@50e3f57e16e6:/# df -h 206 Filesystem Size Used Avail Use% Mounted on 207 none 1.9G 0 1.9G 0% /mnt 208 ``` 209 210 The `--privileged` flag gives *all* capabilities to the container, and it also 211 lifts all the limitations enforced by the `device` cgroup controller. In other 212 words, the container can then do almost everything that the host can do. This 213 flag exists to allow special use-cases, like running Docker within Docker. 214 215 ### <a name="workdir"></a> Set working directory (-w, --workdir) 216 217 ```console 218 $ docker run -w /path/to/dir/ -i -t ubuntu pwd 219 ``` 220 221 The `-w` lets the command being executed inside directory given, here 222 `/path/to/dir/`. If the path does not exist it is created inside the container. 223 224 ### <a name="storage-opt"></a> Set storage driver options per container (--storage-opt) 225 226 ```console 227 $ docker run -it --storage-opt size=120G fedora /bin/bash 228 ``` 229 230 This (size) will allow to set the container filesystem size to 120G at creation time. 231 This option is only available for the `devicemapper`, `btrfs`, `overlay2`, 232 `windowsfilter` and `zfs` graph drivers. 233 For the `devicemapper`, `btrfs`, `windowsfilter` and `zfs` graph drivers, 234 user cannot pass a size less than the Default BaseFS Size. 235 For the `overlay2` storage driver, the size option is only available if the 236 backing filesystem is `xfs` and mounted with the `pquota` mount option. 237 Under these conditions, user can pass any size less than the backing filesystem size. 238 239 ### <a name="tmpfs"></a> Mount tmpfs (--tmpfs) 240 241 ```console 242 $ docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_image 243 ``` 244 245 The `--tmpfs` flag mounts an empty tmpfs into the container with the `rw`, 246 `noexec`, `nosuid`, `size=65536k` options. 247 248 ### <a name="volume"></a> Mount volume (-v, --read-only) 249 250 ```console 251 $ docker run -v `pwd`:`pwd` -w `pwd` -i -t ubuntu pwd 252 ``` 253 254 The `-v` flag mounts the current working directory into the container. The `-w` 255 lets the command being executed inside the current working directory, by 256 changing into the directory to the value returned by `pwd`. So this 257 combination executes the command using the container, but inside the 258 current working directory. 259 260 ```console 261 $ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash 262 ``` 263 264 When the host directory of a bind-mounted volume doesn't exist, Docker 265 will automatically create this directory on the host for you. In the 266 example above, Docker will create the `/doesnt/exist` 267 folder before starting your container. 268 269 ```console 270 $ docker run --read-only -v /icanwrite busybox touch /icanwrite/here 271 ``` 272 273 Volumes can be used in combination with `--read-only` to control where 274 a container writes files. The `--read-only` flag mounts the container's root 275 filesystem as read only prohibiting writes to locations other than the 276 specified volumes for the container. 277 278 ```console 279 $ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v /path/to/static-docker-binary:/usr/bin/docker busybox sh 280 ``` 281 282 By bind-mounting the Docker Unix socket and statically linked Docker 283 binary (refer to [get the Linux binary](https://docs.docker.com/engine/install/binaries/#install-static-binaries)), 284 you give the container the full access to create and manipulate the host's 285 Docker daemon. 286 287 On Windows, the paths must be specified using Windows-style semantics. 288 289 ```powershell 290 PS C:\> docker run -v c:\foo:c:\dest microsoft/nanoserver cmd /s /c type c:\dest\somefile.txt 291 Contents of file 292 293 PS C:\> docker run -v c:\foo:d: microsoft/nanoserver cmd /s /c type d:\somefile.txt 294 Contents of file 295 ``` 296 297 The following examples will fail when using Windows-based containers, as the 298 destination of a volume or bind mount inside the container must be one of: 299 a non-existing or empty directory; or a drive other than C:. Further, the source 300 of a bind mount must be a local directory, not a file. 301 302 ```powershell 303 net use z: \\remotemachine\share 304 docker run -v z:\foo:c:\dest ... 305 docker run -v \\uncpath\to\directory:c:\dest ... 306 docker run -v c:\foo\somefile.txt:c:\dest ... 307 docker run -v c:\foo:c: ... 308 docker run -v c:\foo:c:\existing-directory-with-contents ... 309 ``` 310 311 For in-depth information about volumes, refer to [manage data in containers](https://docs.docker.com/storage/volumes/) 312 313 314 ### <a name="mount"></a> Add bind mounts or volumes using the --mount flag 315 316 The `--mount` flag allows you to mount volumes, host-directories and `tmpfs` 317 mounts in a container. 318 319 The `--mount` flag supports most options that are supported by the `-v` or the 320 `--volume` flag, but uses a different syntax. For in-depth information on the 321 `--mount` flag, and a comparison between `--volume` and `--mount`, refer to 322 [Bind mounts](https://docs.docker.com/storage/bind-mounts/). 323 324 Even though there is no plan to deprecate `--volume`, usage of `--mount` is recommended. 325 326 Examples: 327 328 ```console 329 $ docker run --read-only --mount type=volume,target=/icanwrite busybox touch /icanwrite/here 330 ``` 331 332 ```console 333 $ docker run -t -i --mount type=bind,src=/data,dst=/data busybox sh 334 ``` 335 336 ### <a name="publish"></a> Publish or expose port (-p, --expose) 337 338 ```console 339 $ docker run -p 127.0.0.1:80:8080/tcp ubuntu bash 340 ``` 341 342 This binds port `8080` of the container to TCP port `80` on `127.0.0.1` of the host 343 machine. You can also specify `udp` and `sctp` ports. 344 The [Docker User Guide](https://docs.docker.com/network/links/) 345 explains in detail how to manipulate ports in Docker. 346 347 Note that ports which are not bound to the host (i.e., `-p 80:80` instead of 348 `-p 127.0.0.1:80:80`) will be accessible from the outside. This also applies if 349 you configured UFW to block this specific port, as Docker manages its 350 own iptables rules. [Read more](https://docs.docker.com/network/iptables/) 351 352 ```console 353 $ docker run --expose 80 ubuntu bash 354 ``` 355 356 This exposes port `80` of the container without publishing the port to the host 357 system's interfaces. 358 359 ### <a name="pull"></a> Set the pull policy (--pull) 360 361 Use the `--pull` flag to set the image pull policy when creating (and running) 362 the container. 363 364 The `--pull` flag can take one of these values: 365 366 | Value | Description | 367 |:--------------------|:------------------------------------------------------------------------------------------------------------------| 368 | `missing` (default) | Pull the image if it was not found in the image cache, or use the cached image otherwise. | 369 | `never` | Do not pull the image, even if it's missing, and produce an error if the image does not exist in the image cache. | 370 | `always` | Always perform a pull before creating the container. | 371 372 When creating (and running) a container from an image, the daemon checks if the 373 image exists in the local image cache. If the image is missing, an error is 374 returned to the CLI, allowing it to initiate a pull. 375 376 The default (`missing`) is to only pull the image if it is not present in the 377 daemon's image cache. This default allows you to run images that only exist 378 locally (for example, images you built from a Dockerfile, but that have not 379 been pushed to a registry), and reduces networking. 380 381 The `always` option always initiates a pull before creating the container. This 382 option makes sure the image is up-to-date, and prevents you from using outdated 383 images, but may not be suitable in situations where you want to test a locally 384 built image before pushing (as pulling the image overwrites the existing image 385 in the image cache). 386 387 The `never` option disables (implicit) pulling images when creating containers, 388 and only uses images that are available in the image cache. If the specified 389 image is not found, an error is produced, and the container is not created. 390 This option is useful in situations where networking is not available, or to 391 prevent images from being pulled implicitly when creating containers. 392 393 The following example shows `docker run` with the `--pull=never` option set, 394 which produces en error as the image is missing in the image-cache: 395 396 ```console 397 $ docker run --pull=never hello-world 398 docker: Error response from daemon: No such image: hello-world:latest. 399 ``` 400 401 ### <a name="env"></a> Set environment variables (-e, --env, --env-file) 402 403 ```console 404 $ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash 405 ``` 406 407 Use the `-e`, `--env`, and `--env-file` flags to set simple (non-array) 408 environment variables in the container you're running, or overwrite variables 409 that are defined in the Dockerfile of the image you're running. 410 411 You can define the variable and its value when running the container: 412 413 ```console 414 $ docker run --env VAR1=value1 --env VAR2=value2 ubuntu env | grep VAR 415 VAR1=value1 416 VAR2=value2 417 ``` 418 419 You can also use variables that you've exported to your local environment: 420 421 ```console 422 export VAR1=value1 423 export VAR2=value2 424 425 $ docker run --env VAR1 --env VAR2 ubuntu env | grep VAR 426 VAR1=value1 427 VAR2=value2 428 ``` 429 430 When running the command, the Docker CLI client checks the value the variable 431 has in your local environment and passes it to the container. 432 If no `=` is provided and that variable is not exported in your local 433 environment, the variable won't be set in the container. 434 435 You can also load the environment variables from a file. This file should use 436 the syntax `<variable>=value` (which sets the variable to the given value) or 437 `<variable>` (which takes the value from the local environment), and `#` for comments. 438 439 ```console 440 $ cat env.list 441 # This is a comment 442 VAR1=value1 443 VAR2=value2 444 USER 445 446 $ docker run --env-file env.list ubuntu env | grep -E 'VAR|USER' 447 VAR1=value1 448 VAR2=value2 449 USER=jonzeolla 450 ``` 451 452 ### <a name="label"></a> Set metadata on container (-l, --label, --label-file) 453 454 A label is a `key=value` pair that applies metadata to a container. To label a container with two labels: 455 456 ```console 457 $ docker run -l my-label --label com.example.foo=bar ubuntu bash 458 ``` 459 460 The `my-label` key doesn't specify a value so the label defaults to an empty 461 string (`""`). To add multiple labels, repeat the label flag (`-l` or `--label`). 462 463 The `key=value` must be unique to avoid overwriting the label value. If you 464 specify labels with identical keys but different values, each subsequent value 465 overwrites the previous. Docker uses the last `key=value` you supply. 466 467 Use the `--label-file` flag to load multiple labels from a file. Delimit each 468 label in the file with an EOL mark. The example below loads labels from a 469 labels file in the current directory: 470 471 ```console 472 $ docker run --label-file ./labels ubuntu bash 473 ``` 474 475 The label-file format is similar to the format for loading environment 476 variables. (Unlike environment variables, labels are not visible to processes 477 running inside a container.) The following example illustrates a label-file 478 format: 479 480 ```console 481 com.example.label1="a label" 482 483 # this is a comment 484 com.example.label2=another\ label 485 com.example.label3 486 ``` 487 488 You can load multiple label-files by supplying multiple `--label-file` flags. 489 490 For additional information on working with labels, see [*Labels - custom 491 metadata in Docker*](https://docs.docker.com/config/labels-custom-metadata/) in 492 the Docker User Guide. 493 494 ### <a name="network"></a> Connect a container to a network (--network) 495 496 When you start a container use the `--network` flag to connect it to a network. 497 The following commands create a network named `my-net`, and adds a `busybox` container 498 to the `my-net` network. 499 500 ```console 501 $ docker network create my-net 502 $ docker run -itd --network=my-net busybox 503 ``` 504 505 You can also choose the IP addresses for the container with `--ip` and `--ip6` 506 flags when you start the container on a user-defined network. 507 508 ```console 509 $ docker run -itd --network=my-net --ip=10.10.9.75 busybox 510 ``` 511 512 If you want to add a running container to a network use the `docker network connect` subcommand. 513 514 You can connect multiple containers to the same network. Once connected, the 515 containers can communicate easily using only another container's IP address 516 or name. For `overlay` networks or custom plugins that support multi-host 517 connectivity, containers connected to the same multi-host network but launched 518 from different Engines can also communicate in this way. 519 520 > **Note** 521 > 522 > The default bridge network only allow containers to communicate with each other using 523 > internal IP addresses. User-created bridge networks provide DNS resolution between 524 > containers using container names. 525 526 You can disconnect a container from a network using the `docker network 527 disconnect` command. 528 529 ### <a name="volumes-from"></a> Mount volumes from container (--volumes-from) 530 531 ```console 532 $ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd 533 ``` 534 535 The `--volumes-from` flag mounts all the defined volumes from the referenced 536 containers. Containers can be specified by repetitions of the `--volumes-from` 537 argument. The container ID may be optionally suffixed with `:ro` or `:rw` to 538 mount the volumes in read-only or read-write mode, respectively. By default, 539 the volumes are mounted in the same mode (read write or read only) as 540 the reference container. 541 542 Labeling systems like SELinux require that proper labels are placed on volume 543 content mounted into a container. Without a label, the security system might 544 prevent the processes running inside the container from using the content. By 545 default, Docker does not change the labels set by the OS. 546 547 To change the label in the container context, you can add either of two suffixes 548 `:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file 549 objects on the shared volumes. The `z` option tells Docker that two containers 550 share the volume content. As a result, Docker labels the content with a shared 551 content label. Shared volume labels allow all containers to read/write content. 552 The `Z` option tells Docker to label the content with a private unshared label. 553 Only the current container can use a private volume. 554 555 ### <a name="attach"></a> Attach to STDIN/STDOUT/STDERR (-a, --attach) 556 557 The `--attach` (or `-a`) flag tells `docker run` to bind to the container's 558 `STDIN`, `STDOUT` or `STDERR`. This makes it possible to manipulate the output 559 and input as needed. 560 561 ```console 562 $ echo "test" | docker run -i -a stdin ubuntu cat - 563 ``` 564 565 This pipes data into a container and prints the container's ID by attaching 566 only to the container's `STDIN`. 567 568 ```console 569 $ docker run -a stderr ubuntu echo test 570 ``` 571 572 This isn't going to print anything unless there's an error because we've 573 only attached to the `STDERR` of the container. The container's logs 574 still store what's been written to `STDERR` and `STDOUT`. 575 576 ```console 577 $ cat somefile | docker run -i -a stdin mybuilder dobuild 578 ``` 579 580 This is a way of using `--attach` to pipe a build file into a container. 581 The container's ID will be printed after the build is done and the build 582 logs could be retrieved using `docker logs`. This is 583 useful if you need to pipe a file or something else into a container and 584 retrieve the container's ID once the container has finished running. 585 586 See also [the `docker cp` command](cp.md). 587 588 ### <a name="device"></a> Add host device to container (--device) 589 590 ```console 591 $ docker run -it --rm \ 592 --device=/dev/sdc:/dev/xvdc \ 593 --device=/dev/sdd \ 594 --device=/dev/zero:/dev/foobar \ 595 ubuntu ls -l /dev/{xvdc,sdd,foobar} 596 597 brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc 598 brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd 599 crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/foobar 600 ``` 601 602 It is often necessary to directly expose devices to a container. The `--device` 603 option enables that. For example, a specific block storage device or loop 604 device or audio device can be added to an otherwise unprivileged container 605 (without the `--privileged` flag) and have the application directly access it. 606 607 By default, the container will be able to `read`, `write` and `mknod` these devices. 608 This can be overridden using a third `:rwm` set of options to each `--device` 609 flag. If the container is running in privileged mode, then the permissions specified 610 will be ignored. 611 612 ```console 613 $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc 614 615 Command (m for help): q 616 $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc 617 You will not be able to write the partition table. 618 619 Command (m for help): q 620 621 $ docker run --device=/dev/sda:/dev/xvdc:rw --rm -it ubuntu fdisk /dev/xvdc 622 623 Command (m for help): q 624 625 $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc 626 fdisk: unable to open /dev/xvdc: Operation not permitted 627 ``` 628 629 > **Note** 630 > 631 > The `--device` option cannot be safely used with ephemeral devices. Block devices 632 > that may be removed should not be added to untrusted containers with `--device`. 633 634 For Windows, the format of the string passed to the `--device` option is in 635 the form of `--device=<IdType>/<Id>`. Beginning with Windows Server 2019 636 and Windows 10 October 2018 Update, Windows only supports an IdType of 637 `class` and the Id as a [device interface class 638 GUID](https://docs.microsoft.com/en-us/windows-hardware/drivers/install/overview-of-device-interface-classes). 639 Refer to the table defined in the [Windows container 640 docs](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/hardware-devices-in-containers) 641 for a list of container-supported device interface class GUIDs. 642 643 If this option is specified for a process-isolated Windows container, _all_ 644 devices that implement the requested device interface class GUID are made 645 available in the container. For example, the command below makes all COM 646 ports on the host visible in the container. 647 648 ```powershell 649 PS C:\> docker run --device=class/86E0D1E0-8089-11D0-9CE4-08003E301F73 mcr.microsoft.com/windows/servercore:ltsc2019 650 ``` 651 652 > **Note** 653 > 654 > The `--device` option is only supported on process-isolated Windows containers. 655 > This option fails if the container isolation is `hyperv` or when running Linux 656 > Containers on Windows (LCOW). 657 658 ### <a name="device-cgroup-rule"></a> Using dynamically created devices (--device-cgroup-rule) 659 660 Devices available to a container are assigned at creation time. The 661 assigned devices will both be added to the cgroup.allow file and 662 created into the container once it is run. This poses a problem when 663 a new device needs to be added to running container. 664 665 One of the solutions is to add a more permissive rule to a container 666 allowing it access to a wider range of devices. For example, supposing 667 our container needs access to a character device with major `42` and 668 any number of minor number (added as new devices appear), the 669 following rule would be added: 670 671 ```console 672 $ docker run -d --device-cgroup-rule='c 42:* rmw' -name my-container my-image 673 ``` 674 675 Then, a user could ask `udev` to execute a script that would `docker exec my-container mknod newDevX c 42 <minor>` 676 the required device when it is added. 677 678 > **Note**: initially present devices still need to be explicitly added to the 679 > `docker run` / `docker create` command. 680 681 ### <a name="gpus"></a> Access an NVIDIA GPU 682 683 The `--gpus` flag allows you to access NVIDIA GPU resources. First you need to 684 install [nvidia-container-runtime](https://nvidia.github.io/nvidia-container-runtime/). 685 Visit [Specify a container's resources](https://docs.docker.com/config/containers/resource_constraints/) 686 for more information. 687 688 To use `--gpus`, specify which GPUs (or all) to use. If no value is provided, all 689 available GPUs are used. The example below exposes all available GPUs. 690 691 ```console 692 $ docker run -it --rm --gpus all ubuntu nvidia-smi 693 ``` 694 695 Use the `device` option to specify GPUs. The example below exposes a specific 696 GPU. 697 698 ```console 699 $ docker run -it --rm --gpus device=GPU-3a23c669-1f69-c64e-cf85-44e9b07e7a2a ubuntu nvidia-smi 700 ``` 701 702 The example below exposes the first and third GPUs. 703 704 ```console 705 $ docker run -it --rm --gpus '"device=0,2"' nvidia-smi 706 ``` 707 708 ### <a name="restart"></a> Restart policies (--restart) 709 710 Use Docker's `--restart` to specify a container's *restart policy*. A restart 711 policy controls whether the Docker daemon restarts a container after exit. 712 Docker supports the following restart policies: 713 714 | Policy | Result | 715 |:---------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 716 | `no` | Do not automatically restart the container when it exits. This is the default. | 717 | `on-failure[:max-retries]` | Restart only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts. | 718 | `unless-stopped` | Restart the container unless it is explicitly stopped or Docker itself is stopped or restarted. | 719 | `always` | Always restart the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely. The container will also always start on daemon startup, regardless of the current state of the container. | 720 721 ```console 722 $ docker run --restart=always redis 723 ``` 724 725 This will run the `redis` container with a restart policy of **always** 726 so that if the container exits, Docker will restart it. 727 728 More detailed information on restart policies can be found in the 729 [Restart Policies (--restart)](../run.md#restart-policies---restart) 730 section of the Docker run reference page. 731 732 ### <a name="add-host"></a> Add entries to container hosts file (--add-host) 733 734 You can add other hosts into a container's `/etc/hosts` file by using one or 735 more `--add-host` flags. This example adds a static address for a host named 736 `docker`: 737 738 ```console 739 $ docker run --add-host=docker:93.184.216.34 --rm -it alpine 740 741 / # ping docker 742 PING docker (93.184.216.34): 56 data bytes 743 64 bytes from 93.184.216.34: seq=0 ttl=37 time=93.052 ms 744 64 bytes from 93.184.216.34: seq=1 ttl=37 time=92.467 ms 745 64 bytes from 93.184.216.34: seq=2 ttl=37 time=92.252 ms 746 ^C 747 --- docker ping statistics --- 748 4 packets transmitted, 4 packets received, 0% packet loss 749 round-trip min/avg/max = 92.209/92.495/93.052 ms 750 ``` 751 752 Sometimes you need to connect to the Docker host from within your 753 container. To enable this, pass the Docker host's IP address to 754 the container using the `--add-host` flag. To find the host's address, 755 use the `ip addr show` command. 756 757 The flags you pass to `ip addr show` depend on whether you are 758 using IPv4 or IPv6 networking in your containers. Use the following 759 flags for IPv4 address retrieval for a network device named `eth0`: 760 761 ```console 762 $ HOSTIP=`ip -4 addr show scope global dev eth0 | grep inet | awk '{print $2}' | cut -d / -f 1 | sed -n 1p` 763 $ docker run --add-host=docker:${HOSTIP} --rm -it debian 764 ``` 765 766 For IPv6 use the `-6` flag instead of the `-4` flag. For other network 767 devices, replace `eth0` with the correct device name (for example `docker0` 768 for the bridge device). 769 770 ### <a name="ulimit"></a> Set ulimits in container (--ulimit) 771 772 Since setting `ulimit` settings in a container requires extra privileges not 773 available in the default container, you can set these using the `--ulimit` flag. 774 `--ulimit` is specified with a soft and hard limit as such: 775 `<type>=<soft limit>[:<hard limit>]`, for example: 776 777 ```console 778 $ docker run --ulimit nofile=1024:1024 --rm debian sh -c "ulimit -n" 779 1024 780 ``` 781 782 > **Note** 783 > 784 > If you do not provide a `hard limit`, the `soft limit` is used 785 > for both values. If no `ulimits` are set, they are inherited from 786 > the default `ulimits` set on the daemon. The `as` option is disabled now. 787 > In other words, the following script is not supported: 788 > 789 > ```console 790 > $ docker run -it --ulimit as=1024 fedora /bin/bash 791 > ``` 792 793 The values are sent to the appropriate `syscall` as they are set. 794 Docker doesn't perform any byte conversion. Take this into account when setting the values. 795 796 #### For `nproc` usage 797 798 Be careful setting `nproc` with the `ulimit` flag as `nproc` is designed by Linux to set the 799 maximum number of processes available to a user, not to a container. For example, start four 800 containers with `daemon` user: 801 802 ```console 803 $ docker run -d -u daemon --ulimit nproc=3 busybox top 804 805 $ docker run -d -u daemon --ulimit nproc=3 busybox top 806 807 $ docker run -d -u daemon --ulimit nproc=3 busybox top 808 809 $ docker run -d -u daemon --ulimit nproc=3 busybox top 810 ``` 811 812 The 4th container fails and reports "[8] System error: resource temporarily unavailable" error. 813 This fails because the caller set `nproc=3` resulting in the first three containers using up 814 the three processes quota set for the `daemon` user. 815 816 ### <a name="stop-signal"></a> Stop container with signal (--stop-signal) 817 818 The `--stop-signal` flag sets the system call signal that will be sent to the 819 container to exit. This signal can be a signal name in the format `SIG<NAME>`, 820 for instance `SIGKILL`, or an unsigned number that matches a position in the 821 kernel's syscall table, for instance `9`. 822 823 The default is `SIGTERM` if not specified. 824 825 ### <a name="security-opt"></a> Optional security options (--security-opt) 826 827 On Windows, this flag can be used to specify the `credentialspec` option. 828 The `credentialspec` must be in the format `file://spec.txt` or `registry://keyname`. 829 830 ### <a name="stop-timeout"></a> Stop container with timeout (--stop-timeout) 831 832 The `--stop-timeout` flag sets the number of seconds to wait for the container 833 to stop after sending the pre-defined (see `--stop-signal`) system call signal. 834 If the container does not exit after the timeout elapses, it is forcibly killed 835 with a `SIGKILL` signal. 836 837 If `--stop-timeout` is set to `-1`, no timeout is applied, and the daemon will 838 wait indefinitely for the container to exit. 839 840 The default is determined by the daemon, and is 10 seconds for Linux containers, 841 and 30 seconds for Windows containers. 842 843 ### <a name="isolation"></a> Specify isolation technology for container (--isolation) 844 845 This option is useful in situations where you are running Docker containers on 846 Windows. The `--isolation=<value>` option sets a container's isolation technology. 847 On Linux, the only supported is the `default` option which uses Linux namespaces. 848 These two commands are equivalent on Linux: 849 850 ```console 851 $ docker run -d busybox top 852 $ docker run -d --isolation default busybox top 853 ``` 854 855 On Windows, `--isolation` can take one of these values: 856 857 | Value | Description | 858 |:----------|:-------------------------------------------------------------------------------------------| 859 | `default` | Use the value specified by the Docker daemon's `--exec-opt` or system default (see below). | 860 | `process` | Shared-kernel namespace isolation. | 861 | `hyperv` | Hyper-V hypervisor partition-based isolation. | 862 863 The default isolation on Windows server operating systems is `process`, and `hyperv` 864 on Windows client operating systems, such as Windows 10. Process isolation has better 865 performance, but requires that the image and host use the same kernel version. 866 867 On Windows server, assuming the default configuration, these commands are equivalent 868 and result in `process` isolation: 869 870 ```powershell 871 PS C:\> docker run -d microsoft/nanoserver powershell echo process 872 PS C:\> docker run -d --isolation default microsoft/nanoserver powershell echo process 873 PS C:\> docker run -d --isolation process microsoft/nanoserver powershell echo process 874 ``` 875 876 If you have set the `--exec-opt isolation=hyperv` option on the Docker `daemon`, or 877 are running against a Windows client-based daemon, these commands are equivalent and 878 result in `hyperv` isolation: 879 880 ```powershell 881 PS C:\> docker run -d microsoft/nanoserver powershell echo hyperv 882 PS C:\> docker run -d --isolation default microsoft/nanoserver powershell echo hyperv 883 PS C:\> docker run -d --isolation hyperv microsoft/nanoserver powershell echo hyperv 884 ``` 885 886 ### <a name="memory"></a> Specify hard limits on memory available to containers (-m, --memory) 887 888 These parameters always set an upper limit on the memory available to the container. On Linux, this 889 is set on the cgroup and applications in a container can query it at `/sys/fs/cgroup/memory/memory.limit_in_bytes`. 890 891 On Windows, this will affect containers differently depending on what type of isolation is used. 892 893 - With `process` isolation, Windows will report the full memory of the host system, not the limit to applications running inside the container 894 895 ```powershell 896 PS C:\> docker run -it -m 2GB --isolation=process microsoft/nanoserver powershell Get-ComputerInfo *memory* 897 898 CsTotalPhysicalMemory : 17064509440 899 CsPhyicallyInstalledMemory : 16777216 900 OsTotalVisibleMemorySize : 16664560 901 OsFreePhysicalMemory : 14646720 902 OsTotalVirtualMemorySize : 19154928 903 OsFreeVirtualMemory : 17197440 904 OsInUseVirtualMemory : 1957488 905 OsMaxProcessMemorySize : 137438953344 906 ``` 907 908 - With `hyperv` isolation, Windows will create a utility VM that is big enough to hold the memory limit, plus the minimal OS needed to host the container. That size is reported as "Total Physical Memory." 909 910 ```powershell 911 PS C:\> docker run -it -m 2GB --isolation=hyperv microsoft/nanoserver powershell Get-ComputerInfo *memory* 912 913 CsTotalPhysicalMemory : 2683355136 914 CsPhyicallyInstalledMemory : 915 OsTotalVisibleMemorySize : 2620464 916 OsFreePhysicalMemory : 2306552 917 OsTotalVirtualMemorySize : 2620464 918 OsFreeVirtualMemory : 2356692 919 OsInUseVirtualMemory : 263772 920 OsMaxProcessMemorySize : 137438953344 921 ``` 922 923 924 ### <a name="sysctl"></a> Configure namespaced kernel parameters (sysctls) at runtime (--sysctl) 925 926 The `--sysctl` sets namespaced kernel parameters (sysctls) in the 927 container. For example, to turn on IP forwarding in the containers 928 network namespace, run this command: 929 930 ```console 931 $ docker run --sysctl net.ipv4.ip_forward=1 someimage 932 ``` 933 934 > **Note** 935 > 936 > Not all sysctls are namespaced. Docker does not support changing sysctls 937 > inside of a container that also modify the host system. As the kernel 938 > evolves we expect to see more sysctls become namespaced. 939 940 #### Currently supported sysctls 941 942 IPC Namespace: 943 944 - `kernel.msgmax`, `kernel.msgmnb`, `kernel.msgmni`, `kernel.sem`, 945 `kernel.shmall`, `kernel.shmmax`, `kernel.shmmni`, `kernel.shm_rmid_forced`. 946 - Sysctls beginning with `fs.mqueue.*` 947 - If you use the `--ipc=host` option these sysctls are not allowed. 948 949 Network Namespace: 950 951 - Sysctls beginning with `net.*` 952 - If you use the `--network=host` option using these sysctls are not allowed.