github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/docs/reference/commandline/container_run.md (about) 1 # run 2 3 <!---MARKER_GEN_START--> 4 Create and run a new container from an image 5 6 ### Aliases 7 8 `docker container run`, `docker run` 9 10 ### Options 11 12 | Name | Type | Default | Description | 13 |:------------------------------------------------------|:--------------|:----------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 14 | [`--add-host`](#add-host) | `list` | | Add a custom host-to-IP mapping (host:ip) | 15 | `--annotation` | `map` | `map[]` | Add an annotation to the container (passed through to the OCI runtime) | 16 | [`-a`](#attach), [`--attach`](#attach) | `list` | | Attach to STDIN, STDOUT or STDERR | 17 | `--blkio-weight` | `uint16` | `0` | Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0) | 18 | `--blkio-weight-device` | `list` | | Block IO weight (relative device weight) | 19 | `--cap-add` | `list` | | Add Linux capabilities | 20 | `--cap-drop` | `list` | | Drop Linux capabilities | 21 | [`--cgroup-parent`](#cgroup-parent) | `string` | | Optional parent cgroup for the container | 22 | `--cgroupns` | `string` | | Cgroup namespace to use (host\|private)<br>'host': Run the container in the Docker host's cgroup namespace<br>'private': Run the container in its own private cgroup namespace<br>'': Use the cgroup namespace as configured by the<br> default-cgroupns-mode option on the daemon (default) | 23 | [`--cidfile`](#cidfile) | `string` | | Write the container ID to the file | 24 | `--cpu-count` | `int64` | `0` | CPU count (Windows only) | 25 | `--cpu-percent` | `int64` | `0` | CPU percent (Windows only) | 26 | `--cpu-period` | `int64` | `0` | Limit CPU CFS (Completely Fair Scheduler) period | 27 | `--cpu-quota` | `int64` | `0` | Limit CPU CFS (Completely Fair Scheduler) quota | 28 | `--cpu-rt-period` | `int64` | `0` | Limit CPU real-time period in microseconds | 29 | `--cpu-rt-runtime` | `int64` | `0` | Limit CPU real-time runtime in microseconds | 30 | `-c`, `--cpu-shares` | `int64` | `0` | CPU shares (relative weight) | 31 | `--cpus` | `decimal` | | Number of CPUs | 32 | `--cpuset-cpus` | `string` | | CPUs in which to allow execution (0-3, 0,1) | 33 | `--cpuset-mems` | `string` | | MEMs in which to allow execution (0-3, 0,1) | 34 | [`-d`](#detach), [`--detach`](#detach) | | | Run container in background and print container ID | 35 | [`--detach-keys`](#detach-keys) | `string` | | Override the key sequence for detaching a container | 36 | [`--device`](#device) | `list` | | Add a host device to the container | 37 | [`--device-cgroup-rule`](#device-cgroup-rule) | `list` | | Add a rule to the cgroup allowed devices list | 38 | `--device-read-bps` | `list` | | Limit read rate (bytes per second) from a device | 39 | `--device-read-iops` | `list` | | Limit read rate (IO per second) from a device | 40 | `--device-write-bps` | `list` | | Limit write rate (bytes per second) to a device | 41 | `--device-write-iops` | `list` | | Limit write rate (IO per second) to a device | 42 | `--disable-content-trust` | `bool` | `true` | Skip image verification | 43 | `--dns` | `list` | | Set custom DNS servers | 44 | `--dns-option` | `list` | | Set DNS options | 45 | `--dns-search` | `list` | | Set custom DNS search domains | 46 | `--domainname` | `string` | | Container NIS domain name | 47 | `--entrypoint` | `string` | | Overwrite the default ENTRYPOINT of the image | 48 | [`-e`](#env), [`--env`](#env) | `list` | | Set environment variables | 49 | `--env-file` | `list` | | Read in a file of environment variables | 50 | `--expose` | `list` | | Expose a port or a range of ports | 51 | [`--gpus`](#gpus) | `gpu-request` | | GPU devices to add to the container ('all' to pass all GPUs) | 52 | `--group-add` | `list` | | Add additional groups to join | 53 | `--health-cmd` | `string` | | Command to run to check health | 54 | `--health-interval` | `duration` | `0s` | Time between running the check (ms\|s\|m\|h) (default 0s) | 55 | `--health-retries` | `int` | `0` | Consecutive failures needed to report unhealthy | 56 | `--health-start-interval` | `duration` | `0s` | Time between running the check during the start period (ms\|s\|m\|h) (default 0s) | 57 | `--health-start-period` | `duration` | `0s` | Start period for the container to initialize before starting health-retries countdown (ms\|s\|m\|h) (default 0s) | 58 | `--health-timeout` | `duration` | `0s` | Maximum time to allow one check to run (ms\|s\|m\|h) (default 0s) | 59 | `--help` | | | Print usage | 60 | `-h`, `--hostname` | `string` | | Container host name | 61 | [`--init`](#init) | | | Run an init inside the container that forwards signals and reaps processes | 62 | [`-i`](#interactive), [`--interactive`](#interactive) | | | Keep STDIN open even if not attached | 63 | `--io-maxbandwidth` | `bytes` | `0` | Maximum IO bandwidth limit for the system drive (Windows only) | 64 | `--io-maxiops` | `uint64` | `0` | Maximum IOps limit for the system drive (Windows only) | 65 | `--ip` | `string` | | IPv4 address (e.g., 172.30.100.104) | 66 | `--ip6` | `string` | | IPv6 address (e.g., 2001:db8::33) | 67 | [`--ipc`](#ipc) | `string` | | IPC mode to use | 68 | [`--isolation`](#isolation) | `string` | | Container isolation technology | 69 | `--kernel-memory` | `bytes` | `0` | Kernel memory limit | 70 | [`-l`](#label), [`--label`](#label) | `list` | | Set meta data on a container | 71 | `--label-file` | `list` | | Read in a line delimited file of labels | 72 | `--link` | `list` | | Add link to another container | 73 | `--link-local-ip` | `list` | | Container IPv4/IPv6 link-local addresses | 74 | [`--log-driver`](#log-driver) | `string` | | Logging driver for the container | 75 | `--log-opt` | `list` | | Log driver options | 76 | `--mac-address` | `string` | | Container MAC address (e.g., 92:d0:c6:0a:29:33) | 77 | [`-m`](#memory), [`--memory`](#memory) | `bytes` | `0` | Memory limit | 78 | `--memory-reservation` | `bytes` | `0` | Memory soft limit | 79 | `--memory-swap` | `bytes` | `0` | Swap limit equal to memory plus swap: '-1' to enable unlimited swap | 80 | `--memory-swappiness` | `int64` | `-1` | Tune container memory swappiness (0 to 100) | 81 | [`--mount`](#mount) | `mount` | | Attach a filesystem mount to the container | 82 | [`--name`](#name) | `string` | | Assign a name to the container | 83 | [`--network`](#network) | `network` | | Connect a container to a network | 84 | `--network-alias` | `list` | | Add network-scoped alias for the container | 85 | `--no-healthcheck` | | | Disable any container-specified HEALTHCHECK | 86 | `--oom-kill-disable` | | | Disable OOM Killer | 87 | `--oom-score-adj` | `int` | `0` | Tune host's OOM preferences (-1000 to 1000) | 88 | [`--pid`](#pid) | `string` | | PID namespace to use | 89 | `--pids-limit` | `int64` | `0` | Tune container pids limit (set -1 for unlimited) | 90 | `--platform` | `string` | | Set platform if server is multi-platform capable | 91 | [`--privileged`](#privileged) | | | Give extended privileges to this container | 92 | [`-p`](#publish), [`--publish`](#publish) | `list` | | Publish a container's port(s) to the host | 93 | [`-P`](#publish-all), [`--publish-all`](#publish-all) | | | Publish all exposed ports to random ports | 94 | [`--pull`](#pull) | `string` | `missing` | Pull image before running (`always`, `missing`, `never`) | 95 | `-q`, `--quiet` | | | Suppress the pull output | 96 | [`--read-only`](#read-only) | | | Mount the container's root filesystem as read only | 97 | [`--restart`](#restart) | `string` | `no` | Restart policy to apply when a container exits | 98 | [`--rm`](#rm) | | | Automatically remove the container when it exits | 99 | `--runtime` | `string` | | Runtime to use for this container | 100 | [`--security-opt`](#security-opt) | `list` | | Security Options | 101 | `--shm-size` | `bytes` | `0` | Size of /dev/shm | 102 | `--sig-proxy` | `bool` | `true` | Proxy received signals to the process | 103 | [`--stop-signal`](#stop-signal) | `string` | | Signal to stop the container | 104 | [`--stop-timeout`](#stop-timeout) | `int` | `0` | Timeout (in seconds) to stop a container | 105 | [`--storage-opt`](#storage-opt) | `list` | | Storage driver options for the container | 106 | [`--sysctl`](#sysctl) | `map` | `map[]` | Sysctl options | 107 | [`--tmpfs`](#tmpfs) | `list` | | Mount a tmpfs directory | 108 | [`-t`](#tty), [`--tty`](#tty) | | | Allocate a pseudo-TTY | 109 | [`--ulimit`](#ulimit) | `ulimit` | | Ulimit options | 110 | `-u`, `--user` | `string` | | Username or UID (format: <name\|uid>[:<group\|gid>]) | 111 | [`--userns`](#userns) | `string` | | User namespace to use | 112 | [`--uts`](#uts) | `string` | | UTS namespace to use | 113 | [`-v`](#volume), [`--volume`](#volume) | `list` | | Bind mount a volume | 114 | `--volume-driver` | `string` | | Optional volume driver for the container | 115 | [`--volumes-from`](#volumes-from) | `list` | | Mount volumes from the specified container(s) | 116 | [`-w`](#workdir), [`--workdir`](#workdir) | `string` | | Working directory inside the container | 117 118 119 <!---MARKER_GEN_END--> 120 121 ## Description 122 123 The `docker run` command runs a command in a new container, pulling the image if needed and starting the container. 124 125 You can restart a stopped container with all its previous changes intact using `docker start`. 126 Use `docker ps -a` to view a list of all containers, including those that are stopped. 127 128 ## Examples 129 130 ### <a name="name"></a> Assign name (--name) 131 132 The `--name` flag lets you specify a custom identifier for a container. The 133 following example runs a container named `test` using the `nginx:alpine` image 134 in [detached mode](#detach). 135 136 ```console 137 $ docker run --name test -d nginx:alpine 138 4bed76d3ad428b889c56c1ecc2bf2ed95cb08256db22dc5ef5863e1d03252a19 139 $ docker ps 140 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 141 4bed76d3ad42 nginx:alpine "/docker-entrypoint.…" 1 second ago Up Less than a second 80/tcp test 142 ``` 143 144 You can reference the container by name with other commands. For example, the 145 following commands stop and remove a container named `test`: 146 147 ```console 148 $ docker stop test 149 test 150 $ docker rm test 151 test 152 ``` 153 154 If you don't specify a custom name using the `--name` flag, the daemon assigns 155 a randomly generated name, such as `vibrant_cannon`, to the container. Using a 156 custom-defined name provides the benefit of having an easy-to-remember ID for a 157 container. 158 159 Moreover, if you connect the container to a user-defined bridge network, other 160 containers on the same network can refer to the container by name via DNS. 161 162 ```console 163 $ docker network create mynet 164 cb79f45948d87e389e12013fa4d969689ed2c3316985dd832a43aaec9a0fe394 165 $ docker run --name test --net mynet -d nginx:alpine 166 58df6ecfbc2ad7c42d088ed028d367f9e22a5f834d7c74c66c0ab0485626c32a 167 $ docker run --net mynet busybox:latest ping test 168 PING test (172.18.0.2): 56 data bytes 169 64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.073 ms 170 64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.411 ms 171 64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.319 ms 172 64 bytes from 172.18.0.2: seq=3 ttl=64 time=0.383 ms 173 ... 174 ``` 175 176 ### <a name="cidfile"></a> Capture container ID (--cidfile) 177 178 To help with automation, you can have Docker write the container ID out to a 179 file of your choosing. This is similar to how some programs might write out 180 their process ID to a file (you might've seen them as PID files): 181 182 ```console 183 $ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test" 184 ``` 185 186 This creates a container and prints `test` to the console. The `cidfile` 187 flag makes Docker attempt to create a new file and write the container ID to it. 188 If the file exists already, Docker returns an error. Docker closes this 189 file when `docker run` exits. 190 191 ### <a name="pid"></a> PID settings (--pid) 192 193 ```text 194 --pid="" : Set the PID (Process) Namespace mode for the container, 195 'container:<name|id>': joins another container's PID namespace 196 'host': use the host's PID namespace inside the container 197 ``` 198 199 By default, all containers have the PID namespace enabled. 200 201 PID namespace provides separation of processes. The PID Namespace removes the 202 view of the system processes, and allows process ids to be reused including 203 PID 1. 204 205 In certain cases you want your container to share the host's process namespace, 206 allowing processes within the container to see all of the processes on the 207 system. For example, you could build a container with debugging tools like 208 `strace` or `gdb`, but want to use these tools when debugging processes within 209 the container. 210 211 #### Example: run htop inside a container 212 213 To run `htop` in a container that shares the process namespac of the host: 214 215 1. Run an alpine container with the `--pid=host` option: 216 217 ```console 218 $ docker run --rm -it --pid=host alpine 219 ``` 220 221 2. Install `htop` in the container: 222 223 ```console 224 / # apk add htop 225 fetch https://dl-cdn.alpinelinux.org/alpine/v3.18/main/aarch64/APKINDEX.tar.gz 226 fetch https://dl-cdn.alpinelinux.org/alpine/v3.18/community/aarch64/APKINDEX.tar.gz 227 (1/3) Installing ncurses-terminfo-base (6.4_p20230506-r0) 228 (2/3) Installing libncursesw (6.4_p20230506-r0) 229 (3/3) Installing htop (3.2.2-r1) 230 Executing busybox-1.36.1-r2.trigger 231 OK: 9 MiB in 18 packages 232 ``` 233 234 3. Invoke the `htop` command. 235 236 ```console 237 / # htop 238 ``` 239 240 #### Example, join another container's PID namespace 241 242 Joining another container's PID namespace can be useful for debugging that 243 container. 244 245 1. Start a container running a Redis server: 246 247 ```console 248 $ docker run --rm --name my-nginx -d nginx:alpine 249 ``` 250 251 2. Run an Alpine container that attaches the `--pid` namespace to the 252 `my-nginx` container: 253 254 ```console 255 $ docker run --rm -it --pid=container:my-nginx \ 256 --cap-add SYS_PTRACE \ 257 --security-opt seccomp=unconfined \ 258 alpine 259 ``` 260 261 3. Install `strace` in the Alpine container: 262 263 ```console 264 / # apk add strace 265 ``` 266 267 4. Attach to process 1, the process ID of the `my-nginx` container: 268 269 ```console 270 / # strace -p 1 271 strace: Process 1 attached 272 ``` 273 274 ### <a name="userns"></a> Disable namespace remapping for a container (--userns) 275 276 If you enable user namespaces on the daemon, 277 all containers are started with user namespaces enabled by default. 278 To disable user namespace remapping for a specific container, 279 you can set the `--userns` flag to `host`. 280 281 ```console 282 docker run --userns=host hello-world 283 ``` 284 285 `host` is the only valid value for the `--userns` flag. 286 287 For more information, refer to [Isolate containers with a user namespace](https://docs.docker.com/engine/security/userns-remap/). 288 289 ### <a name="uts"></a> UTS settings (--uts) 290 291 ```text 292 --uts="" : Set the UTS namespace mode for the container 293 'host': use the host's UTS namespace inside the container 294 ``` 295 296 The UTS namespace is for setting the hostname and the domain that's visible to 297 running processes in that namespace. By default, all containers, including 298 those with `--network=host`, have their own UTS namespace. Setting `--uts` to 299 `host` results in the container using the same UTS namespace as the host. 300 301 > **Note** 302 > 303 > Docker disallows combining the `--hostname` and `--domainname` flags with 304 > `--uts=host`. This is to prevent containers running in the host's UTS 305 > namespace from attempting to change the hosts' configuration. 306 307 You may wish to share the UTS namespace with the host if you would like the 308 hostname of the container to change as the hostname of the host changes. A more 309 advanced use case would be changing the host's hostname from a container. 310 311 ### <a name="ipc"></a> IPC settings (--ipc) 312 313 ```text 314 --ipc="MODE" : Set the IPC mode for the container 315 ``` 316 317 The `--ipc` flag accepts the following values: 318 319 | Value | Description | 320 |:---------------------------|:----------------------------------------------------------------------------------| 321 | "" | Use daemon's default. | 322 | "none" | Own private IPC namespace, with /dev/shm not mounted. | 323 | "private" | Own private IPC namespace. | 324 | "shareable" | Own private IPC namespace, with a possibility to share it with other containers. | 325 | "container:<_name-or-ID_>" | Join another ("shareable") container's IPC namespace. | 326 | "host" | Use the host system's IPC namespace. | 327 328 If not specified, daemon default is used, which can either be `"private"` 329 or `"shareable"`, depending on the daemon version and configuration. 330 331 [System V interprocess communication (IPC)](https://linux.die.net/man/5/ipc) 332 namespaces provide separation of named shared memory segments, semaphores and 333 message queues. 334 335 Shared memory segments are used to accelerate inter-process communication at 336 memory speed, rather than through pipes or through the network stack. Shared 337 memory is commonly used by databases and custom-built (typically C/OpenMPI, 338 C++/using boost libraries) high performance applications for scientific 339 computing and financial services industries. If these types of applications 340 are broken into multiple containers, you might need to share the IPC mechanisms 341 of the containers, using `"shareable"` mode for the main (i.e. "donor") 342 container, and `"container:<donor-name-or-ID>"` for other containers. 343 344 ### <a name="privileged"></a> Escalate container privileges (--privileged) 345 346 The `--privileged` flag gives the following capabilities to a container: 347 348 - Enables all Linux kernel capabilities 349 - Disables the default seccomp profile 350 - Disables the default AppArmor profile 351 - Disables the SELinux process label 352 - Grants access to all host devices 353 - Makes `/sys` read-write 354 - Makes cgroups mounts read-write 355 356 In other words, the container can then do almost everything that the host can 357 do. This flag exists to allow special use-cases, like running Docker within 358 Docker. 359 360 > **Warning** 361 > 362 > Use the `--privileged` flag with caution. 363 > A container with `--privileged` is not a securely sandboxed process. 364 > Containers in this mode can get a root shell on the host 365 > and take control over the system. 366 > 367 > For most use cases, this flag should not be the preferred solution. 368 > If your container requires escalated privileges, 369 > you should prefer to explicitly grant the necessary permissions, 370 > for example by adding individual kernel capabilities with `--cap-add`. 371 > 372 > For more information, see 373 > [Runtime privilege and Linux capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) 374 { .warning } 375 376 The following example doesn't work, because by default, Docker drops most 377 potentially dangerous kernel capabilities, including `CAP_SYS_ADMIN ` (which is 378 required to mount filesystems). 379 380 ```console 381 $ docker run -t -i --rm ubuntu bash 382 root@bc338942ef20:/# mount -t tmpfs none /mnt 383 mount: permission denied 384 ``` 385 386 It works when you add the `--privileged` flag: 387 388 ```console 389 $ docker run -t -i --privileged ubuntu bash 390 root@50e3f57e16e6:/# mount -t tmpfs none /mnt 391 root@50e3f57e16e6:/# df -h 392 Filesystem Size Used Avail Use% Mounted on 393 none 1.9G 0 1.9G 0% /mnt 394 ``` 395 396 ### <a name="workdir"></a> Set working directory (-w, --workdir) 397 398 ```console 399 $ docker run -w /path/to/dir/ -i -t ubuntu pwd 400 ``` 401 402 The `-w` option runs the command executed inside the directory specified, in this example, 403 `/path/to/dir/`. If the path doesn't exist, Docker creates it inside the container. 404 405 ### <a name="storage-opt"></a> Set storage driver options per container (--storage-opt) 406 407 ```console 408 $ docker run -it --storage-opt size=120G fedora /bin/bash 409 ``` 410 411 This (size) constraints the container filesystem size to 120G at creation time. 412 This option is only available for the `btrfs`, `overlay2`, `windowsfilter`, 413 and `zfs` storage drivers. 414 415 For the `overlay2` storage driver, the size option is only available if the 416 backing filesystem is `xfs` and mounted with the `pquota` mount option. 417 Under these conditions, you can pass any size less than the backing filesystem size. 418 419 For the `windowsfilter`, `btrfs`, and `zfs` storage drivers, you cannot pass a 420 size less than the Default BaseFS Size. 421 422 ### <a name="tmpfs"></a> Mount tmpfs (--tmpfs) 423 424 The `--tmpfs` flag lets you create a `tmpfs` mount. 425 426 The options that you can pass to `--tmpfs` are identical to the Linux `mount -t 427 tmpfs -o` command. The following example mounts an empty `tmpfs` into the 428 container with the `rw`, `noexec`, `nosuid`, `size=65536k` options. 429 430 ```console 431 $ docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_image 432 ``` 433 434 For more information, see [tmpfs mounts](https://docs.docker.com/storage/tmpfs/). 435 436 ### <a name="volume"></a> Mount volume (-v) 437 438 ```console 439 $ docker run -v $(pwd):$(pwd) -w $(pwd) -i -t ubuntu pwd 440 ``` 441 442 The example above mounts the current directory into the container at the same path 443 using the `-v` flag, sets it as the working directory, and then runs the `pwd` command inside the container. 444 445 As of Docker Engine version 23, you can use relative paths on the host. 446 447 ```console 448 $ docker run -v ./content:/content -w /content -i -t ubuntu pwd 449 ``` 450 451 The example above mounts the `content` directory in the current directory into the container at the 452 `/content` path using the `-v` flag, sets it as the working directory, and then 453 runs the `pwd` command inside the container. 454 455 ```console 456 $ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash 457 ``` 458 459 When the host directory of a bind-mounted volume doesn't exist, Docker 460 automatically creates this directory on the host for you. In the 461 example above, Docker creates the `/doesnt/exist` 462 folder before starting your container. 463 464 ### <a name="read-only"></a> Mount volume read-only (--read-only) 465 466 ```console 467 $ docker run --read-only -v /icanwrite busybox touch /icanwrite/here 468 ``` 469 470 You can use volumes in combination with the `--read-only` flag to control where 471 a container writes files. The `--read-only` flag mounts the container's root 472 filesystem as read only prohibiting writes to locations other than the 473 specified volumes for the container. 474 475 ```console 476 $ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v /path/to/static-docker-binary:/usr/bin/docker busybox sh 477 ``` 478 479 By bind-mounting the Docker Unix socket and statically linked Docker 480 binary (refer to [get the Linux binary](https://docs.docker.com/engine/install/binaries/#install-static-binaries)), 481 you give the container the full access to create and manipulate the host's 482 Docker daemon. 483 484 On Windows, you must specify the paths using Windows-style path semantics. 485 486 ```powershell 487 PS C:\> docker run -v c:\foo:c:\dest microsoft/nanoserver cmd /s /c type c:\dest\somefile.txt 488 Contents of file 489 490 PS C:\> docker run -v c:\foo:d: microsoft/nanoserver cmd /s /c type d:\somefile.txt 491 Contents of file 492 ``` 493 494 The following examples fails when using Windows-based containers, as the 495 destination of a volume or bind mount inside the container must be one of: 496 a non-existing or empty directory; or a drive other than `C:`. Further, the source 497 of a bind mount must be a local directory, not a file. 498 499 ```powershell 500 net use z: \\remotemachine\share 501 docker run -v z:\foo:c:\dest ... 502 docker run -v \\uncpath\to\directory:c:\dest ... 503 docker run -v c:\foo\somefile.txt:c:\dest ... 504 docker run -v c:\foo:c: ... 505 docker run -v c:\foo:c:\existing-directory-with-contents ... 506 ``` 507 508 For in-depth information about volumes, refer to [manage data in containers](https://docs.docker.com/storage/volumes/) 509 510 ### <a name="mount"></a> Add bind mounts or volumes using the --mount flag 511 512 The `--mount` flag allows you to mount volumes, host-directories, and `tmpfs` 513 mounts in a container. 514 515 The `--mount` flag supports most options supported by the `-v` or the 516 `--volume` flag, but uses a different syntax. For in-depth information on the 517 `--mount` flag, and a comparison between `--volume` and `--mount`, refer to 518 [Bind mounts](https://docs.docker.com/storage/bind-mounts/). 519 520 Even though there is no plan to deprecate `--volume`, usage of `--mount` is recommended. 521 522 Examples: 523 524 ```console 525 $ docker run --read-only --mount type=volume,target=/icanwrite busybox touch /icanwrite/here 526 ``` 527 528 ```console 529 $ docker run -t -i --mount type=bind,src=/data,dst=/data busybox sh 530 ``` 531 532 ### <a name="publish"></a> Publish or expose port (-p, --expose) 533 534 ```console 535 $ docker run -p 127.0.0.1:80:8080/tcp nginx:alpine 536 ``` 537 538 This binds port `8080` of the container to TCP port `80` on `127.0.0.1` of the 539 host. You can also specify `udp` and `sctp` ports. The [Networking overview 540 page](https://docs.docker.com/network/) explains in detail how to publish ports 541 with Docker. 542 543 > **Note** 544 > 545 > If you don't specify an IP address (i.e., `-p 80:80` instead of `-p 546 > 127.0.0.1:80:80`) when publishing a container's ports, Docker publishes the 547 > port on all interfaces (address `0.0.0.0`) by default. These ports are 548 > externally accessible. This also applies if you configured UFW to block this 549 > specific port, as Docker manages its own iptables rules. [Read 550 > more](https://docs.docker.com/network/packet-filtering-firewalls/) 551 552 ```console 553 $ docker run --expose 80 nginx:alpine 554 ``` 555 556 This exposes port `80` of the container without publishing the port to the host 557 system's interfaces. 558 559 ### <a name="publish-all"></a> Publish all exposed ports (-P, --publish-all) 560 561 ```console 562 $ docker run -P nginx:alpine 563 ``` 564 565 The `-P`, or `--publish-all`, flag publishes all the exposed ports to the host. 566 Docker binds each exposed port to a random port on the host. 567 568 The `-P` flag only publishes port numbers that are explicitly flagged as 569 exposed, either using the Dockerfile `EXPOSE` instruction or the `--expose` 570 flag for the `docker run` command. 571 572 The range of ports are within an *ephemeral port range* defined by 573 `/proc/sys/net/ipv4/ip_local_port_range`. Use the `-p` flag to explicitly map a 574 single port or range of ports. 575 576 ### <a name="pull"></a> Set the pull policy (--pull) 577 578 Use the `--pull` flag to set the image pull policy when creating (and running) 579 the container. 580 581 The `--pull` flag can take one of these values: 582 583 | Value | Description | 584 |:--------------------|:------------------------------------------------------------------------------------------------------------------| 585 | `missing` (default) | Pull the image if it was not found in the image cache, or use the cached image otherwise. | 586 | `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. | 587 | `always` | Always perform a pull before creating the container. | 588 589 When creating (and running) a container from an image, the daemon checks if the 590 image exists in the local image cache. If the image is missing, an error is 591 returned to the CLI, allowing it to initiate a pull. 592 593 The default (`missing`) is to only pull the image if it's not present in the 594 daemon's image cache. This default allows you to run images that only exist 595 locally (for example, images you built from a Dockerfile, but that have not 596 been pushed to a registry), and reduces networking. 597 598 The `always` option always initiates a pull before creating the container. This 599 option makes sure the image is up-to-date, and prevents you from using outdated 600 images, but may not be suitable in situations where you want to test a locally 601 built image before pushing (as pulling the image overwrites the existing image 602 in the image cache). 603 604 The `never` option disables (implicit) pulling images when creating containers, 605 and only uses images that are available in the image cache. If the specified 606 image is not found, an error is produced, and the container is not created. 607 This option is useful in situations where networking is not available, or to 608 prevent images from being pulled implicitly when creating containers. 609 610 The following example shows `docker run` with the `--pull=never` option set, 611 which produces en error as the image is missing in the image-cache: 612 613 ```console 614 $ docker run --pull=never hello-world 615 docker: Error response from daemon: No such image: hello-world:latest. 616 ``` 617 618 ### <a name="env"></a> Set environment variables (-e, --env, --env-file) 619 620 ```console 621 $ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash 622 ``` 623 624 Use the `-e`, `--env`, and `--env-file` flags to set simple (non-array) 625 environment variables in the container you're running, or overwrite variables 626 defined in the Dockerfile of the image you're running. 627 628 You can define the variable and its value when running the container: 629 630 ```console 631 $ docker run --env VAR1=value1 --env VAR2=value2 ubuntu env | grep VAR 632 VAR1=value1 633 VAR2=value2 634 ``` 635 636 You can also use variables exported to your local environment: 637 638 ```console 639 export VAR1=value1 640 export VAR2=value2 641 642 $ docker run --env VAR1 --env VAR2 ubuntu env | grep VAR 643 VAR1=value1 644 VAR2=value2 645 ``` 646 647 When running the command, the Docker CLI client checks the value the variable 648 has in your local environment and passes it to the container. 649 If no `=` is provided and that variable isn't exported in your local 650 environment, the variable is unset in the container. 651 652 You can also load the environment variables from a file. This file should use 653 the syntax `<variable>=value` (which sets the variable to the given value) or 654 `<variable>` (which takes the value from the local environment), and `#` for 655 comments. Lines beginning with `#` are treated as line comments and are 656 ignored, whereas a `#` appearing anywhere else in a line is treated as part of 657 the variable value. 658 659 ```console 660 $ cat env.list 661 # This is a comment 662 VAR1=value1 663 VAR2=value2 664 USER 665 666 $ docker run --env-file env.list ubuntu env | grep -E 'VAR|USER' 667 VAR1=value1 668 VAR2=value2 669 USER=jonzeolla 670 ``` 671 672 ### <a name="label"></a> Set metadata on container (-l, --label, --label-file) 673 674 A label is a `key=value` pair that applies metadata to a container. To label a container with two labels: 675 676 ```console 677 $ docker run -l my-label --label com.example.foo=bar ubuntu bash 678 ``` 679 680 The `my-label` key doesn't specify a value so the label defaults to an empty 681 string (`""`). To add multiple labels, repeat the label flag (`-l` or `--label`). 682 683 The `key=value` must be unique to avoid overwriting the label value. If you 684 specify labels with identical keys but different values, each subsequent value 685 overwrites the previous. Docker uses the last `key=value` you supply. 686 687 Use the `--label-file` flag to load multiple labels from a file. Delimit each 688 label in the file with an EOL mark. The example below loads labels from a 689 labels file in the current directory: 690 691 ```console 692 $ docker run --label-file ./labels ubuntu bash 693 ``` 694 695 The label-file format is similar to the format for loading environment 696 variables. (Unlike environment variables, labels are not visible to processes 697 running inside a container.) The following example shows a label-file 698 format: 699 700 ```console 701 com.example.label1="a label" 702 703 # this is a comment 704 com.example.label2=another\ label 705 com.example.label3 706 ``` 707 708 You can load multiple label-files by supplying multiple `--label-file` flags. 709 710 For additional information on working with labels, see 711 [Labels](https://docs.docker.com/config/labels-custom-metadata/). 712 713 ### <a name="network"></a> Connect a container to a network (--network) 714 715 To start a container and connect it to a network, use the `--network` option. 716 717 The following commands create a network named `my-net` and adds a `busybox` container 718 to the `my-net` network. 719 720 ```console 721 $ docker network create my-net 722 $ docker run -itd --network=my-net busybox 723 ``` 724 725 You can also choose the IP addresses for the container with `--ip` and `--ip6` 726 flags when you start the container on a user-defined network. To assign a 727 static IP to containers, you must specify subnet block for the network. 728 729 ```console 730 $ docker network create --subnet 192.0.2.0/24 my-net 731 $ docker run -itd --network=my-net --ip=192.0.2.69 busybox 732 ``` 733 734 If you want to add a running container to a network use the `docker network connect` subcommand. 735 736 You can connect multiple containers to the same network. Once connected, the 737 containers can communicate using only another container's IP address 738 or name. For `overlay` networks or custom plugins that support multi-host 739 connectivity, containers connected to the same multi-host network but launched 740 from different Engines can also communicate in this way. 741 742 > **Note** 743 > 744 > The default bridge network only allow containers to communicate with each other using 745 > internal IP addresses. User-created bridge networks provide DNS resolution between 746 > containers using container names. 747 748 You can disconnect a container from a network using the `docker network 749 disconnect` command. 750 751 For more information on connecting a container to a network when using the `run` command, see the ["*Docker network overview*"](https://docs.docker.com/network/). 752 753 ### <a name="volumes-from"></a> Mount volumes from container (--volumes-from) 754 755 ```console 756 $ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd 757 ``` 758 759 The `--volumes-from` flag mounts all the defined volumes from the referenced 760 containers. You can specify more than one container by repetitions of the `--volumes-from` 761 argument. The container ID may be optionally suffixed with `:ro` or `:rw` to 762 mount the volumes in read-only or read-write mode, respectively. By default, 763 Docker mounts the volumes in the same mode (read write or read only) as 764 the reference container. 765 766 Labeling systems like SELinux require placing proper labels on volume 767 content mounted into a container. Without a label, the security system might 768 prevent the processes running inside the container from using the content. By 769 default, Docker does not change the labels set by the OS. 770 771 To change the label in the container context, you can add either of two suffixes 772 `:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file 773 objects on the shared volumes. The `z` option tells Docker that two containers 774 share the volume content. As a result, Docker labels the content with a shared 775 content label. Shared volume labels allow all containers to read/write content. 776 The `Z` option tells Docker to label the content with a private unshared label. 777 Only the current container can use a private volume. 778 779 ### <a name="detach"></a> Detached mode (-d, --detach) 780 781 The `--detach` (or `-d`) flag starts a container as a background process that 782 doesn't occupy your terminal window. By design, containers started in detached 783 mode exit when the root process used to run the container exits, unless you 784 also specify the `--rm` option. If you use `-d` with `--rm`, the container is 785 removed when it exits or when the daemon exits, whichever happens first. 786 787 Don't pass a `service x start` command to a detached container. For example, 788 this command attempts to start the `nginx` service. 789 790 ```console 791 $ docker run -d -p 80:80 my_image service nginx start 792 ``` 793 794 This succeeds in starting the `nginx` service inside the container. However, it 795 fails the detached container paradigm in that, the root process (`service nginx 796 start`) returns and the detached container stops as designed. As a result, the 797 `nginx` service starts but can't be used. Instead, to start a process such as 798 the `nginx` web server do the following: 799 800 ```console 801 $ docker run -d -p 80:80 my_image nginx -g 'daemon off;' 802 ``` 803 804 To do input/output with a detached container use network connections or shared 805 volumes. These are required because the container is no longer listening to the 806 command line where `docker run` was run. 807 808 ### <a name="detach-keys"></a> Override the detach sequence (--detach-keys) 809 810 Use the `--detach-keys` option to override the Docker key sequence for detach. 811 This is useful if the Docker default sequence conflicts with key sequence you 812 use for other applications. There are two ways to define your own detach key 813 sequence, as a per-container override or as a configuration property on your 814 entire configuration. 815 816 To override the sequence for an individual container, use the 817 `--detach-keys="<sequence>"` flag with the `docker attach` command. The format of 818 the `<sequence>` is either a letter [a-Z], or the `ctrl-` combined with any of 819 the following: 820 821 * `a-z` (a single lowercase alpha character ) 822 * `@` (at sign) 823 * `[` (left bracket) 824 * `\\` (two backward slashes) 825 * `_` (underscore) 826 * `^` (caret) 827 828 These `a`, `ctrl-a`, `X`, or `ctrl-\\` values are all examples of valid key 829 sequences. To configure a different configuration default key sequence for all 830 containers, see [**Configuration file** section](https://docs.docker.com/engine/reference/commandline/cli/#configuration-files). 831 832 ### <a name="device"></a> Add host device to container (--device) 833 834 ```console 835 $ docker run -it --rm \ 836 --device=/dev/sdc:/dev/xvdc \ 837 --device=/dev/sdd \ 838 --device=/dev/zero:/dev/foobar \ 839 ubuntu ls -l /dev/{xvdc,sdd,foobar} 840 841 brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc 842 brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd 843 crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/foobar 844 ``` 845 846 It's often necessary to directly expose devices to a container. The `--device` 847 option enables that. For example, adding a specific block storage device or loop 848 device or audio device to an otherwise unprivileged container 849 (without the `--privileged` flag) and have the application directly access it. 850 851 By default, the container is able to `read`, `write` and `mknod` these devices. 852 This can be overridden using a third `:rwm` set of options to each `--device` 853 flag. If the container is running in privileged mode, then Docker ignores the 854 specified permissions. 855 856 ```console 857 $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc 858 859 Command (m for help): q 860 $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc 861 You will not be able to write the partition table. 862 863 Command (m for help): q 864 865 $ docker run --device=/dev/sda:/dev/xvdc:rw --rm -it ubuntu fdisk /dev/xvdc 866 867 Command (m for help): q 868 869 $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc 870 fdisk: unable to open /dev/xvdc: Operation not permitted 871 ``` 872 873 > **Note** 874 > 875 > The `--device` option cannot be safely used with ephemeral devices. You shouldn't 876 > add block devices that may be removed to untrusted containers with `--device`. 877 878 For Windows, the format of the string passed to the `--device` option is in 879 the form of `--device=<IdType>/<Id>`. Beginning with Windows Server 2019 880 and Windows 10 October 2018 Update, Windows only supports an IdType of 881 `class` and the Id as a [device interface class 882 GUID](https://docs.microsoft.com/en-us/windows-hardware/drivers/install/overview-of-device-interface-classes). 883 Refer to the table defined in the [Windows container 884 docs](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/hardware-devices-in-containers) 885 for a list of container-supported device interface class GUIDs. 886 887 If you specify this option for a process-isolated Windows container, Docker makes 888 _all_ devices that implement the requested device interface class GUID 889 available in the container. For example, the command below makes all COM 890 ports on the host visible in the container. 891 892 ```powershell 893 PS C:\> docker run --device=class/86E0D1E0-8089-11D0-9CE4-08003E301F73 mcr.microsoft.com/windows/servercore:ltsc2019 894 ``` 895 896 > **Note** 897 > 898 > The `--device` option is only supported on process-isolated Windows containers, 899 > and produces an error if the container isolation is `hyperv`. 900 901 #### CDI devices 902 903 > **Note** 904 > 905 > This is experimental feature and as such doesn't represent a stable API. 906 907 Container Device Interface (CDI) is a 908 [standardized](https://github.com/cncf-tags/container-device-interface/blob/main/SPEC.md) 909 mechanism for container runtimes to create containers which are able to 910 interact with third party devices. 911 912 With CDI, device configurations are defined using a JSON file. In addition to 913 enabling the container to interact with the device node, it also lets you 914 specify additional configuration for the device, such as kernel modules, host 915 libraries, and environment variables. 916 917 You can reference a CDI device with the `--device` flag using the 918 fully-qualified name of the device, as shown in the following example: 919 920 ```console 921 $ docker run --device=vendor.com/class=device-name --rm -it ubuntu 922 ``` 923 924 This starts an `ubuntu` container with access to the specified CDI device, 925 `vendor.com/class=device-name`, assuming that: 926 927 - A valid CDI specification (JSON file) for the requested device is available 928 on the system running the daemon, in one of the configured CDI specification 929 directories. 930 - The CDI feature has been enabled on the daemon side, see [Enable CDI 931 devices](https://docs.docker.com/reference/cli/dockerd/#enable-cdi-devices). 932 933 ### <a name="attach"></a> Attach to STDIN/STDOUT/STDERR (-a, --attach) 934 935 The `--attach` (or `-a`) flag tells `docker run` to bind to the container's 936 `STDIN`, `STDOUT` or `STDERR`. This makes it possible to manipulate the output 937 and input as needed. You can specify to which of the three standard streams 938 (`STDIN`, `STDOUT`, `STDERR`) you'd like to connect instead, as in: 939 940 ```console 941 $ docker run -a stdin -a stdout -i -t ubuntu /bin/bash 942 ``` 943 944 The following example pipes data into a container and prints the container's ID 945 by attaching only to the container's `STDIN`. 946 947 ```console 948 $ echo "test" | docker run -i -a stdin ubuntu cat - 949 ``` 950 951 The following example doesn't print anything to the console unless there's an 952 error because output is only attached to the `STDERR` of the container. The 953 container's logs still store what's written to `STDERR` and `STDOUT`. 954 955 ```console 956 $ docker run -a stderr ubuntu echo test 957 ``` 958 959 The following example shows a way of using `--attach` to pipe a file into a 960 container. The command prints the container's ID after the build completes and 961 you can retrieve the build logs using `docker logs`. This is useful if you need 962 to pipe a file or something else into a container and retrieve the container's 963 ID once the container has finished running. 964 965 ```console 966 $ cat somefile | docker run -i -a stdin mybuilder dobuild 967 ``` 968 969 > **Note** 970 > 971 > A process running as PID 1 inside a container is treated specially by 972 > Linux: it ignores any signal with the default action. So, the process 973 > doesn't terminate on `SIGINT` or `SIGTERM` unless it's coded to do so. 974 975 See also [the `docker cp` command](container_cp.md). 976 977 ### <a name="interactive"></a> Keep STDIN open (-i, --interactive) 978 979 The `--interactive` (or `-i`) flag keeps the container's `STDIN` open, and lets 980 you send input to the container through standard input. 981 982 ```console 983 $ echo hello | docker run --rm -i busybox cat 984 hello 985 ``` 986 987 The `-i` flag is most often used together with the `--tty` flag to bind the I/O 988 streams of the container to a pseudo terminal, creating an interactive terminal 989 session for the container. See [Allocate a pseudo-TTY](#tty) for more examples. 990 991 ```console 992 $ docker run -it debian 993 root@10a3e71492b0:/# factor 90 994 90: 2 3 3 5 995 root@10a3e71492b0:/# exit 996 exit 997 ``` 998 999 Using the `-i` flag on its own allows for composition, such as piping input to 1000 containers: 1001 1002 ```console 1003 $ docker run --rm -i busybox echo "foo bar baz" \ 1004 | docker run --rm -i busybox awk '{ print $2 }' \ 1005 | docker run --rm -i busybox rev 1006 rab 1007 ``` 1008 1009 ### <a name="init"></a> Specify an init process 1010 1011 You can use the `--init` flag to indicate that an init process should be used as 1012 the PID 1 in the container. Specifying an init process ensures the usual 1013 responsibilities of an init system, such as reaping zombie processes, are 1014 performed inside the created container. 1015 1016 The default init process used is the first `docker-init` executable found in the 1017 system path of the Docker daemon process. This `docker-init` binary, included in 1018 the default installation, is backed by [tini](https://github.com/krallin/tini). 1019 1020 ### <a name="tty"></a> Allocate a pseudo-TTY (-t, --tty) 1021 1022 The `--tty` (or `-t`) flag attaches a pseudo-TTY to the container, connecting 1023 your terminal to the I/O streams of the container. Allocating a pseudo-TTY to 1024 the container means that you get access to input and output feature that TTY 1025 devices provide. 1026 1027 For example, the following command runs the `passwd` command in a `debian` 1028 container, to set a new password for the `root` user. 1029 1030 ```console 1031 $ docker run -i debian passwd root 1032 New password: karjalanpiirakka9 1033 Retype new password: karjalanpiirakka9 1034 passwd: password updated successfully 1035 ``` 1036 1037 If you run this command with only the `-i` flag (which lets you send text to 1038 `STDIN` of the container), the `passwd` prompt displays the password in plain 1039 text. However, if you try the same thing but also adding the `-t` flag, the 1040 password is hidden: 1041 1042 ```console 1043 $ docker run -it debian passwd root 1044 New password: 1045 Retype new password: 1046 passwd: password updated successfully 1047 ``` 1048 1049 This is because `passwd` can suppress the output of characters to the terminal 1050 using the echo-off TTY feature. 1051 1052 You can use the `-t` flag without `-i` flag. This still allocates a pseudo-TTY 1053 to the container, but with no way of writing to `STDIN`. The only time this 1054 might be useful is if the output of the container requires a TTY environment. 1055 1056 ### <a name="cgroup-parent"></a> Specify custom cgroups 1057 1058 Using the `--cgroup-parent` flag, you can pass a specific cgroup to run a 1059 container in. This allows you to create and manage cgroups on their own. You can 1060 define custom resources for those cgroups and put containers under a common 1061 parent group. 1062 1063 ### <a name="device-cgroup-rule"></a> Using dynamically created devices (--device-cgroup-rule) 1064 1065 Docker assigns devices available to a container at creation time. The 1066 assigned devices are added to the cgroup.allow file and 1067 created into the container when it runs. This poses a problem when 1068 you need to add a new device to running container. 1069 1070 One solution is to add a more permissive rule to a container 1071 allowing it access to a wider range of devices. For example, supposing 1072 the container needs access to a character device with major `42` and 1073 any number of minor numbers (added as new devices appear), add the 1074 following rule: 1075 1076 ```console 1077 $ docker run -d --device-cgroup-rule='c 42:* rmw' --name my-container my-image 1078 ``` 1079 1080 Then, a user could ask `udev` to execute a script that would `docker exec my-container mknod newDevX c 42 <minor>` 1081 the required device when it is added. 1082 1083 > **Note**: You still need to explicitly add initially present devices to the 1084 > `docker run` / `docker create` command. 1085 1086 ### <a name="gpus"></a> Access an NVIDIA GPU 1087 1088 The `--gpus` flag allows you to access NVIDIA GPU resources. First you need to 1089 install the [nvidia-container-runtime](https://nvidia.github.io/nvidia-container-runtime/). 1090 1091 > **Note** 1092 > 1093 > You can also specify a GPU as a CDI device with the `--device` flag, see 1094 > [CDI devices](#cdi-devices). 1095 1096 Read [Specify a container's resources](https://docs.docker.com/config/containers/resource_constraints/) 1097 for more information. 1098 1099 To use `--gpus`, specify which GPUs (or all) to use. If you provide no value, Docker uses all 1100 available GPUs. The example below exposes all available GPUs. 1101 1102 ```console 1103 $ docker run -it --rm --gpus all ubuntu nvidia-smi 1104 ``` 1105 1106 Use the `device` option to specify GPUs. The example below exposes a specific 1107 GPU. 1108 1109 ```console 1110 $ docker run -it --rm --gpus device=GPU-3a23c669-1f69-c64e-cf85-44e9b07e7a2a ubuntu nvidia-smi 1111 ``` 1112 1113 The example below exposes the first and third GPUs. 1114 1115 ```console 1116 $ docker run -it --rm --gpus '"device=0,2"' ubuntu nvidia-smi 1117 ``` 1118 1119 ### <a name="restart"></a> Restart policies (--restart) 1120 1121 Use the `--restart` flag to specify a container's *restart policy*. A restart 1122 policy controls whether the Docker daemon restarts a container after exit. 1123 Docker supports the following restart policies: 1124 1125 | Policy | Result | 1126 |:---------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 1127 | `no` | Do not automatically restart the container when it exits. This is the default. | 1128 | `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. | 1129 | `unless-stopped` | Restart the container unless it's explicitly stopped or Docker itself is stopped or restarted. | 1130 | `always` | Always restart the container regardless of the exit status. When you specify always, the Docker daemon tries to restart the container indefinitely. The container always starts on daemon startup, regardless of the current state of the container. | 1131 1132 ```console 1133 $ docker run --restart=always redis 1134 ``` 1135 1136 This runs the `redis` container with a restart policy of **always**. 1137 If the container exits, Docker restarts it. 1138 1139 When a restart policy is active on a container, it shows as either `Up` or 1140 `Restarting` in [`docker ps`](container_ls.md). It can also be useful to use 1141 [`docker events`](system_events.md) to see the restart policy in effect. 1142 1143 An increasing delay (double the previous delay, starting at 100 milliseconds) 1144 is added before each restart to prevent flooding the server. This means the 1145 daemon waits for 100 ms, then 200 ms, 400, 800, 1600, and so on until either 1146 the `on-failure` limit, the maximum delay of 1 minute is hit, or when you 1147 `docker stop` or `docker rm -f` the container. 1148 1149 If a container is successfully restarted (the container is started and runs 1150 for at least 10 seconds), the delay is reset to its default value of 100 ms. 1151 1152 #### Specify a limit for restart attempts 1153 1154 You can specify the maximum amount of times Docker attempts to restart the 1155 container when using the **on-failure** policy. By default, Docker never stops 1156 attempting to restart the container. 1157 1158 The following example runs the `redis` container with a restart policy of 1159 **on-failure** and a maximum restart count of 10. 1160 1161 ```console 1162 $ docker run --restart=on-failure:10 redis 1163 ``` 1164 1165 If the `redis` container exits with a non-zero exit status more than 10 times 1166 in a row, Docker stops trying to restart the container. Providing a maximum 1167 restart limit is only valid for the **on-failure** policy. 1168 1169 #### Inspect container restarts 1170 1171 The number of (attempted) restarts for a container can be obtained using the 1172 [`docker inspect`](inspect.md) command. For example, to get the number of 1173 restarts for container "my-container"; 1174 1175 ```console 1176 $ docker inspect -f "{{ .RestartCount }}" my-container 1177 2 1178 ``` 1179 1180 Or, to get the last time the container was (re)started; 1181 1182 ```console 1183 $ docker inspect -f "{{ .State.StartedAt }}" my-container 1184 2015-03-04T23:47:07.691840179Z 1185 ``` 1186 1187 Combining `--restart` (restart policy) with the `--rm` (clean up) flag results 1188 in an error. On container restart, attached clients are disconnected. 1189 1190 ### <a name="rm"></a> Clean up (--rm) 1191 1192 By default, a container's file system persists even after the container exits. 1193 This makes debugging a lot easier, since you can inspect the container's final 1194 state and you retain all your data. 1195 1196 If you are running short-term **foreground** processes, these container file 1197 systems can start to pile up. If you'd like Docker to automatically clean up 1198 the container and remove the file system when the container exits, use the 1199 `--rm` flag: 1200 1201 ```text 1202 --rm=false: Automatically remove the container when it exits 1203 ``` 1204 1205 > **Note** 1206 > 1207 > If you set the `--rm` flag, Docker also removes the anonymous volumes 1208 > associated with the container when the container is removed. This is similar 1209 > to running `docker rm -v my-container`. Only volumes that are specified 1210 > without a name are removed. For example, when running the following command, 1211 > volume `/foo` is removed, but not `/bar`: 1212 > 1213 > ```console 1214 > $ docker run --rm -v /foo -v awesome:/bar busybox top 1215 > ``` 1216 > 1217 > Volumes inherited via `--volumes-from` are removed with the same logic: 1218 > if the original volume was specified with a name it isn't removed. 1219 1220 ### <a name="add-host"></a> Add entries to container hosts file (--add-host) 1221 1222 You can add other hosts into a container's `/etc/hosts` file by using one or 1223 more `--add-host` flags. This example adds a static address for a host named 1224 `my-hostname`: 1225 1226 ```console 1227 $ docker run --add-host=my-hostname=8.8.8.8 --rm -it alpine 1228 1229 / # ping my-hostname 1230 PING my-hostname (8.8.8.8): 56 data bytes 1231 64 bytes from 8.8.8.8: seq=0 ttl=37 time=93.052 ms 1232 64 bytes from 8.8.8.8: seq=1 ttl=37 time=92.467 ms 1233 64 bytes from 8.8.8.8: seq=2 ttl=37 time=92.252 ms 1234 ^C 1235 --- my-hostname ping statistics --- 1236 4 packets transmitted, 4 packets received, 0% packet loss 1237 round-trip min/avg/max = 92.209/92.495/93.052 ms 1238 ``` 1239 1240 You can wrap an IPv6 address in square brackets: 1241 1242 ```console 1243 $ docker run --add-host my-hostname=[2001:db8::33] --rm -it alpine 1244 ``` 1245 1246 The `--add-host` flag supports a special `host-gateway` value that resolves to 1247 the internal IP address of the host. This is useful when you want containers to 1248 connect to services running on the host machine. 1249 1250 It's conventional to use `host.docker.internal` as the hostname referring to 1251 `host-gateway`. Docker Desktop automatically resolves this hostname, see 1252 [Explore networking features](https://docs.docker.com/desktop/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host). 1253 1254 The following example shows how the special `host-gateway` value works. The 1255 example runs an HTTP server that serves a file from host to container over the 1256 `host.docker.internal` hostname, which resolves to the host's internal IP. 1257 1258 ```console 1259 $ echo "hello from host!" > ./hello 1260 $ python3 -m http.server 8000 1261 Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ... 1262 $ docker run \ 1263 --add-host host.docker.internal=host-gateway \ 1264 curlimages/curl -s host.docker.internal:8000/hello 1265 hello from host! 1266 ``` 1267 1268 The `--add-host` flag also accepts a `:` separator, for example: 1269 1270 ```console 1271 $ docker run --add-host=my-hostname:8.8.8.8 --rm -it alpine 1272 ``` 1273 1274 ### <a name="log-driver"></a> Logging drivers (--log-driver) 1275 1276 The container can have a different logging driver than the Docker daemon. Use 1277 the `--log-driver=<DRIVER>` with the `docker run` command to configure the 1278 container's logging driver. 1279 1280 To learn about the supported logging drivers and how to use them, refer to 1281 [Configure logging drivers](https://docs.docker.com/config/containers/logging/configure/). 1282 1283 To disable logging for a container, set the `--log-driver` flag to `none`: 1284 1285 ```console 1286 $ docker run --log-driver=none -d nginx:alpine 1287 5101d3b7fe931c27c2ba0e65fd989654d297393ad65ae238f20b97a020e7295b 1288 $ docker logs 5101d3b 1289 Error response from daemon: configured logging driver does not support reading 1290 ``` 1291 1292 ### <a name="ulimit"></a> Set ulimits in container (--ulimit) 1293 1294 Since setting `ulimit` settings in a container requires extra privileges not 1295 available in the default container, you can set these using the `--ulimit` flag. 1296 Specify `--ulimit` with a soft and hard limit in the format 1297 `<type>=<soft limit>[:<hard limit>]`. For example: 1298 1299 ```console 1300 $ docker run --ulimit nofile=1024:1024 --rm debian sh -c "ulimit -n" 1301 1024 1302 ``` 1303 1304 > **Note** 1305 > 1306 > If you don't provide a hard limit value, Docker uses the soft limit value 1307 > for both values. If you don't provide any values, they are inherited from 1308 > the default `ulimits` set on the daemon. 1309 1310 > **Note** 1311 > 1312 > The `as` option is deprecated. 1313 > In other words, the following script is not supported: 1314 > 1315 > ```console 1316 > $ docker run -it --ulimit as=1024 fedora /bin/bash 1317 > ``` 1318 1319 Docker sends the values to the appropriate OS `syscall` and doesn't perform any byte conversion. 1320 Take this into account when setting the values. 1321 1322 #### For `nproc` usage 1323 1324 Be careful setting `nproc` with the `ulimit` flag as Linux uses `nproc` to set the 1325 maximum number of processes available to a user, not to a container. For example, start four 1326 containers with `daemon` user: 1327 1328 ```console 1329 $ docker run -d -u daemon --ulimit nproc=3 busybox top 1330 1331 $ docker run -d -u daemon --ulimit nproc=3 busybox top 1332 1333 $ docker run -d -u daemon --ulimit nproc=3 busybox top 1334 1335 $ docker run -d -u daemon --ulimit nproc=3 busybox top 1336 ``` 1337 1338 The 4th container fails and reports a "[8] System error: resource temporarily unavailable" error. 1339 This fails because the caller set `nproc=3` resulting in the first three containers using up 1340 the three processes quota set for the `daemon` user. 1341 1342 ### <a name="stop-signal"></a> Stop container with signal (--stop-signal) 1343 1344 The `--stop-signal` flag sends the system call signal to the 1345 container to exit. This signal can be a signal name in the format `SIG<NAME>`, 1346 for instance `SIGKILL`, or an unsigned number that matches a position in the 1347 kernel's syscall table, for instance `9`. 1348 1349 The default value is defined by [`STOPSIGNAL`](https://docs.docker.com/reference/dockerfile/#stopsignal) 1350 in the image, or `SIGTERM` if the image has no `STOPSIGNAL` defined. 1351 1352 ### <a name="security-opt"></a> Optional security options (--security-opt) 1353 1354 | Option | Description | 1355 |:------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 1356 | `--security-opt="label=user:USER"` | Set the label user for the container | 1357 | `--security-opt="label=role:ROLE"` | Set the label role for the container | 1358 | `--security-opt="label=type:TYPE"` | Set the label type for the container | 1359 | `--security-opt="label=level:LEVEL"` | Set the label level for the container | 1360 | `--security-opt="label=disable"` | Turn off label confinement for the container | 1361 | `--security-opt="apparmor=PROFILE"` | Set the apparmor profile to be applied to the container | 1362 | `--security-opt="no-new-privileges=true"` | Disable container processes from gaining new privileges | 1363 | `--security-opt="seccomp=unconfined"` | Turn off seccomp confinement for the container | 1364 | `--security-opt="seccomp=builtin"` | Use the default (built-in) seccomp profile for the container. This can be used to enable seccomp for a container running on a daemon with a custom default profile set, or with seccomp disabled ("unconfined"). | 1365 | `--security-opt="seccomp=profile.json"` | White-listed syscalls seccomp Json file to be used as a seccomp filter | 1366 1367 The `--security-opt` flag lets you override the default labeling scheme for a 1368 container. Specifying the level in the following command allows you to share 1369 the same content between containers. 1370 1371 ```console 1372 $ docker run --security-opt label=level:s0:c100,c200 -it fedora bash 1373 ``` 1374 1375 > **Note** 1376 > 1377 > Automatic translation of MLS labels isn't supported. 1378 1379 To disable the security labeling for a container entirely, you can use 1380 `label=disable`: 1381 1382 ```console 1383 $ docker run --security-opt label=disable -it ubuntu bash 1384 ``` 1385 1386 If you want a tighter security policy on the processes within a container, you 1387 can specify a custom `type` label. The following example runs a container 1388 that's only allowed to listen on Apache ports: 1389 1390 ```console 1391 $ docker run --security-opt label=type:svirt_apache_t -it ubuntu bash 1392 ``` 1393 1394 > **Note** 1395 > 1396 > You would have to write policy defining a `svirt_apache_t` type. 1397 1398 To prevent your container processes from gaining additional privileges, you can 1399 use the following command: 1400 1401 ```console 1402 $ docker run --security-opt no-new-privileges -it ubuntu bash 1403 ``` 1404 1405 This means that commands that raise privileges such as `su` or `sudo` no longer work. 1406 It also causes any seccomp filters to be applied later, after privileges have been dropped 1407 which may mean you can have a more restrictive set of filters. 1408 For more details, see the [kernel documentation](https://www.kernel.org/doc/Documentation/prctl/no_new_privs.txt). 1409 1410 On Windows, you can use the `--security-opt` flag to specify the `credentialspec` option. 1411 The `credentialspec` must be in the format `file://spec.txt` or `registry://keyname`. 1412 1413 ### <a name="stop-timeout"></a> Stop container with timeout (--stop-timeout) 1414 1415 The `--stop-timeout` flag sets the number of seconds to wait for the container 1416 to stop after sending the pre-defined (see `--stop-signal`) system call signal. 1417 If the container does not exit after the timeout elapses, it's forcibly killed 1418 with a `SIGKILL` signal. 1419 1420 If you set `--stop-timeout` to `-1`, no timeout is applied, and the daemon 1421 waits indefinitely for the container to exit. 1422 1423 The Daemon determines the default, and is 10 seconds for Linux containers, 1424 and 30 seconds for Windows containers. 1425 1426 ### <a name="isolation"></a> Specify isolation technology for container (--isolation) 1427 1428 This option is useful in situations where you are running Docker containers on 1429 Windows. The `--isolation=<value>` option sets a container's isolation technology. 1430 On Linux, the only supported is the `default` option which uses Linux namespaces. 1431 These two commands are equivalent on Linux: 1432 1433 ```console 1434 $ docker run -d busybox top 1435 $ docker run -d --isolation default busybox top 1436 ``` 1437 1438 On Windows, `--isolation` can take one of these values: 1439 1440 | Value | Description | 1441 |:----------|:-------------------------------------------------------------------------------------------| 1442 | `default` | Use the value specified by the Docker daemon's `--exec-opt` or system default (see below). | 1443 | `process` | Shared-kernel namespace isolation. | 1444 | `hyperv` | Hyper-V hypervisor partition-based isolation. | 1445 1446 The default isolation on Windows server operating systems is `process`, and `hyperv` 1447 on Windows client operating systems, such as Windows 10. Process isolation has better 1448 performance, but requires that the image and host use the same kernel version. 1449 1450 On Windows server, assuming the default configuration, these commands are equivalent 1451 and result in `process` isolation: 1452 1453 ```powershell 1454 PS C:\> docker run -d microsoft/nanoserver powershell echo process 1455 PS C:\> docker run -d --isolation default microsoft/nanoserver powershell echo process 1456 PS C:\> docker run -d --isolation process microsoft/nanoserver powershell echo process 1457 ``` 1458 1459 If you have set the `--exec-opt isolation=hyperv` option on the Docker `daemon`, or 1460 are running against a Windows client-based daemon, these commands are equivalent and 1461 result in `hyperv` isolation: 1462 1463 ```powershell 1464 PS C:\> docker run -d microsoft/nanoserver powershell echo hyperv 1465 PS C:\> docker run -d --isolation default microsoft/nanoserver powershell echo hyperv 1466 PS C:\> docker run -d --isolation hyperv microsoft/nanoserver powershell echo hyperv 1467 ``` 1468 1469 ### <a name="memory"></a> Specify hard limits on memory available to containers (-m, --memory) 1470 1471 These parameters always set an upper limit on the memory available to the container. Linux sets this 1472 on the cgroup and applications in a container can query it at `/sys/fs/cgroup/memory/memory.limit_in_bytes`. 1473 1474 On Windows, this affects containers differently depending on what type of isolation you use. 1475 1476 - With `process` isolation, Windows reports the full memory of the host system, not the limit to applications running inside the container 1477 1478 ```powershell 1479 PS C:\> docker run -it -m 2GB --isolation=process microsoft/nanoserver powershell Get-ComputerInfo *memory* 1480 1481 CsTotalPhysicalMemory : 17064509440 1482 CsPhyicallyInstalledMemory : 16777216 1483 OsTotalVisibleMemorySize : 16664560 1484 OsFreePhysicalMemory : 14646720 1485 OsTotalVirtualMemorySize : 19154928 1486 OsFreeVirtualMemory : 17197440 1487 OsInUseVirtualMemory : 1957488 1488 OsMaxProcessMemorySize : 137438953344 1489 ``` 1490 1491 - With `hyperv` isolation, Windows creates 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." 1492 1493 ```powershell 1494 PS C:\> docker run -it -m 2GB --isolation=hyperv microsoft/nanoserver powershell Get-ComputerInfo *memory* 1495 1496 CsTotalPhysicalMemory : 2683355136 1497 CsPhyicallyInstalledMemory : 1498 OsTotalVisibleMemorySize : 2620464 1499 OsFreePhysicalMemory : 2306552 1500 OsTotalVirtualMemorySize : 2620464 1501 OsFreeVirtualMemory : 2356692 1502 OsInUseVirtualMemory : 263772 1503 OsMaxProcessMemorySize : 137438953344 1504 ``` 1505 1506 ### <a name="sysctl"></a> Configure namespaced kernel parameters (sysctls) at runtime (--sysctl) 1507 1508 The `--sysctl` sets namespaced kernel parameters (sysctls) in the 1509 container. For example, to turn on IP forwarding in the containers 1510 network namespace, run this command: 1511 1512 ```console 1513 $ docker run --sysctl net.ipv4.ip_forward=1 someimage 1514 ``` 1515 1516 > **Note** 1517 > 1518 > Not all sysctls are namespaced. Docker does not support changing sysctls 1519 > inside of a container that also modify the host system. As the kernel 1520 > evolves we expect to see more sysctls become namespaced. 1521 1522 1523 #### Currently supported sysctls 1524 1525 IPC Namespace: 1526 1527 - `kernel.msgmax`, `kernel.msgmnb`, `kernel.msgmni`, `kernel.sem`, 1528 `kernel.shmall`, `kernel.shmmax`, `kernel.shmmni`, `kernel.shm_rmid_forced`. 1529 - Sysctls beginning with `fs.mqueue.*` 1530 - If you use the `--ipc=host` option these sysctls are not allowed. 1531 1532 Network Namespace: 1533 1534 - Sysctls beginning with `net.*` 1535 - If you use the `--network=host` option using these sysctls are not allowed. 1536 1537 ## Command internals 1538 1539 The `docker run` command is equivalent to the following API calls: 1540 1541 - `/<API version>/containers/create` 1542 - If that call returns a 404 (image not found), and depending on the `--pull` option ("always", "missing", "never") the call can trigger a `docker pull <image>`. 1543 - `/containers/create` again after pulling the image. 1544 - `/containers/(id)/start` to start the container. 1545 - `/containers/(id)/attach` to attach to the container when starting with the `-it` flags for interactive containers.