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