-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
run.md
1468 lines (1123 loc) · 95.8 KB
/
run.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# run
<!---MARKER_GEN_START-->
Create and run a new container from an image
### Aliases
`docker container run`, `docker run`
### Options
| Name | Type | Default | Description |
|:------------------------------------------------------|:--------------|:----------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`--add-host`](#add-host) | `list` | | Add a custom host-to-IP mapping (host:ip) |
| `--annotation` | `map` | `map[]` | Add an annotation to the container (passed through to the OCI runtime) |
| [`-a`](#attach), [`--attach`](#attach) | `list` | | Attach to STDIN, STDOUT or STDERR |
| `--blkio-weight` | `uint16` | `0` | Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0) |
| `--blkio-weight-device` | `list` | | Block IO weight (relative device weight) |
| `--cap-add` | `list` | | Add Linux capabilities |
| `--cap-drop` | `list` | | Drop Linux capabilities |
| [`--cgroup-parent`](#cgroup-parent) | `string` | | Optional parent cgroup for the container |
| `--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) |
| [`--cidfile`](#cidfile) | `string` | | Write the container ID to the file |
| `--cpu-count` | `int64` | `0` | CPU count (Windows only) |
| `--cpu-percent` | `int64` | `0` | CPU percent (Windows only) |
| `--cpu-period` | `int64` | `0` | Limit CPU CFS (Completely Fair Scheduler) period |
| `--cpu-quota` | `int64` | `0` | Limit CPU CFS (Completely Fair Scheduler) quota |
| `--cpu-rt-period` | `int64` | `0` | Limit CPU real-time period in microseconds |
| `--cpu-rt-runtime` | `int64` | `0` | Limit CPU real-time runtime in microseconds |
| `-c`, `--cpu-shares` | `int64` | `0` | CPU shares (relative weight) |
| `--cpus` | `decimal` | | Number of CPUs |
| `--cpuset-cpus` | `string` | | CPUs in which to allow execution (0-3, 0,1) |
| `--cpuset-mems` | `string` | | MEMs in which to allow execution (0-3, 0,1) |
| [`-d`](#detach), [`--detach`](#detach) | | | Run container in background and print container ID |
| [`--detach-keys`](#detach-keys) | `string` | | Override the key sequence for detaching a container |
| [`--device`](#device) | `list` | | Add a host device to the container |
| [`--device-cgroup-rule`](#device-cgroup-rule) | `list` | | Add a rule to the cgroup allowed devices list |
| `--device-read-bps` | `list` | | Limit read rate (bytes per second) from a device |
| `--device-read-iops` | `list` | | Limit read rate (IO per second) from a device |
| `--device-write-bps` | `list` | | Limit write rate (bytes per second) to a device |
| `--device-write-iops` | `list` | | Limit write rate (IO per second) to a device |
| `--disable-content-trust` | | | Skip image verification |
| `--dns` | `list` | | Set custom DNS servers |
| `--dns-option` | `list` | | Set DNS options |
| `--dns-search` | `list` | | Set custom DNS search domains |
| `--domainname` | `string` | | Container NIS domain name |
| `--entrypoint` | `string` | | Overwrite the default ENTRYPOINT of the image |
| [`-e`](#env), [`--env`](#env) | `list` | | Set environment variables |
| `--env-file` | `list` | | Read in a file of environment variables |
| `--expose` | `list` | | Expose a port or a range of ports |
| [`--gpus`](#gpus) | `gpu-request` | | GPU devices to add to the container ('all' to pass all GPUs) |
| `--group-add` | `list` | | Add additional groups to join |
| `--health-cmd` | `string` | | Command to run to check health |
| `--health-interval` | `duration` | `0s` | Time between running the check (ms\|s\|m\|h) (default 0s) |
| `--health-retries` | `int` | `0` | Consecutive failures needed to report unhealthy |
| `--health-start-interval` | `duration` | `0s` | Time between running the check during the start period (ms\|s\|m\|h) (default 0s) |
| `--health-start-period` | `duration` | `0s` | Start period for the container to initialize before starting health-retries countdown (ms\|s\|m\|h) (default 0s) |
| `--health-timeout` | `duration` | `0s` | Maximum time to allow one check to run (ms\|s\|m\|h) (default 0s) |
| `--help` | | | Print usage |
| `-h`, `--hostname` | `string` | | Container host name |
| [`--init`](#init) | | | Run an init inside the container that forwards signals and reaps processes |
| [`-i`](#interactive), [`--interactive`](#interactive) | | | Keep STDIN open even if not attached |
| `--io-maxbandwidth` | `bytes` | `0` | Maximum IO bandwidth limit for the system drive (Windows only) |
| `--io-maxiops` | `uint64` | `0` | Maximum IOps limit for the system drive (Windows only) |
| `--ip` | `string` | | IPv4 address (e.g., 172.30.100.104) |
| `--ip6` | `string` | | IPv6 address (e.g., 2001:db8::33) |
| [`--ipc`](#ipc) | `string` | | IPC mode to use |
| [`--isolation`](#isolation) | `string` | | Container isolation technology |
| `--kernel-memory` | `bytes` | `0` | Kernel memory limit |
| [`-l`](#label), [`--label`](#label) | `list` | | Set meta data on a container |
| `--label-file` | `list` | | Read in a line delimited file of labels |
| `--link` | `list` | | Add link to another container |
| `--link-local-ip` | `list` | | Container IPv4/IPv6 link-local addresses |
| [`--log-driver`](#log-driver) | `string` | | Logging driver for the container |
| `--log-opt` | `list` | | Log driver options |
| `--mac-address` | `string` | | Container MAC address (e.g., 92:d0:c6:0a:29:33) |
| [`-m`](#memory), [`--memory`](#memory) | `bytes` | `0` | Memory limit |
| `--memory-reservation` | `bytes` | `0` | Memory soft limit |
| `--memory-swap` | `bytes` | `0` | Swap limit equal to memory plus swap: '-1' to enable unlimited swap |
| `--memory-swappiness` | `int64` | `-1` | Tune container memory swappiness (0 to 100) |
| [`--mount`](#mount) | `mount` | | Attach a filesystem mount to the container |
| [`--name`](#name) | `string` | | Assign a name to the container |
| [`--network`](#network) | `network` | | Connect a container to a network |
| `--network-alias` | `list` | | Add network-scoped alias for the container |
| `--no-healthcheck` | | | Disable any container-specified HEALTHCHECK |
| `--oom-kill-disable` | | | Disable OOM Killer |
| `--oom-score-adj` | `int` | `0` | Tune host's OOM preferences (-1000 to 1000) |
| [`--pid`](#pid) | `string` | | PID namespace to use |
| `--pids-limit` | `int64` | `0` | Tune container pids limit (set -1 for unlimited) |
| `--platform` | `string` | | Set platform if server is multi-platform capable |
| [`--privileged`](#privileged) | | | Give extended privileges to this container |
| [`-p`](#publish), [`--publish`](#publish) | `list` | | Publish a container's port(s) to the host |
| [`-P`](#publish-all), [`--publish-all`](#publish-all) | | | Publish all exposed ports to random ports |
| [`--pull`](#pull) | `string` | `missing` | Pull image before running (`always`, `missing`, `never`) |
| `-q`, `--quiet` | | | Suppress the pull output |
| [`--read-only`](#read-only) | | | Mount the container's root filesystem as read only |
| [`--restart`](#restart) | `string` | `no` | Restart policy to apply when a container exits |
| [`--rm`](#rm) | | | Automatically remove the container when it exits |
| `--runtime` | `string` | | Runtime to use for this container |
| [`--security-opt`](#security-opt) | `list` | | Security Options |
| `--shm-size` | `bytes` | `0` | Size of /dev/shm |
| `--sig-proxy` | | | Proxy received signals to the process |
| [`--stop-signal`](#stop-signal) | `string` | | Signal to stop the container |
| [`--stop-timeout`](#stop-timeout) | `int` | `0` | Timeout (in seconds) to stop a container |
| [`--storage-opt`](#storage-opt) | `list` | | Storage driver options for the container |
| [`--sysctl`](#sysctl) | `map` | `map[]` | Sysctl options |
| [`--tmpfs`](#tmpfs) | `list` | | Mount a tmpfs directory |
| [`-t`](#tty), [`--tty`](#tty) | | | Allocate a pseudo-TTY |
| [`--ulimit`](#ulimit) | `ulimit` | | Ulimit options |
| `-u`, `--user` | `string` | | Username or UID (format: <name\|uid>[:<group\|gid>]) |
| `--userns` | `string` | | User namespace to use |
| [`--uts`](#uts) | `string` | | UTS namespace to use |
| [`-v`](#volume), [`--volume`](#volume) | `list` | | Bind mount a volume |
| `--volume-driver` | `string` | | Optional volume driver for the container |
| [`--volumes-from`](#volumes-from) | `list` | | Mount volumes from the specified container(s) |
| [`-w`](#workdir), [`--workdir`](#workdir) | `string` | | Working directory inside the container |
<!---MARKER_GEN_END-->
## Description
The `docker run` command runs a command in a new container, pulling the image if needed and starting the container.
You can restart a stopped container with all its previous changes intact using `docker start`.
Use `docker ps -a` to view a list of all containers, including those that are stopped.
## Examples
### <a name="name"></a> Assign name (--name)
The `--name` flag lets you specify a custom identifier for a container. The
following example runs a container named `test` using the `nginx:alpine` image
in [detached mode](#detach).
```console
$ docker run --name test -d nginx:alpine
4bed76d3ad428b889c56c1ecc2bf2ed95cb08256db22dc5ef5863e1d03252a19
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4bed76d3ad42 nginx:alpine "/docker-entrypoint.…" 1 second ago Up Less than a second 80/tcp test
```
You can reference the container by name with other commands. For example, the
following commands stop and remove a container named `test`:
```console
$ docker stop test
test
$ docker rm test
test
```
If you don't specify a custom name using the `--name` flag, the daemon assigns
a randomly generated name, such as `vibrant_cannon`, to the container. Using a
custom-defined name provides the benefit of having an easy-to-remember ID for a
container.
Moreover, if you connect the container to a user-defined bridge network, other
containers on the same network can refer to the container by name via DNS.
```console
$ docker network create mynet
cb79f45948d87e389e12013fa4d969689ed2c3316985dd832a43aaec9a0fe394
$ docker run --name test --net mynet -d nginx:alpine
58df6ecfbc2ad7c42d088ed028d367f9e22a5f834d7c74c66c0ab0485626c32a
$ docker run --net mynet busybox:latest ping test
PING test (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.073 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.411 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.319 ms
64 bytes from 172.18.0.2: seq=3 ttl=64 time=0.383 ms
...
```
### <a name="cidfile"></a> Capture container ID (--cidfile)
To help with automation, you can have Docker write the container ID out to a
file of your choosing. This is similar to how some programs might write out
their process ID to a file (you might've seen them as PID files):
```console
$ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
```
This creates a container and prints `test` to the console. The `cidfile`
flag makes Docker attempt to create a new file and write the container ID to it.
If the file exists already, Docker returns an error. Docker closes this
file when `docker run` exits.
### <a name="pid"></a> PID settings (--pid)
```text
--pid="" : Set the PID (Process) Namespace mode for the container,
'container:<name|id>': joins another container's PID namespace
'host': use the host's PID namespace inside the container
```
By default, all containers have the PID namespace enabled.
PID namespace provides separation of processes. The PID Namespace removes the
view of the system processes, and allows process ids to be reused including
PID 1.
In certain cases you want your container to share the host's process namespace,
allowing processes within the container to see all of the processes on the
system. For example, you could build a container with debugging tools like
`strace` or `gdb`, but want to use these tools when debugging processes within
the container.
#### Example: run htop inside a container
To run `htop` in a container that shares the process namespac of the host:
1. Run an alpine container with the `--pid=host` option:
```console
$ docker run --rm -it --pid=host alpine
```
2. Install `htop` in the container:
```console
/ # apk add htop
fetch https://dl-cdn.alpinelinux.org/alpine/v3.18/main/aarch64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.18/community/aarch64/APKINDEX.tar.gz
(1/3) Installing ncurses-terminfo-base (6.4_p20230506-r0)
(2/3) Installing libncursesw (6.4_p20230506-r0)
(3/3) Installing htop (3.2.2-r1)
Executing busybox-1.36.1-r2.trigger
OK: 9 MiB in 18 packages
```
3. Invoke the `htop` command.
```console
/ # htop
```
#### Example, join another container's PID namespace
Joining another container's PID namespace can be useful for debugging that
container.
1. Start a container running a Redis server:
```console
$ docker run --rm --name my-nginx -d nginx:alpine
```
2. Run an Alpine container that attaches the `--pid` namespace to the
`my-nginx` container:
```console
$ docker run --rm -it --pid=container:my-nginx \
--cap-add SYS_PTRACE \
--security-opt seccomp=unconfined \
alpine
```
3. Install `strace` in the Alpine container:
```console
/ # apk add strace
```
4. Attach to process 1, the process ID of the `my-nginx` container:
```console
/ # strace -p 1
strace: Process 1 attached
```
### <a name="uts"></a> UTS settings (--uts)
```text
--uts="" : Set the UTS namespace mode for the container
'host': use the host's UTS namespace inside the container
```
The UTS namespace is for setting the hostname and the domain that's visible to
running processes in that namespace. By default, all containers, including
those with `--network=host`, have their own UTS namespace. Setting `--uts` to
`host` results in the container using the same UTS namespace as the host.
> **Note**
>
> Docker disallows combining the `--hostname` and `--domainname` flags with
> `--uts=host`. This is to prevent containers running in the host's UTS
> namespace from attempting to change the hosts' configuration.
You may wish to share the UTS namespace with the host if you would like the
hostname of the container to change as the hostname of the host changes. A more
advanced use case would be changing the host's hostname from a container.
### <a name="ipc"></a> IPC settings (--ipc)
```text
--ipc="MODE" : Set the IPC mode for the container
```
The `--ipc` flag accepts the following values:
| Value | Description |
|:---------------------------|:----------------------------------------------------------------------------------|
| "" | Use daemon's default. |
| "none" | Own private IPC namespace, with /dev/shm not mounted. |
| "private" | Own private IPC namespace. |
| "shareable" | Own private IPC namespace, with a possibility to share it with other containers. |
| "container:<_name-or-ID_>" | Join another ("shareable") container's IPC namespace. |
| "host" | Use the host system's IPC namespace. |
If not specified, daemon default is used, which can either be `"private"`
or `"shareable"`, depending on the daemon version and configuration.
[System V interprocess communication (IPC)](https://linux.die.net/man/5/ipc)
namespaces provide separation of named shared memory segments, semaphores and
message queues.
Shared memory segments are used to accelerate inter-process communication at
memory speed, rather than through pipes or through the network stack. Shared
memory is commonly used by databases and custom-built (typically C/OpenMPI,
C++/using boost libraries) high performance applications for scientific
computing and financial services industries. If these types of applications
are broken into multiple containers, you might need to share the IPC mechanisms
of the containers, using `"shareable"` mode for the main (i.e. "donor")
container, and `"container:<donor-name-or-ID>"` for other containers.
### <a name="privileged"></a> Full container capabilities (--privileged)
The following example doesn't work, because by default, Docker drops most
potentially dangerous kernel capabilities, including `CAP_SYS_ADMIN ` (which is
required to mount filesystems).
```console
$ docker run -t -i --rm ubuntu bash
root@bc338942ef20:/# mount -t tmpfs none /mnt
mount: permission denied
```
It works when you add the `--privileged` flag:
```console
$ docker run -t -i --privileged ubuntu bash
root@50e3f57e16e6:/# mount -t tmpfs none /mnt
root@50e3f57e16e6:/# df -h
Filesystem Size Used Avail Use% Mounted on
none 1.9G 0 1.9G 0% /mnt
```
The `--privileged` flag gives all capabilities to the container, and it also
lifts all the limitations enforced by the `device` cgroup controller. In other
words, the container can then do almost everything that the host can do. This
flag exists to allow special use-cases, like running Docker within Docker.
### <a name="workdir"></a> Set working directory (-w, --workdir)
```console
$ docker run -w /path/to/dir/ -i -t ubuntu pwd
```
The `-w` option runs the command executed inside the directory specified, in this example,
`/path/to/dir/`. If the path doesn't exist, Docker creates it inside the container.
### <a name="storage-opt"></a> Set storage driver options per container (--storage-opt)
```console
$ docker run -it --storage-opt size=120G fedora /bin/bash
```
This (size) constraints the container filesystem size to 120G at creation time.
This option is only available for the `btrfs`, `overlay2`, `windowsfilter`,
and `zfs` storage drivers.
For the `overlay2` storage driver, the size option is only available if the
backing filesystem is `xfs` and mounted with the `pquota` mount option.
Under these conditions, you can pass any size less than the backing filesystem size.
For the `windowsfilter`, `btrfs`, and `zfs` storage drivers, you cannot pass a
size less than the Default BaseFS Size.
### <a name="tmpfs"></a> Mount tmpfs (--tmpfs)
The `--tmpfs` flag lets you create a `tmpfs` mount.
The options that you can pass to `--tmpfs` are identical to the Linux `mount -t
tmpfs -o` command. The following example mounts an empty `tmpfs` into the
container with the `rw`, `noexec`, `nosuid`, `size=65536k` options.
```console
$ docker run -d --tmpfs /run:rw,noexec,nosuid,size=65536k my_image
```
For more information, see [tmpfs mounts](https://docs.docker.com/storage/tmpfs/#tmpfs-mounts).
### <a name="volume"></a> Mount volume (-v)
```console
$ docker run -v $(pwd):$(pwd) -w $(pwd) -i -t ubuntu pwd
```
The example above mounts the current directory into the container at the same path
using the `-v` flag, sets it as the working directory, and then runs the `pwd` command inside the container.
As of Docker Engine version 23, you can use relative paths on the host.
```console
$ docker run -v ./content:/content -w /content -i -t ubuntu pwd
```
The example above mounts the `content` directory in the current directory into the container at the
`/content` path using the `-v` flag, sets it as the working directory, and then
runs the `pwd` command inside the container.
```console
$ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash
```
When the host directory of a bind-mounted volume doesn't exist, Docker
automatically creates this directory on the host for you. In the
example above, Docker creates the `/doesnt/exist`
folder before starting your container.
### <a name="read-only"></a> Mount volume read-only (--read-only)
```console
$ docker run --read-only -v /icanwrite busybox touch /icanwrite/here
```
You can use volumes in combination with the `--read-only` flag to control where
a container writes files. The `--read-only` flag mounts the container's root
filesystem as read only prohibiting writes to locations other than the
specified volumes for the container.
```console
$ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v /path/to/static-docker-binary:/usr/bin/docker busybox sh
```
By bind-mounting the Docker Unix socket and statically linked Docker
binary (refer to [get the Linux binary](https://docs.docker.com/engine/install/binaries/#install-static-binaries)),
you give the container the full access to create and manipulate the host's
Docker daemon.
On Windows, you must specify the paths using Windows-style path semantics.
```powershell
PS C:\> docker run -v c:\foo:c:\dest microsoft/nanoserver cmd /s /c type c:\dest\somefile.txt
Contents of file
PS C:\> docker run -v c:\foo:d: microsoft/nanoserver cmd /s /c type d:\somefile.txt
Contents of file
```
The following examples fails when using Windows-based containers, as the
destination of a volume or bind mount inside the container must be one of:
a non-existing or empty directory; or a drive other than `C:`. Further, the source
of a bind mount must be a local directory, not a file.
```powershell
net use z: \\remotemachine\share
docker run -v z:\foo:c:\dest ...
docker run -v \\uncpath\to\directory:c:\dest ...
docker run -v c:\foo\somefile.txt:c:\dest ...
docker run -v c:\foo:c: ...
docker run -v c:\foo:c:\existing-directory-with-contents ...
```
For in-depth information about volumes, refer to [manage data in containers](https://docs.docker.com/storage/volumes/)
### <a name="mount"></a> Add bind mounts or volumes using the --mount flag
The `--mount` flag allows you to mount volumes, host-directories, and `tmpfs`
mounts in a container.
The `--mount` flag supports most options supported by the `-v` or the
`--volume` flag, but uses a different syntax. For in-depth information on the
`--mount` flag, and a comparison between `--volume` and `--mount`, refer to
[Bind mounts](https://docs.docker.com/storage/bind-mounts/).
Even though there is no plan to deprecate `--volume`, usage of `--mount` is recommended.
Examples:
```console
$ docker run --read-only --mount type=volume,target=/icanwrite busybox touch /icanwrite/here
```
```console
$ docker run -t -i --mount type=bind,src=/data,dst=/data busybox sh
```
### <a name="publish"></a> Publish or expose port (-p, --expose)
```console
$ docker run -p 127.0.0.1:80:8080/tcp nginx:alpine
```
This binds port `8080` of the container to TCP port `80` on `127.0.0.1` of the
host. You can also specify `udp` and `sctp` ports. The [Networking overview
page](https://docs.docker.com/network/) explains in detail how to publish ports
with Docker.
> **Note**
>
> If you don't specify an IP address (i.e., `-p 80:80` instead of `-p
> 127.0.0.1:80:80`) when publishing a container's ports, Docker publishes the
> port on all interfaces (address `0.0.0.0`) by default. These ports are
> externally accessible. This also applies if you configured UFW to block this
> specific port, as Docker manages its own iptables rules. [Read
> more](https://docs.docker.com/network/packet-filtering-firewalls/)
```console
$ docker run --expose 80 nginx:alpine
```
This exposes port `80` of the container without publishing the port to the host
system's interfaces.
### <a name="publish-all"></a> Publish all exposed ports (-P, --publish-all)
```console
$ docker run -P nginx:alpine
```
The `-P`, or `--publish-all`, flag publishes all the exposed ports to the host.
Docker binds each exposed port to a random port on the host.
The `-P` flag only publishes port numbers that are explicitly flagged as
exposed, either using the Dockerfile `EXPOSE` instruction or the `--expose`
flag for the `docker run` command.
The range of ports are within an *ephemeral port range* defined by
`/proc/sys/net/ipv4/ip_local_port_range`. Use the `-p` flag to explicitly map a
single port or range of ports.
### <a name="pull"></a> Set the pull policy (--pull)
Use the `--pull` flag to set the image pull policy when creating (and running)
the container.
The `--pull` flag can take one of these values:
| Value | Description |
|:--------------------|:------------------------------------------------------------------------------------------------------------------|
| `missing` (default) | Pull the image if it was not found in the image cache, or use the cached image otherwise. |
| `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. |
| `always` | Always perform a pull before creating the container. |
When creating (and running) a container from an image, the daemon checks if the
image exists in the local image cache. If the image is missing, an error is
returned to the CLI, allowing it to initiate a pull.
The default (`missing`) is to only pull the image if it's not present in the
daemon's image cache. This default allows you to run images that only exist
locally (for example, images you built from a Dockerfile, but that have not
been pushed to a registry), and reduces networking.
The `always` option always initiates a pull before creating the container. This
option makes sure the image is up-to-date, and prevents you from using outdated
images, but may not be suitable in situations where you want to test a locally
built image before pushing (as pulling the image overwrites the existing image
in the image cache).
The `never` option disables (implicit) pulling images when creating containers,
and only uses images that are available in the image cache. If the specified
image is not found, an error is produced, and the container is not created.
This option is useful in situations where networking is not available, or to
prevent images from being pulled implicitly when creating containers.
The following example shows `docker run` with the `--pull=never` option set,
which produces en error as the image is missing in the image-cache:
```console
$ docker run --pull=never hello-world
docker: Error response from daemon: No such image: hello-world:latest.
```
### <a name="env"></a> Set environment variables (-e, --env, --env-file)
```console
$ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash
```
Use the `-e`, `--env`, and `--env-file` flags to set simple (non-array)
environment variables in the container you're running, or overwrite variables
defined in the Dockerfile of the image you're running.
You can define the variable and its value when running the container:
```console
$ docker run --env VAR1=value1 --env VAR2=value2 ubuntu env | grep VAR
VAR1=value1
VAR2=value2
```
You can also use variables exported to your local environment:
```console
export VAR1=value1
export VAR2=value2
$ docker run --env VAR1 --env VAR2 ubuntu env | grep VAR
VAR1=value1
VAR2=value2
```
When running the command, the Docker CLI client checks the value the variable
has in your local environment and passes it to the container.
If no `=` is provided and that variable isn't exported in your local
environment, the variable is unset in the container.
You can also load the environment variables from a file. This file should use
the syntax `<variable>=value` (which sets the variable to the given value) or
`<variable>` (which takes the value from the local environment), and `#` for
comments. Lines beginning with `#` are treated as line comments and are
ignored, whereas a `#` appearing anywhere else in a line is treated as part of
the variable value.
```console
$ cat env.list
# This is a comment
VAR1=value1
VAR2=value2
USER
$ docker run --env-file env.list ubuntu env | grep -E 'VAR|USER'
VAR1=value1
VAR2=value2
USER=jonzeolla
```
### <a name="label"></a> Set metadata on container (-l, --label, --label-file)
A label is a `key=value` pair that applies metadata to a container. To label a container with two labels:
```console
$ docker run -l my-label --label com.example.foo=bar ubuntu bash
```
The `my-label` key doesn't specify a value so the label defaults to an empty
string (`""`). To add multiple labels, repeat the label flag (`-l` or `--label`).
The `key=value` must be unique to avoid overwriting the label value. If you
specify labels with identical keys but different values, each subsequent value
overwrites the previous. Docker uses the last `key=value` you supply.
Use the `--label-file` flag to load multiple labels from a file. Delimit each
label in the file with an EOL mark. The example below loads labels from a
labels file in the current directory:
```console
$ docker run --label-file ./labels ubuntu bash
```
The label-file format is similar to the format for loading environment
variables. (Unlike environment variables, labels are not visible to processes
running inside a container.) The following example shows a label-file
format:
```console
com.example.label1="a label"
# this is a comment
com.example.label2=another\ label
com.example.label3
```
You can load multiple label-files by supplying multiple `--label-file` flags.
For additional information on working with labels, see
[Labels](https://docs.docker.com/config/labels-custom-metadata/).
### <a name="network"></a> Connect a container to a network (--network)
To start a container and connect it to a network, use the `--network` option.
The following commands create a network named `my-net` and adds a `busybox` container
to the `my-net` network.
```console
$ docker network create my-net
$ docker run -itd --network=my-net busybox
```
You can also choose the IP addresses for the container with `--ip` and `--ip6`
flags when you start the container on a user-defined network. To assign a
static IP to containers, you must specify subnet block for the network.
```console
$ docker network create --subnet 192.0.2.0/24 my-net
$ docker run -itd --network=my-net --ip=192.0.2.69 busybox
```
If you want to add a running container to a network use the `docker network connect` subcommand.
You can connect multiple containers to the same network. Once connected, the
containers can communicate using only another container's IP address
or name. For `overlay` networks or custom plugins that support multi-host
connectivity, containers connected to the same multi-host network but launched
from different Engines can also communicate in this way.
> **Note**
>
> The default bridge network only allow containers to communicate with each other using
> internal IP addresses. User-created bridge networks provide DNS resolution between
> containers using container names.
You can disconnect a container from a network using the `docker network
disconnect` command.
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/).
### <a name="volumes-from"></a> Mount volumes from container (--volumes-from)
```console
$ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd
```
The `--volumes-from` flag mounts all the defined volumes from the referenced
containers. You can specify more than one container by repetitions of the `--volumes-from`
argument. The container ID may be optionally suffixed with `:ro` or `:rw` to
mount the volumes in read-only or read-write mode, respectively. By default,
Docker mounts the volumes in the same mode (read write or read only) as
the reference container.
Labeling systems like SELinux require placing proper labels on volume
content mounted into a container. Without a label, the security system might
prevent the processes running inside the container from using the content. By
default, Docker does not change the labels set by the OS.
To change the label in the container context, you can add either of two suffixes
`:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file
objects on the shared volumes. The `z` option tells Docker that two containers
share the volume content. As a result, Docker labels the content with a shared
content label. Shared volume labels allow all containers to read/write content.
The `Z` option tells Docker to label the content with a private unshared label.
Only the current container can use a private volume.
### <a name="detach"></a> Detached mode (-d, --detach)
The `--detach` (or `-d`) flag starts a container as a background process that
doesn't occupy your terminal window. By design, containers started in detached
mode exit when the root process used to run the container exits, unless you
also specify the `--rm` option. If you use `-d` with `--rm`, the container is
removed when it exits or when the daemon exits, whichever happens first.
Don't pass a `service x start` command to a detached container. For example,
this command attempts to start the `nginx` service.
```console
$ docker run -d -p 80:80 my_image service nginx start
```
This succeeds in starting the `nginx` service inside the container. However, it
fails the detached container paradigm in that, the root process (`service nginx
start`) returns and the detached container stops as designed. As a result, the
`nginx` service starts but can't be used. Instead, to start a process such as
the `nginx` web server do the following:
```console
$ docker run -d -p 80:80 my_image nginx -g 'daemon off;'
```
To do input/output with a detached container use network connections or shared
volumes. These are required because the container is no longer listening to the
command line where `docker run` was run.
### <a name="detach-keys"></a> Override the detach sequence (--detach-keys)
Use the `--detach-keys` option to override the Docker key sequence for detach.
This is useful if the Docker default sequence conflicts with key sequence you
use for other applications. There are two ways to define your own detach key
sequence, as a per-container override or as a configuration property on your
entire configuration.
To override the sequence for an individual container, use the
`--detach-keys="<sequence>"` flag with the `docker attach` command. The format of
the `<sequence>` is either a letter [a-Z], or the `ctrl-` combined with any of
the following:
* `a-z` (a single lowercase alpha character )
* `@` (at sign)
* `[` (left bracket)
* `\\` (two backward slashes)
* `_` (underscore)
* `^` (caret)
These `a`, `ctrl-a`, `X`, or `ctrl-\\` values are all examples of valid key
sequences. To configure a different configuration default key sequence for all
containers, see [**Configuration file** section](cli.md#configuration-files).
### <a name="device"></a> Add host device to container (--device)
```console
$ docker run -it --rm \
--device=/dev/sdc:/dev/xvdc \
--device=/dev/sdd \
--device=/dev/zero:/dev/foobar \
ubuntu ls -l /dev/{xvdc,sdd,foobar}
brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc
brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd
crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/foobar
```
It's often necessary to directly expose devices to a container. The `--device`
option enables that. For example, adding a specific block storage device or loop
device or audio device to an otherwise unprivileged container
(without the `--privileged` flag) and have the application directly access it.
By default, the container is able to `read`, `write` and `mknod` these devices.
This can be overridden using a third `:rwm` set of options to each `--device`
flag. If the container is running in privileged mode, then Docker ignores the
specified permissions.
```console
$ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc
Command (m for help): q
$ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc
You will not be able to write the partition table.
Command (m for help): q
$ docker run --device=/dev/sda:/dev/xvdc:rw --rm -it ubuntu fdisk /dev/xvdc
Command (m for help): q
$ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc
fdisk: unable to open /dev/xvdc: Operation not permitted
```
> **Note**
>
> The `--device` option cannot be safely used with ephemeral devices. You shouldn't
> add block devices that may be removed to untrusted containers with `--device`.
For Windows, the format of the string passed to the `--device` option is in
the form of `--device=<IdType>/<Id>`. Beginning with Windows Server 2019
and Windows 10 October 2018 Update, Windows only supports an IdType of
`class` and the Id as a [device interface class
GUID](https://docs.microsoft.com/en-us/windows-hardware/drivers/install/overview-of-device-interface-classes).
Refer to the table defined in the [Windows container
docs](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/hardware-devices-in-containers)
for a list of container-supported device interface class GUIDs.
If you specify this option for a process-isolated Windows container, Docker makes
_all_ devices that implement the requested device interface class GUID
available in the container. For example, the command below makes all COM
ports on the host visible in the container.
```powershell
PS C:\> docker run --device=class/86E0D1E0-8089-11D0-9CE4-08003E301F73 mcr.microsoft.com/windows/servercore:ltsc2019
```
> **Note**
>
> The `--device` option is only supported on process-isolated Windows containers,
> and produces an error if the container isolation is `hyperv`.
### <a name="attach"></a> Attach to STDIN/STDOUT/STDERR (-a, --attach)
The `--attach` (or `-a`) flag tells `docker run` to bind to the container's
`STDIN`, `STDOUT` or `STDERR`. This makes it possible to manipulate the output
and input as needed. You can specify to which of the three standard streams
(`STDIN`, `STDOUT`, `STDERR`) you'd like to connect instead, as in:
```console
$ docker run -a stdin -a stdout -i -t ubuntu /bin/bash
```
The following example pipes data into a container and prints the container's ID
by attaching only to the container's `STDIN`.
```console
$ echo "test" | docker run -i -a stdin ubuntu cat -
```
The following example doesn't print anything to the console unless there's an
error because output is only attached to the `STDERR` of the container. The
container's logs still store what's written to `STDERR` and `STDOUT`.
```console
$ docker run -a stderr ubuntu echo test
```
The following example shows a way of using `--attach` to pipe a file into a
container. The command prints the container's ID after the build completes and
you can retrieve the build logs using `docker logs`. This is useful if you need
to pipe a file or something else into a container and retrieve the container's
ID once the container has finished running.
```console
$ cat somefile | docker run -i -a stdin mybuilder dobuild
```
> **Note**
>
> A process running as PID 1 inside a container is treated specially by
> Linux: it ignores any signal with the default action. So, the process
> doesn't terminate on `SIGINT` or `SIGTERM` unless it's coded to do so.
See also [the `docker cp` command](cp.md).
### <a name="interactive"></a> Keep STDIN open (-i, --interactive)
The `--interactive` (or `-i`) flag keeps the container's `STDIN` open, and lets
you send input to the container through standard input.
```console
$ echo hello | docker run --rm -i busybox cat
hello
```
The `-i` flag is most often used together with the `--tty` flag to bind the I/O
streams of the container to a pseudo terminal, creating an interactive terminal
session for the container. See [Allocate a pseudo-TTY](#tty) for more examples.
```console
$ docker run -it debian
root@10a3e71492b0:/# factor 90
90: 2 3 3 5
root@10a3e71492b0:/# exit
exit
```
Using the `-i` flag on its own allows for composition, such as piping input to
containers:
```console
$ docker run --rm -i busybox echo "foo bar baz" \
| docker run --rm -i busybox awk '{ print $2 }' \
| docker run --rm -i busybox rev
rab
```
### <a name="init"></a> Specify an init process
You can use the `--init` flag to indicate that an init process should be used as
the PID 1 in the container. Specifying an init process ensures the usual
responsibilities of an init system, such as reaping zombie processes, are
performed inside the created container.
The default init process used is the first `docker-init` executable found in the
system path of the Docker daemon process. This `docker-init` binary, included in
the default installation, is backed by [tini](https://github.com/krallin/tini).
### <a name="tty"></a> Allocate a pseudo-TTY (-t, --tty)
The `--tty` (or `-t`) flag attaches a pseudo-TTY to the container, connecting
your terminal to the I/O streams of the container. Allocating a pseudo-TTY to
the container means that you get access to input and output feature that TTY
devices provide.
For example, the following command runs the `passwd` command in a `debian`
container, to set a new password for the `root` user.
```console
$ docker run -i debian passwd root
New password: karjalanpiirakka9
Retype new password: karjalanpiirakka9
passwd: password updated successfully
```
If you run this command with only the `-i` flag (which lets you send text to
`STDIN` of the container), the `passwd` prompt displays the password in plain
text. However, if you try the same thing but also adding the `-t` flag, the
password is hidden:
```console
$ docker run -i debian passwd root
New password:
Retype new password:
passwd: password updated successfully
```
This is because `passwd` can suppress the output of characters to the terminal
using the echo-off TTY feature.
You can use the `-t` flag without `-i` flag. This still allocates a pseudo-TTY
to the container, but with no way of writing to `STDIN`. The only time this
might be useful is if the output of the container requires a TTY environment.
### <a name="cgroup-parent"></a> Specify custom cgroups
Using the `--cgroup-parent` flag, you can pass a specific cgroup to run a
container in. This allows you to create and manage cgroups on their own. You can
define custom resources for those cgroups and put containers under a common
parent group.
### <a name="device-cgroup-rule"></a> Using dynamically created devices (--device-cgroup-rule)
Docker assigns devices available to a container at creation time. The
assigned devices are added to the cgroup.allow file and
created into the container when it runs. This poses a problem when
you need to add a new device to running container.
One solution is to add a more permissive rule to a container
allowing it access to a wider range of devices. For example, supposing
the container needs access to a character device with major `42` and