github.com/a4a881d4/docker@v1.9.0-rc2/docs/reference/run.md (about) 1 <!--[metadata]> 2 +++ 3 title = "Docker run reference" 4 description = "Configure containers at runtime" 5 keywords = ["docker, run, configure, runtime"] 6 [menu.main] 7 parent = "mn_reference" 8 +++ 9 <![end-metadata]--> 10 11 <!-- TODO (@thaJeztah) define more flexible table/td classes --> 12 <style> 13 .content-body table .no-wrap { 14 white-space: nowrap; 15 } 16 </style> 17 # Docker run reference 18 19 Docker runs processes in isolated containers. A container is a process 20 which runs on a host. The host may be local or remote. When an operator 21 executes `docker run`, the container process that runs is isolated in 22 that it has its own file system, its own networking, and its own 23 isolated process tree separate from the host. 24 25 This page details how to use the `docker run` command to define the 26 container's resources at runtime. 27 28 ## General form 29 30 The basic `docker run` command takes this form: 31 32 $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...] 33 34 The `docker run` command must specify an [*IMAGE*](glossary.md#image) 35 to derive the container from. An image developer can define image 36 defaults related to: 37 38 * detached or foreground running 39 * container identification 40 * network settings 41 * runtime constraints on CPU and memory 42 * privileges and LXC configuration 43 44 With the `docker run [OPTIONS]` an operator can add to or override the 45 image defaults set by a developer. And, additionally, operators can 46 override nearly all the defaults set by the Docker runtime itself. The 47 operator's ability to override image and Docker runtime defaults is why 48 [*run*](commandline/run.md) has more options than any 49 other `docker` command. 50 51 To learn how to interpret the types of `[OPTIONS]`, see [*Option 52 types*](commandline/cli.md#option-types). 53 54 > **Note**: Depending on your Docker system configuration, you may be 55 > required to preface the `docker run` command with `sudo`. To avoid 56 > having to use `sudo` with the `docker` command, your system 57 > administrator can create a Unix group called `docker` and add users to 58 > it. For more information about this configuration, refer to the Docker 59 > installation documentation for your operating system. 60 61 62 ## Operator exclusive options 63 64 Only the operator (the person executing `docker run`) can set the 65 following options. 66 67 - [Detached vs foreground](#detached-vs-foreground) 68 - [Detached (-d)](#detached-d) 69 - [Foreground](#foreground) 70 - [Container identification](#container-identification) 71 - [Name (--name)](#name-name) 72 - [PID equivalent](#pid-equivalent) 73 - [IPC settings (--ipc)](#ipc-settings-ipc) 74 - [Network settings](#network-settings) 75 - [Restart policies (--restart)](#restart-policies-restart) 76 - [Clean up (--rm)](#clean-up-rm) 77 - [Runtime constraints on resources](#runtime-constraints-on-resources) 78 - [Runtime privilege, Linux capabilities, and LXC configuration](#runtime-privilege-linux-capabilities-and-lxc-configuration) 79 80 ## Detached vs foreground 81 82 When starting a Docker container, you must first decide if you want to 83 run the container in the background in a "detached" mode or in the 84 default foreground mode: 85 86 -d=false: Detached mode: Run container in the background, print new container id 87 88 ### Detached (-d) 89 90 To start a container in detached mode, you use `-d=true` or just `-d` option. By 91 design, containers started in detached mode exit when the root process used to 92 run the container exits. A container in detached mode cannot be automatically 93 removed when it stops, this means you cannot use the `--rm` option with `-d` option. 94 95 Do not pass a `service x start` command to a detached container. For example, this 96 command attempts to start the `nginx` service. 97 98 $ docker run -d -p 80:80 my_image service nginx start 99 100 This succeeds in starting the `nginx` service inside the container. However, it 101 fails the detached container paradigm in that, the root process (`service nginx 102 start`) returns and the detached container stops as designed. As a result, the 103 `nginx` service is started but could not be used. Instead, to start a process 104 such as the `nginx` web server do the following: 105 106 $ docker run -d -p 80:80 my_image nginx -g 'daemon off;' 107 108 To do input/output with a detached container use network connections or shared 109 volumes. These are required because the container is no longer listening to the 110 command line where `docker run` was run. 111 112 To reattach to a detached container, use `docker` 113 [*attach*](commandline/attach.md) command. 114 115 ### Foreground 116 117 In foreground mode (the default when `-d` is not specified), `docker 118 run` can start the process in the container and attach the console to 119 the process's standard input, output, and standard error. It can even 120 pretend to be a TTY (this is what most command line executables expect) 121 and pass along signals. All of that is configurable: 122 123 -a=[] : Attach to `STDIN`, `STDOUT` and/or `STDERR` 124 -t=false : Allocate a pseudo-tty 125 --sig-proxy=true: Proxify all received signal to the process (non-TTY mode only) 126 -i=false : Keep STDIN open even if not attached 127 128 If you do not specify `-a` then Docker will [attach all standard 129 streams]( https://github.com/docker/docker/blob/75a7f4d90cde0295bcfb7213004abce8d4779b75/commands.go#L1797). 130 You can specify to which of the three standard streams (`STDIN`, `STDOUT`, 131 `STDERR`) you'd like to connect instead, as in: 132 133 $ docker run -a stdin -a stdout -i -t ubuntu /bin/bash 134 135 For interactive processes (like a shell), you must use `-i -t` together in 136 order to allocate a tty for the container process. `-i -t` is often written `-it` 137 as you'll see in later examples. Specifying `-t` is forbidden when the client 138 standard output is redirected or piped, such as in: 139 `echo test | docker run -i busybox cat`. 140 141 >**Note**: A process running as PID 1 inside a container is treated 142 >specially by Linux: it ignores any signal with the default action. 143 >So, the process will not terminate on `SIGINT` or `SIGTERM` unless it is 144 >coded to do so. 145 146 ## Container identification 147 148 ### Name (--name) 149 150 The operator can identify a container in three ways: 151 152 - UUID long identifier 153 ("f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778") 154 - UUID short identifier ("f78375b1c487") 155 - Name ("evil_ptolemy") 156 157 The UUID identifiers come from the Docker daemon, and if you do not 158 assign a name to the container with `--name` then the daemon will also 159 generate a random string name too. The name can become a handy way to 160 add meaning to a container since you can use this name when defining 161 [*links*](../userguide/dockerlinks.md) (or any 162 other place you need to identify a container). This works for both 163 background and foreground Docker containers. 164 165 ### PID equivalent 166 167 Finally, to help with automation, you can have Docker write the 168 container ID out to a file of your choosing. This is similar to how some 169 programs might write out their process ID to a file (you've seen them as 170 PID files): 171 172 --cidfile="": Write the container ID to the file 173 174 ### Image[:tag] 175 176 While not strictly a means of identifying a container, you can specify a version of an 177 image you'd like to run the container with by adding `image[:tag]` to the command. For 178 example, `docker run ubuntu:14.04`. 179 180 ### Image[@digest] 181 182 Images using the v2 or later image format have a content-addressable identifier 183 called a digest. As long as the input used to generate the image is unchanged, 184 the digest value is predictable and referenceable. 185 186 ## PID settings (--pid) 187 188 --pid="" : Set the PID (Process) Namespace mode for the container, 189 'host': use the host's PID namespace inside the container 190 191 By default, all containers have the PID namespace enabled. 192 193 PID namespace provides separation of processes. The PID Namespace removes the 194 view of the system processes, and allows process ids to be reused including 195 pid 1. 196 197 In certain cases you want your container to share the host's process namespace, 198 basically allowing processes within the container to see all of the processes 199 on the system. For example, you could build a container with debugging tools 200 like `strace` or `gdb`, but want to use these tools when debugging processes 201 within the container. 202 203 $ docker run --pid=host rhel7 strace -p 1234 204 205 This command would allow you to use `strace` inside the container on pid 1234 on 206 the host. 207 208 ## UTS settings (--uts) 209 210 --uts="" : Set the UTS namespace mode for the container, 211 'host': use the host's UTS namespace inside the container 212 213 The UTS namespace is for setting the hostname and the domain that is visible 214 to running processes in that namespace. By default, all containers, including 215 those with `--net=host`, have their own UTS namespace. The `host` setting will 216 result in the container using the same UTS namespace as the host. 217 218 You may wish to share the UTS namespace with the host if you would like the 219 hostname of the container to change as the hostname of the host changes. A 220 more advanced use case would be changing the host's hostname from a container. 221 222 > **Note**: `--uts="host"` gives the container full access to change the 223 > hostname of the host and is therefore considered insecure. 224 225 ## IPC settings (--ipc) 226 227 --ipc="" : Set the IPC mode for the container, 228 'container:<name|id>': reuses another container's IPC namespace 229 'host': use the host's IPC namespace inside the container 230 231 By default, all containers have the IPC namespace enabled. 232 233 IPC (POSIX/SysV IPC) namespace provides separation of named shared memory 234 segments, semaphores and message queues. 235 236 Shared memory segments are used to accelerate inter-process communication at 237 memory speed, rather than through pipes or through the network stack. Shared 238 memory is commonly used by databases and custom-built (typically C/OpenMPI, 239 C++/using boost libraries) high performance applications for scientific 240 computing and financial services industries. If these types of applications 241 are broken into multiple containers, you might need to share the IPC mechanisms 242 of the containers. 243 244 ## Network settings 245 246 --dns=[] : Set custom dns servers for the container 247 --net="bridge" : Connects a container to a network 248 'bridge': creates a new network stack for the container on the docker bridge 249 'none': no networking for this container 250 'container:<name|id>': reuses another container network stack 251 'host': use the host network stack inside the container 252 'NETWORK': connects the container to user-created network using `docker network create` command 253 --add-host="" : Add a line to /etc/hosts (host:IP) 254 --mac-address="" : Sets the container's Ethernet device's MAC address 255 256 By default, all containers have networking enabled and they can make any 257 outgoing connections. The operator can completely disable networking 258 with `docker run --net none` which disables all incoming and outgoing 259 networking. In cases like this, you would perform I/O through files or 260 `STDIN` and `STDOUT` only. 261 262 Publishing ports and linking to other containers will not work 263 when `--net` is anything other than the default (bridge). 264 265 Your container will use the same DNS servers as the host by default, but 266 you can override this with `--dns`. 267 268 By default, the MAC address is generated using the IP address allocated to the 269 container. You can set the container's MAC address explicitly by providing a 270 MAC address via the `--mac-address` parameter (format:`12:34:56:78:9a:bc`). 271 272 Supported networks : 273 274 <table> 275 <thead> 276 <tr> 277 <th class="no-wrap">Network</th> 278 <th>Description</th> 279 </tr> 280 </thead> 281 <tbody> 282 <tr> 283 <td class="no-wrap"><strong>none</strong></td> 284 <td> 285 No networking in the container. 286 </td> 287 </tr> 288 <tr> 289 <td class="no-wrap"><strong>bridge</strong> (default)</td> 290 <td> 291 Connect the container to the bridge via veth interfaces. 292 </td> 293 </tr> 294 <tr> 295 <td class="no-wrap"><strong>host</strong></td> 296 <td> 297 Use the host's network stack inside the container. 298 </td> 299 </tr> 300 <tr> 301 <td class="no-wrap"><strong>container</strong>:<name|id></td> 302 <td> 303 Use the network stack of another container, specified via 304 its *name* or *id*. 305 </td> 306 </tr> 307 <tr> 308 <td class="no-wrap"><strong>NETWORK</strong></td> 309 <td> 310 Connects the container to a user created network (using `docker network create` command) 311 </td> 312 </tr> 313 </tbody> 314 </table> 315 316 #### Network: none 317 318 With the network is `none` a container will not have 319 access to any external routes. The container will still have a 320 `loopback` interface enabled in the container but it does not have any 321 routes to external traffic. 322 323 #### Network: bridge 324 325 With the network set to `bridge` a container will use docker's 326 default networking setup. A bridge is setup on the host, commonly named 327 `docker0`, and a pair of `veth` interfaces will be created for the 328 container. One side of the `veth` pair will remain on the host attached 329 to the bridge while the other side of the pair will be placed inside the 330 container's namespaces in addition to the `loopback` interface. An IP 331 address will be allocated for containers on the bridge's network and 332 traffic will be routed though this bridge to the container. 333 334 #### Network: host 335 336 With the network set to `host` a container will share the host's 337 network stack and all interfaces from the host will be available to the 338 container. The container's hostname will match the hostname on the host 339 system. Note that `--add-host` `--hostname` `--dns` `--dns-search` 340 `--dns-opt` and `--mac-address` are invalid in `host` netmode. 341 342 Compared to the default `bridge` mode, the `host` mode gives *significantly* 343 better networking performance since it uses the host's native networking stack 344 whereas the bridge has to go through one level of virtualization through the 345 docker daemon. It is recommended to run containers in this mode when their 346 networking performance is critical, for example, a production Load Balancer 347 or a High Performance Web Server. 348 349 > **Note**: `--net="host"` gives the container full access to local system 350 > services such as D-bus and is therefore considered insecure. 351 352 #### Network: container 353 354 With the network set to `container` a container will share the 355 network stack of another container. The other container's name must be 356 provided in the format of `--net container:<name|id>`. Note that `--add-host` 357 `--hostname` `--dns` `--dns-search` `--dns-opt` and `--mac-address` are 358 invalid in `container` netmode, and `--publish` `--publish-all` `--expose` are 359 also invalid in `container` netmode. 360 361 Example running a Redis container with Redis binding to `localhost` then 362 running the `redis-cli` command and connecting to the Redis server over the 363 `localhost` interface. 364 365 $ docker run -d --name redis example/redis --bind 127.0.0.1 366 $ # use the redis container's network stack to access localhost 367 $ docker run --rm -it --net container:redis example/redis-cli -h 127.0.0.1 368 369 #### Network: User-Created NETWORK 370 371 In addition to all the above special networks, user can create a network using 372 their favorite network driver or external plugin. The driver used to create the 373 network takes care of all the network plumbing requirements for the container 374 connected to that network. 375 376 Example creating a network using the inbuilt overlay network driver and running 377 a container in the created network 378 379 ``` 380 $ docker network create -d overlay multi-host-network 381 $ docker run --net=multi-host-network -itd --name=container3 busybox 382 ``` 383 384 ### Managing /etc/hosts 385 386 Your container will have lines in `/etc/hosts` which define the hostname of the 387 container itself as well as `localhost` and a few other common things. The 388 `--add-host` flag can be used to add additional lines to `/etc/hosts`. 389 390 $ docker run -it --add-host db-static:86.75.30.9 ubuntu cat /etc/hosts 391 172.17.0.22 09d03f76bf2c 392 fe00::0 ip6-localnet 393 ff00::0 ip6-mcastprefix 394 ff02::1 ip6-allnodes 395 ff02::2 ip6-allrouters 396 127.0.0.1 localhost 397 ::1 localhost ip6-localhost ip6-loopback 398 86.75.30.9 db-static 399 400 ## Restart policies (--restart) 401 402 Using the `--restart` flag on Docker run you can specify a restart policy for 403 how a container should or should not be restarted on exit. 404 405 When a restart policy is active on a container, it will be shown as either `Up` 406 or `Restarting` in [`docker ps`](commandline/ps.md). It can also be 407 useful to use [`docker events`](commandline/events.md) to see the 408 restart policy in effect. 409 410 Docker supports the following restart policies: 411 412 <table> 413 <thead> 414 <tr> 415 <th>Policy</th> 416 <th>Result</th> 417 </tr> 418 </thead> 419 <tbody> 420 <tr> 421 <td><strong>no</strong></td> 422 <td> 423 Do not automatically restart the container when it exits. This is the 424 default. 425 </td> 426 </tr> 427 <tr> 428 <td> 429 <span style="white-space: nowrap"> 430 <strong>on-failure</strong>[:max-retries] 431 </span> 432 </td> 433 <td> 434 Restart only if the container exits with a non-zero exit status. 435 Optionally, limit the number of restart retries the Docker 436 daemon attempts. 437 </td> 438 </tr> 439 <tr> 440 <td><strong>always</strong></td> 441 <td> 442 Always restart the container regardless of the exit status. 443 When you specify always, the Docker daemon will try to restart 444 the container indefinitely. The container will also always start 445 on daemon startup, regardless of the current state of the container. 446 </td> 447 </tr> 448 <tr> 449 <td><strong>unless-stopped</strong></td> 450 <td> 451 Always restart the container regardless of the exit status, but 452 do not start it on daemon startup if the container has been put 453 to a stopped state before. 454 </td> 455 </tr> 456 </tbody> 457 </table> 458 459 An ever increasing delay (double the previous delay, starting at 100 460 milliseconds) is added before each restart to prevent flooding the server. 461 This means the daemon will wait for 100 ms, then 200 ms, 400, 800, 1600, 462 and so on until either the `on-failure` limit is hit, or when you `docker stop` 463 or `docker rm -f` the container. 464 465 If a container is successfully restarted (the container is started and runs 466 for at least 10 seconds), the delay is reset to its default value of 100 ms. 467 468 You can specify the maximum amount of times Docker will try to restart the 469 container when using the **on-failure** policy. The default is that Docker 470 will try forever to restart the container. The number of (attempted) restarts 471 for a container can be obtained via [`docker inspect`](commandline/inspect.md). For example, to get the number of restarts 472 for container "my-container"; 473 474 $ docker inspect -f "{{ .RestartCount }}" my-container 475 # 2 476 477 Or, to get the last time the container was (re)started; 478 479 $ docker inspect -f "{{ .State.StartedAt }}" my-container 480 # 2015-03-04T23:47:07.691840179Z 481 482 You cannot set any restart policy in combination with 483 ["clean up (--rm)"](#clean-up-rm). Setting both `--restart` and `--rm` 484 results in an error. 485 486 ### Examples 487 488 $ docker run --restart=always redis 489 490 This will run the `redis` container with a restart policy of **always** 491 so that if the container exits, Docker will restart it. 492 493 $ docker run --restart=on-failure:10 redis 494 495 This will run the `redis` container with a restart policy of **on-failure** 496 and a maximum restart count of 10. If the `redis` container exits with a 497 non-zero exit status more than 10 times in a row Docker will abort trying to 498 restart the container. Providing a maximum restart limit is only valid for the 499 **on-failure** policy. 500 501 ## Clean up (--rm) 502 503 By default a container's file system persists even after the container 504 exits. This makes debugging a lot easier (since you can inspect the 505 final state) and you retain all your data by default. But if you are 506 running short-term **foreground** processes, these container file 507 systems can really pile up. If instead you'd like Docker to 508 **automatically clean up the container and remove the file system when 509 the container exits**, you can add the `--rm` flag: 510 511 --rm=false: Automatically remove the container when it exits (incompatible with -d) 512 513 > **Note**: When you set the `--rm` flag, Docker also removes the volumes 514 associated with the container when the container is removed. This is similar 515 to running `docker rm -v my-container`. 516 517 ## Security configuration 518 --security-opt="label:user:USER" : Set the label user for the container 519 --security-opt="label:role:ROLE" : Set the label role for the container 520 --security-opt="label:type:TYPE" : Set the label type for the container 521 --security-opt="label:level:LEVEL" : Set the label level for the container 522 --security-opt="label:disable" : Turn off label confinement for the container 523 --security-opt="apparmor:PROFILE" : Set the apparmor profile to be applied 524 to the container 525 526 You can override the default labeling scheme for each container by specifying 527 the `--security-opt` flag. For example, you can specify the MCS/MLS level, a 528 requirement for MLS systems. Specifying the level in the following command 529 allows you to share the same content between containers. 530 531 $ docker run --security-opt label:level:s0:c100,c200 -i -t fedora bash 532 533 An MLS example might be: 534 535 $ docker run --security-opt label:level:TopSecret -i -t rhel7 bash 536 537 To disable the security labeling for this container versus running with the 538 `--permissive` flag, use the following command: 539 540 $ docker run --security-opt label:disable -i -t fedora bash 541 542 If you want a tighter security policy on the processes within a container, 543 you can specify an alternate type for the container. You could run a container 544 that is only allowed to listen on Apache ports by executing the following 545 command: 546 547 $ docker run --security-opt label:type:svirt_apache_t -i -t centos bash 548 549 > **Note**: You would have to write policy defining a `svirt_apache_t` type. 550 551 ## Specifying custom cgroups 552 553 Using the `--cgroup-parent` flag, you can pass a specific cgroup to run a 554 container in. This allows you to create and manage cgroups on their own. You can 555 define custom resources for those cgroups and put containers under a common 556 parent group. 557 558 ## Runtime constraints on resources 559 560 The operator can also adjust the performance parameters of the 561 container: 562 563 | Option | Description | 564 |----------------------------|---------------------------------------------------------------------------------------------| 565 | `-m`, `--memory="" ` | Memory limit (format: `<number>[<unit>]`, where unit = b, k, m or g) | 566 | `--memory-swap=""` | Total memory limit (memory + swap, format: `<number>[<unit>]`, where unit = b, k, m or g) | 567 | `--memory-reservation=""` | Memory soft limit (format: `<number>[<unit>]`, where unit = b, k, m or g) | 568 | `--kernel-memory=""` | Kernel memory limit (format: `<number>[<unit>]`, where unit = b, k, m or g) | 569 | `-c`, `--cpu-shares=0` | CPU shares (relative weight) | 570 | `--cpu-period=0` | Limit the CPU CFS (Completely Fair Scheduler) period | 571 | `--cpuset-cpus="" ` | CPUs in which to allow execution (0-3, 0,1) | 572 | `--cpuset-mems=""` | Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. | 573 | `--cpu-quota=0` | Limit the CPU CFS (Completely Fair Scheduler) quota | 574 | `--blkio-weight=0` | Block IO weight (relative weight) accepts a weight value between 10 and 1000. | 575 | `--oom-kill-disable=false` | Whether to disable OOM Killer for the container or not. | 576 | `--memory-swappiness="" ` | Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. | 577 578 ### User memory constraints 579 580 We have four ways to set user memory usage: 581 582 <table> 583 <thead> 584 <tr> 585 <th>Option</th> 586 <th>Result</th> 587 </tr> 588 </thead> 589 <tbody> 590 <tr> 591 <td class="no-wrap"> 592 <strong>memory=inf, memory-swap=inf</strong> (default) 593 </td> 594 <td> 595 There is no memory limit for the container. The container can use 596 as much memory as needed. 597 </td> 598 </tr> 599 <tr> 600 <td class="no-wrap"><strong>memory=L<inf, memory-swap=inf</strong></td> 601 <td> 602 (specify memory and set memory-swap as <code>-1</code>) The container is 603 not allowed to use more than L bytes of memory, but can use as much swap 604 as is needed (if the host supports swap memory). 605 </td> 606 </tr> 607 <tr> 608 <td class="no-wrap"><strong>memory=L<inf, memory-swap=2*L</strong></td> 609 <td> 610 (specify memory without memory-swap) The container is not allowed to 611 use more than L bytes of memory, swap *plus* memory usage is double 612 of that. 613 </td> 614 </tr> 615 <tr> 616 <td class="no-wrap"> 617 <strong>memory=L<inf, memory-swap=S<inf, L<=S</strong> 618 </td> 619 <td> 620 (specify both memory and memory-swap) The container is not allowed to 621 use more than L bytes of memory, swap *plus* memory usage is limited 622 by S. 623 </td> 624 </tr> 625 </tbody> 626 </table> 627 628 Examples: 629 630 $ docker run -ti ubuntu:14.04 /bin/bash 631 632 We set nothing about memory, this means the processes in the container can use 633 as much memory and swap memory as they need. 634 635 $ docker run -ti -m 300M --memory-swap -1 ubuntu:14.04 /bin/bash 636 637 We set memory limit and disabled swap memory limit, this means the processes in 638 the container can use 300M memory and as much swap memory as they need (if the 639 host supports swap memory). 640 641 $ docker run -ti -m 300M ubuntu:14.04 /bin/bash 642 643 We set memory limit only, this means the processes in the container can use 644 300M memory and 300M swap memory, by default, the total virtual memory size 645 (--memory-swap) will be set as double of memory, in this case, memory + swap 646 would be 2*300M, so processes can use 300M swap memory as well. 647 648 $ docker run -ti -m 300M --memory-swap 1G ubuntu:14.04 /bin/bash 649 650 We set both memory and swap memory, so the processes in the container can use 651 300M memory and 700M swap memory. 652 653 Memory reservation is a kind of memory soft limit that allows for greater 654 sharing of memory. Under normal circumstances, containers can use as much of 655 the memory as needed and are constrained only by the hard limits set with the 656 `-m`/`--memory` option. When memory reservation is set, Docker detects memory 657 contention or low memory and forces containers to restrict their consumption to 658 a reservation limit. 659 660 Always set the memory reservation value below the hard limit, otherwise the hard 661 limit takes precedence. A reservation of 0 is the same as setting no 662 reservation. By default (without reservation set), memory reservation is the 663 same as the hard memory limit. 664 665 Memory reservation is a soft-limit feature and does not guarantee the limit 666 won't be exceeded. Instead, the feature attempts to ensure that, when memory is 667 heavily contended for, memory is allocated based on the reservation hints/setup. 668 669 The following example limits the memory (`-m`) to 500M and sets the memory 670 reservation to 200M. 671 672 ```bash 673 $ docker run -ti -m 500M --memory-reservation 200M ubuntu:14.04 /bin/bash 674 ``` 675 676 Under this configuration, when the container consumes memory more than 200M and 677 less than 500M, the next system memory reclaim attempts to shrink container 678 memory below 200M. 679 680 The following example set memory reservation to 1G without a hard memory limit. 681 682 ```bash 683 $ docker run -ti --memory-reservation 1G ubuntu:14.04 /bin/bash 684 ``` 685 686 The container can use as much memory as it needs. The memory reservation setting 687 ensures the container doesn't consume too much memory for long time, because 688 every memory reclaim shrinks the container's consumption to the reservation. 689 690 By default, kernel kills processes in a container if an out-of-memory (OOM) 691 error occurs. To change this behaviour, use the `--oom-kill-disable` option. 692 Only disable the OOM killer on containers where you have also set the 693 `-m/--memory` option. If the `-m` flag is not set, this can result in the host 694 running out of memory and require killing the host's system processes to free 695 memory. 696 697 The following example limits the memory to 100M and disables the OOM killer for 698 this container: 699 700 $ docker run -ti -m 100M --oom-kill-disable ubuntu:14.04 /bin/bash 701 702 The following example, illustrates a dangerous way to use the flag: 703 704 $ docker run -ti --oom-kill-disable ubuntu:14.04 /bin/bash 705 706 The container has unlimited memory which can cause the host to run out memory 707 and require killing system processes to free memory. 708 709 ### Kernel memory constraints 710 711 Kernel memory is fundamentally different than user memory as kernel memory can't 712 be swapped out. The inability to swap makes it possible for the container to 713 block system services by consuming too much kernel memory. Kernel memory includes: 714 715 - stack pages 716 - slab pages 717 - sockets memory pressure 718 - tcp memory pressure 719 720 You can setup kernel memory limit to constrain these kinds of memory. For example, 721 every process consumes some stack pages. By limiting kernel memory, you can 722 prevent new processes from being created when the kernel memory usage is too high. 723 724 Kernel memory is never completely independent of user memory. Instead, you limit 725 kernel memory in the context of the user memory limit. Assume "U" is the user memory 726 limit and "K" the kernel limit. There are three possible ways to set limits: 727 728 <table> 729 <thead> 730 <tr> 731 <th>Option</th> 732 <th>Result</th> 733 </tr> 734 </thead> 735 <tbody> 736 <tr> 737 <td class="no-wrap"><strong>U != 0, K = inf</strong> (default)</td> 738 <td> 739 This is the standard memory limitation mechanism already present before using 740 kernel memory. Kernel memory is completely ignored. 741 </td> 742 </tr> 743 <tr> 744 <td class="no-wrap"><strong>U != 0, K < U</strong></td> 745 <td> 746 Kernel memory is a subset of the user memory. This setup is useful in 747 deployments where the total amount of memory per-cgroup is overcommitted. 748 Overcommitting kernel memory limits is definitely not recommended, since the 749 box can still run out of non-reclaimable memory. 750 In this case, the you can configure K so that the sum of all groups is 751 never greater than the total memory. Then, freely set U at the expense of 752 the system's service quality. 753 </td> 754 </tr> 755 <tr> 756 <td class="no-wrap"><strong>U != 0, K > U</strong></td> 757 <td> 758 Since kernel memory charges are also fed to the user counter and reclamation 759 is triggered for the container for both kinds of memory. This configuration 760 gives the admin a unified view of memory. It is also useful for people 761 who just want to track kernel memory usage. 762 </td> 763 </tr> 764 </tbody> 765 </table> 766 767 Examples: 768 769 $ docker run -ti -m 500M --kernel-memory 50M ubuntu:14.04 /bin/bash 770 771 We set memory and kernel memory, so the processes in the container can use 772 500M memory in total, in this 500M memory, it can be 50M kernel memory tops. 773 774 $ docker run -ti --kernel-memory 50M ubuntu:14.04 /bin/bash 775 776 We set kernel memory without **-m**, so the processes in the container can 777 use as much memory as they want, but they can only use 50M kernel memory. 778 779 ### Swappiness constraint 780 781 By default, a container's kernel can swap out a percentage of anonymous pages. 782 To set this percentage for a container, specify a `--memory-swappiness` value 783 between 0 and 100. A value of 0 turns off anonymous page swapping. A value of 784 100 sets all anonymous pages as swappable. By default, if you are not using 785 `--memory-swappiness`, memory swappiness value will be inherited from the parent. 786 787 For example, you can set: 788 789 $ docker run -ti --memory-swappiness=0 ubuntu:14.04 /bin/bash 790 791 Setting the `--memory-swappiness` option is helpful when you want to retain the 792 container's working set and to avoid swapping performance penalties. 793 794 ### CPU share constraint 795 796 By default, all containers get the same proportion of CPU cycles. This proportion 797 can be modified by changing the container's CPU share weighting relative 798 to the weighting of all other running containers. 799 800 To modify the proportion from the default of 1024, use the `-c` or `--cpu-shares` 801 flag to set the weighting to 2 or higher. If 0 is set, the system will ignore the 802 value and use the default of 1024. 803 804 The proportion will only apply when CPU-intensive processes are running. 805 When tasks in one container are idle, other containers can use the 806 left-over CPU time. The actual amount of CPU time will vary depending on 807 the number of containers running on the system. 808 809 For example, consider three containers, one has a cpu-share of 1024 and 810 two others have a cpu-share setting of 512. When processes in all three 811 containers attempt to use 100% of CPU, the first container would receive 812 50% of the total CPU time. If you add a fourth container with a cpu-share 813 of 1024, the first container only gets 33% of the CPU. The remaining containers 814 receive 16.5%, 16.5% and 33% of the CPU. 815 816 On a multi-core system, the shares of CPU time are distributed over all CPU 817 cores. Even if a container is limited to less than 100% of CPU time, it can 818 use 100% of each individual CPU core. 819 820 For example, consider a system with more than three cores. If you start one 821 container `{C0}` with `-c=512` running one process, and another container 822 `{C1}` with `-c=1024` running two processes, this can result in the following 823 division of CPU shares: 824 825 PID container CPU CPU share 826 100 {C0} 0 100% of CPU0 827 101 {C1} 1 100% of CPU1 828 102 {C1} 2 100% of CPU2 829 830 ### CPU period constraint 831 832 The default CPU CFS (Completely Fair Scheduler) period is 100ms. We can use 833 `--cpu-period` to set the period of CPUs to limit the container's CPU usage. 834 And usually `--cpu-period` should work with `--cpu-quota`. 835 836 Examples: 837 838 $ docker run -ti --cpu-period=50000 --cpu-quota=25000 ubuntu:14.04 /bin/bash 839 840 If there is 1 CPU, this means the container can get 50% CPU worth of run-time every 50ms. 841 842 For more information, see the [CFS documentation on bandwidth limiting](https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt). 843 844 ### Cpuset constraint 845 846 We can set cpus in which to allow execution for containers. 847 848 Examples: 849 850 $ docker run -ti --cpuset-cpus="1,3" ubuntu:14.04 /bin/bash 851 852 This means processes in container can be executed on cpu 1 and cpu 3. 853 854 $ docker run -ti --cpuset-cpus="0-2" ubuntu:14.04 /bin/bash 855 856 This means processes in container can be executed on cpu 0, cpu 1 and cpu 2. 857 858 We can set mems in which to allow execution for containers. Only effective 859 on NUMA systems. 860 861 Examples: 862 863 $ docker run -ti --cpuset-mems="1,3" ubuntu:14.04 /bin/bash 864 865 This example restricts the processes in the container to only use memory from 866 memory nodes 1 and 3. 867 868 $ docker run -ti --cpuset-mems="0-2" ubuntu:14.04 /bin/bash 869 870 This example restricts the processes in the container to only use memory from 871 memory nodes 0, 1 and 2. 872 873 ### CPU quota constraint 874 875 The `--cpu-quota` flag limits the container's CPU usage. The default 0 value 876 allows the container to take 100% of a CPU resource (1 CPU). The CFS (Completely Fair 877 Scheduler) handles resource allocation for executing processes and is default 878 Linux Scheduler used by the kernel. Set this value to 50000 to limit the container 879 to 50% of a CPU resource. For multiple CPUs, adjust the `--cpu-quota` as necessary. 880 For more information, see the [CFS documentation on bandwidth limiting](https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt). 881 882 ### Block IO bandwidth (Blkio) constraint 883 884 By default, all containers get the same proportion of block IO bandwidth 885 (blkio). This proportion is 500. To modify this proportion, change the 886 container's blkio weight relative to the weighting of all other running 887 containers using the `--blkio-weight` flag. 888 889 The `--blkio-weight` flag can set the weighting to a value between 10 to 1000. 890 For example, the commands below create two containers with different blkio 891 weight: 892 893 $ docker run -ti --name c1 --blkio-weight 300 ubuntu:14.04 /bin/bash 894 $ docker run -ti --name c2 --blkio-weight 600 ubuntu:14.04 /bin/bash 895 896 If you do block IO in the two containers at the same time, by, for example: 897 898 $ time dd if=/mnt/zerofile of=test.out bs=1M count=1024 oflag=direct 899 900 You'll find that the proportion of time is the same as the proportion of blkio 901 weights of the two containers. 902 903 > **Note:** The blkio weight setting is only available for direct IO. Buffered IO 904 > is not currently supported. 905 906 ## Additional groups 907 --group-add: Add Linux capabilities 908 909 By default, the docker container process runs with the supplementary groups looked 910 up for the specified user. If one wants to add more to that list of groups, then 911 one can use this flag: 912 913 $ docker run -ti --rm --group-add audio --group-add dbus --group-add 777 busybox id 914 uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777 915 916 ## Runtime privilege, Linux capabilities, and LXC configuration 917 918 --cap-add: Add Linux capabilities 919 --cap-drop: Drop Linux capabilities 920 --privileged=false: Give extended privileges to this container 921 --device=[]: Allows you to run devices inside the container without the --privileged flag. 922 --lxc-conf=[]: Add custom lxc options 923 924 By default, Docker containers are "unprivileged" and cannot, for 925 example, run a Docker daemon inside a Docker container. This is because 926 by default a container is not allowed to access any devices, but a 927 "privileged" container is given access to all devices (see [lxc-template.go]( 928 https://github.com/docker/docker/blob/master/daemon/execdriver/lxc/lxc_template.go) 929 and documentation on [cgroups devices]( 930 https://www.kernel.org/doc/Documentation/cgroups/devices.txt)). 931 932 When the operator executes `docker run --privileged`, Docker will enable 933 to access to all devices on the host as well as set some configuration 934 in AppArmor or SELinux to allow the container nearly all the same access to the 935 host as processes running outside containers on the host. Additional 936 information about running with `--privileged` is available on the 937 [Docker Blog](http://blog.docker.com/2013/09/docker-can-now-run-within-docker/). 938 939 If you want to limit access to a specific device or devices you can use 940 the `--device` flag. It allows you to specify one or more devices that 941 will be accessible within the container. 942 943 $ docker run --device=/dev/snd:/dev/snd ... 944 945 By default, the container will be able to `read`, `write`, and `mknod` these devices. 946 This can be overridden using a third `:rwm` set of options to each `--device` flag: 947 948 $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc 949 950 Command (m for help): q 951 $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc 952 You will not be able to write the partition table. 953 954 Command (m for help): q 955 956 $ docker run --device=/dev/sda:/dev/xvdc:w --rm -it ubuntu fdisk /dev/xvdc 957 crash.... 958 959 $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc 960 fdisk: unable to open /dev/xvdc: Operation not permitted 961 962 In addition to `--privileged`, the operator can have fine grain control over the 963 capabilities using `--cap-add` and `--cap-drop`. By default, Docker has a default 964 list of capabilities that are kept. The following table lists the Linux capability options which can be added or dropped. 965 966 | Capability Key | Capability Description | 967 | -------------- | ---------------------- | 968 | SETPCAP | Modify process capabilities. | 969 | SYS_MODULE| Load and unload kernel modules. | 970 | SYS_RAWIO | Perform I/O port operations (iopl(2) and ioperm(2)). | 971 | SYS_PACCT | Use acct(2), switch process accounting on or off. | 972 | SYS_ADMIN | Perform a range of system administration operations. | 973 | SYS_NICE | Raise process nice value (nice(2), setpriority(2)) and change the nice value for arbitrary processes. | 974 | SYS_RESOURCE | Override resource Limits. | 975 | SYS_TIME | Set system clock (settimeofday(2), stime(2), adjtimex(2)); set real-time (hardware) clock. | 976 | SYS_TTY_CONFIG | Use vhangup(2); employ various privileged ioctl(2) operations on virtual terminals. | 977 | MKNOD | Create special files using mknod(2). | 978 | AUDIT_WRITE | Write records to kernel auditing log. | 979 | AUDIT_CONTROL | Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules. | 980 | MAC_OVERRIDE | Allow MAC configuration or state changes. Implemented for the Smack LSM. | 981 | MAC_ADMIN | Override Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM). | 982 | NET_ADMIN | Perform various network-related operations. | 983 | SYSLOG | Perform privileged syslog(2) operations. | 984 | CHOWN | Make arbitrary changes to file UIDs and GIDs (see chown(2)). | 985 | NET_RAW | Use RAW and PACKET sockets. | 986 | DAC_OVERRIDE | Bypass file read, write, and execute permission checks. | 987 | FOWNER | Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file. | 988 | DAC_READ_SEARCH | Bypass file read permission checks and directory read and execute permission checks. | 989 | FSETID | Don't clear set-user-ID and set-group-ID permission bits when a file is modified. | 990 | KILL | Bypass permission checks for sending signals. | 991 | SETGID | Make arbitrary manipulations of process GIDs and supplementary GID list. | 992 | SETUID | Make arbitrary manipulations of process UIDs. | 993 | LINUX_IMMUTABLE | Set the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags. | 994 | NET_BIND_SERVICE | Bind a socket to internet domain privileged ports (port numbers less than 1024). | 995 | NET_BROADCAST | Make socket broadcasts, and listen to multicasts. | 996 | IPC_LOCK | Lock memory (mlock(2), mlockall(2), mmap(2), shmctl(2)). | 997 | IPC_OWNER | Bypass permission checks for operations on System V IPC objects. | 998 | SYS_CHROOT | Use chroot(2), change root directory. | 999 | SYS_PTRACE | Trace arbitrary processes using ptrace(2). | 1000 | SYS_BOOT | Use reboot(2) and kexec_load(2), reboot and load a new kernel for later execution. | 1001 | LEASE | Establish leases on arbitrary files (see fcntl(2)). | 1002 | SETFCAP | Set file capabilities.| 1003 | WAKE_ALARM | Trigger something that will wake up the system. | 1004 | BLOCK_SUSPEND | Employ features that can block system suspend. | 1005 1006 Further reference information is available on the [capabilities(7) - Linux man page](http://linux.die.net/man/7/capabilities) 1007 1008 Both flags support the value `ALL`, so if the 1009 operator wants to have all capabilities but `MKNOD` they could use: 1010 1011 $ docker run --cap-add=ALL --cap-drop=MKNOD ... 1012 1013 For interacting with the network stack, instead of using `--privileged` they 1014 should use `--cap-add=NET_ADMIN` to modify the network interfaces. 1015 1016 $ docker run -t -i --rm ubuntu:14.04 ip link add dummy0 type dummy 1017 RTNETLINK answers: Operation not permitted 1018 $ docker run -t -i --rm --cap-add=NET_ADMIN ubuntu:14.04 ip link add dummy0 type dummy 1019 1020 To mount a FUSE based filesystem, you need to combine both `--cap-add` and 1021 `--device`: 1022 1023 $ docker run --rm -it --cap-add SYS_ADMIN sshfs sshfs sven@10.10.10.20:/home/sven /mnt 1024 fuse: failed to open /dev/fuse: Operation not permitted 1025 $ docker run --rm -it --device /dev/fuse sshfs sshfs sven@10.10.10.20:/home/sven /mnt 1026 fusermount: mount failed: Operation not permitted 1027 $ docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs 1028 # sshfs sven@10.10.10.20:/home/sven /mnt 1029 The authenticity of host '10.10.10.20 (10.10.10.20)' can't be established. 1030 ECDSA key fingerprint is 25:34:85:75:25:b0:17:46:05:19:04:93:b5:dd:5f:c6. 1031 Are you sure you want to continue connecting (yes/no)? yes 1032 sven@10.10.10.20's password: 1033 root@30aa0cfaf1b5:/# ls -la /mnt/src/docker 1034 total 1516 1035 drwxrwxr-x 1 1000 1000 4096 Dec 4 06:08 . 1036 drwxrwxr-x 1 1000 1000 4096 Dec 4 11:46 .. 1037 -rw-rw-r-- 1 1000 1000 16 Oct 8 00:09 .dockerignore 1038 -rwxrwxr-x 1 1000 1000 464 Oct 8 00:09 .drone.yml 1039 drwxrwxr-x 1 1000 1000 4096 Dec 4 06:11 .git 1040 -rw-rw-r-- 1 1000 1000 461 Dec 4 06:08 .gitignore 1041 .... 1042 1043 1044 If the Docker daemon was started using the `lxc` exec-driver 1045 (`docker daemon --exec-driver=lxc`) then the operator can also specify LXC options 1046 using one or more `--lxc-conf` parameters. These can be new parameters or 1047 override existing parameters from the [lxc-template.go]( 1048 https://github.com/docker/docker/blob/master/daemon/execdriver/lxc/lxc_template.go). 1049 Note that in the future, a given host's docker daemon may not use LXC, so this 1050 is an implementation-specific configuration meant for operators already 1051 familiar with using LXC directly. 1052 1053 > **Note:** 1054 > If you use `--lxc-conf` to modify a container's configuration which is also 1055 > managed by the Docker daemon, then the Docker daemon will not know about this 1056 > modification, and you will need to manage any conflicts yourself. For example, 1057 > you can use `--lxc-conf` to set a container's IP address, but this will not be 1058 > reflected in the `/etc/hosts` file. 1059 1060 ## Logging drivers (--log-driver) 1061 1062 The container can have a different logging driver than the Docker daemon. Use 1063 the `--log-driver=VALUE` with the `docker run` command to configure the 1064 container's logging driver. The following options are supported: 1065 1066 | `none` | Disables any logging for the container. `docker logs` won't be available with this driver. | 1067 |-------------|-------------------------------------------------------------------------------------------------------------------------------| 1068 | `json-file` | Default logging driver for Docker. Writes JSON messages to file. No logging options are supported for this driver. | 1069 | `syslog` | Syslog logging driver for Docker. Writes log messages to syslog. | 1070 | `journald` | Journald logging driver for Docker. Writes log messages to `journald`. | 1071 | `gelf` | Graylog Extended Log Format (GELF) logging driver for Docker. Writes log messages to a GELF endpoint likeGraylog or Logstash. | 1072 | `fluentd` | Fluentd logging driver for Docker. Writes log messages to `fluentd` (forward input). | 1073 | `awslogs` | Amazon CloudWatch Logs logging driver for Docker. Writes log messages to Amazon CloudWatch Logs | 1074 1075 The `docker logs` command is available only for the `json-file` and `journald` 1076 logging drivers. For detailed information on working with logging drivers, see 1077 [Configure a logging driver](logging/overview.md). 1078 1079 1080 ## Overriding Dockerfile image defaults 1081 1082 When a developer builds an image from a [*Dockerfile*](builder.md) 1083 or when she commits it, the developer can set a number of default parameters 1084 that take effect when the image starts up as a container. 1085 1086 Four of the Dockerfile commands cannot be overridden at runtime: `FROM`, 1087 `MAINTAINER`, `RUN`, and `ADD`. Everything else has a corresponding override 1088 in `docker run`. We'll go through what the developer might have set in each 1089 Dockerfile instruction and how the operator can override that setting. 1090 1091 - [CMD (Default Command or Options)](#cmd-default-command-or-options) 1092 - [ENTRYPOINT (Default Command to Execute at Runtime)]( 1093 #entrypoint-default-command-to-execute-at-runtime) 1094 - [EXPOSE (Incoming Ports)](#expose-incoming-ports) 1095 - [ENV (Environment Variables)](#env-environment-variables) 1096 - [VOLUME (Shared Filesystems)](#volume-shared-filesystems) 1097 - [USER](#user) 1098 - [WORKDIR](#workdir) 1099 1100 ### CMD (default command or options) 1101 1102 Recall the optional `COMMAND` in the Docker 1103 commandline: 1104 1105 $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...] 1106 1107 This command is optional because the person who created the `IMAGE` may 1108 have already provided a default `COMMAND` using the Dockerfile `CMD` 1109 instruction. As the operator (the person running a container from the 1110 image), you can override that `CMD` instruction just by specifying a new 1111 `COMMAND`. 1112 1113 If the image also specifies an `ENTRYPOINT` then the `CMD` or `COMMAND` 1114 get appended as arguments to the `ENTRYPOINT`. 1115 1116 ### ENTRYPOINT (default command to execute at runtime) 1117 1118 --entrypoint="": Overwrite the default entrypoint set by the image 1119 1120 The `ENTRYPOINT` of an image is similar to a `COMMAND` because it 1121 specifies what executable to run when the container starts, but it is 1122 (purposely) more difficult to override. The `ENTRYPOINT` gives a 1123 container its default nature or behavior, so that when you set an 1124 `ENTRYPOINT` you can run the container *as if it were that binary*, 1125 complete with default options, and you can pass in more options via the 1126 `COMMAND`. But, sometimes an operator may want to run something else 1127 inside the container, so you can override the default `ENTRYPOINT` at 1128 runtime by using a string to specify the new `ENTRYPOINT`. Here is an 1129 example of how to run a shell in a container that has been set up to 1130 automatically run something else (like `/usr/bin/redis-server`): 1131 1132 $ docker run -i -t --entrypoint /bin/bash example/redis 1133 1134 or two examples of how to pass more parameters to that ENTRYPOINT: 1135 1136 $ docker run -i -t --entrypoint /bin/bash example/redis -c ls -l 1137 $ docker run -i -t --entrypoint /usr/bin/redis-cli example/redis --help 1138 1139 ### EXPOSE (incoming ports) 1140 1141 The following `run` command options work with container networking: 1142 1143 --expose=[]: Expose a port or a range of ports inside the container. 1144 These are additional to those exposed by the `EXPOSE` instruction 1145 -P=false : Publish all exposed ports to the host interfaces 1146 -p=[] : Publish a container᾿s port or a range of ports to the host 1147 format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort 1148 Both hostPort and containerPort can be specified as a 1149 range of ports. When specifying ranges for both, the 1150 number of container ports in the range must match the 1151 number of host ports in the range, for example: 1152 -p 1234-1236:1234-1236/tcp 1153 1154 When specifying a range for hostPort only, the 1155 containerPort must not be a range. In this case the 1156 container port is published somewhere within the 1157 specified hostPort range. (e.g., `-p 1234-1236:1234/tcp`) 1158 1159 (use 'docker port' to see the actual mapping) 1160 1161 --link="" : Add link to another container (<name or id>:alias or <name or id>) 1162 1163 With the exception of the `EXPOSE` directive, an image developer hasn't 1164 got much control over networking. The `EXPOSE` instruction defines the 1165 initial incoming ports that provide services. These ports are available 1166 to processes inside the container. An operator can use the `--expose` 1167 option to add to the exposed ports. 1168 1169 To expose a container's internal port, an operator can start the 1170 container with the `-P` or `-p` flag. The exposed port is accessible on 1171 the host and the ports are available to any client that can reach the 1172 host. 1173 1174 The `-P` option publishes all the ports to the host interfaces. Docker 1175 binds each exposed port to a random port on the host. The range of 1176 ports are within an *ephemeral port range* defined by 1177 `/proc/sys/net/ipv4/ip_local_port_range`. Use the `-p` flag to 1178 explicitly map a single port or range of ports. 1179 1180 The port number inside the container (where the service listens) does 1181 not need to match the port number exposed on the outside of the 1182 container (where clients connect). For example, inside the container an 1183 HTTP service is listening on port 80 (and so the image developer 1184 specifies `EXPOSE 80` in the Dockerfile). At runtime, the port might be 1185 bound to 42800 on the host. To find the mapping between the host ports 1186 and the exposed ports, use `docker port`. 1187 1188 If the operator uses `--link` when starting a new client container, 1189 then the client container can access the exposed port via a private 1190 networking interface. Docker will set some environment variables in the 1191 client container to help indicate which interface and port to use. For 1192 more information on linking, see [the guide on linking container 1193 together](../userguide/dockerlinks.md) 1194 1195 ### ENV (environment variables) 1196 1197 When a new container is created, Docker will set the following environment 1198 variables automatically: 1199 1200 <table> 1201 <tr> 1202 <th>Variable</th> 1203 <th>Value</th> 1204 </tr> 1205 <tr> 1206 <td><code>HOME</code></td> 1207 <td> 1208 Set based on the value of <code>USER</code> 1209 </td> 1210 </tr> 1211 <tr> 1212 <td><code>HOSTNAME</code></td> 1213 <td> 1214 The hostname associated with the container 1215 </td> 1216 </tr> 1217 <tr> 1218 <td><code>PATH</code></td> 1219 <td> 1220 Includes popular directories, such as :<br> 1221 <code>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin</code> 1222 </td> 1223 <tr> 1224 <td><code>TERM</code></td> 1225 <td><code>xterm</code> if the container is allocated a pseudo-TTY</td> 1226 </tr> 1227 </table> 1228 1229 The container may also include environment variables defined 1230 as a result of the container being linked with another container. See 1231 the [*Container Links*](../userguide/dockerlinks.md#connect-with-the-linking-system) 1232 section for more details. 1233 1234 Additionally, the operator can **set any environment variable** in the 1235 container by using one or more `-e` flags, even overriding those mentioned 1236 above, or already defined by the developer with a Dockerfile `ENV`: 1237 1238 $ docker run -e "deep=purple" --rm ubuntu /bin/bash -c export 1239 declare -x HOME="/" 1240 declare -x HOSTNAME="85bc26a0e200" 1241 declare -x OLDPWD 1242 declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" 1243 declare -x PWD="/" 1244 declare -x SHLVL="1" 1245 declare -x container="lxc" 1246 declare -x deep="purple" 1247 1248 Similarly the operator can set the **hostname** with `-h`. 1249 1250 `--link <name or id>:alias` also sets environment variables, using the *alias* string to 1251 define environment variables within the container that give the IP and PORT 1252 information for connecting to the service container. Let's imagine we have a 1253 container running Redis: 1254 1255 # Start the service container, named redis-name 1256 $ docker run -d --name redis-name dockerfiles/redis 1257 4241164edf6f5aca5b0e9e4c9eccd899b0b8080c64c0cd26efe02166c73208f3 1258 1259 # The redis-name container exposed port 6379 1260 $ docker ps 1261 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1262 4241164edf6f $ dockerfiles/redis:latest /redis-stable/src/re 5 seconds ago Up 4 seconds 6379/tcp redis-name 1263 1264 # Note that there are no public ports exposed since we didn᾿t use -p or -P 1265 $ docker port 4241164edf6f 6379 1266 2014/01/25 00:55:38 Error: No public port '6379' published for 4241164edf6f 1267 1268 Yet we can get information about the Redis container's exposed ports 1269 with `--link`. Choose an alias that will form a 1270 valid environment variable! 1271 1272 $ docker run --rm --link redis-name:redis_alias --entrypoint /bin/bash dockerfiles/redis -c export 1273 declare -x HOME="/" 1274 declare -x HOSTNAME="acda7f7b1cdc" 1275 declare -x OLDPWD 1276 declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" 1277 declare -x PWD="/" 1278 declare -x REDIS_ALIAS_NAME="/distracted_wright/redis" 1279 declare -x REDIS_ALIAS_PORT="tcp://172.17.0.32:6379" 1280 declare -x REDIS_ALIAS_PORT_6379_TCP="tcp://172.17.0.32:6379" 1281 declare -x REDIS_ALIAS_PORT_6379_TCP_ADDR="172.17.0.32" 1282 declare -x REDIS_ALIAS_PORT_6379_TCP_PORT="6379" 1283 declare -x REDIS_ALIAS_PORT_6379_TCP_PROTO="tcp" 1284 declare -x SHLVL="1" 1285 declare -x container="lxc" 1286 1287 And we can use that information to connect from another container as a client: 1288 1289 $ docker run -i -t --rm --link redis-name:redis_alias --entrypoint /bin/bash dockerfiles/redis -c '/redis-stable/src/redis-cli -h $REDIS_ALIAS_PORT_6379_TCP_ADDR -p $REDIS_ALIAS_PORT_6379_TCP_PORT' 1290 172.17.0.32:6379> 1291 1292 Docker will also map the private IP address to the alias of a linked 1293 container by inserting an entry into `/etc/hosts`. You can use this 1294 mechanism to communicate with a linked container by its alias: 1295 1296 $ docker run -d --name servicename busybox sleep 30 1297 $ docker run -i -t --link servicename:servicealias busybox ping -c 1 servicealias 1298 1299 If you restart the source container (`servicename` in this case), the recipient 1300 container's `/etc/hosts` entry will be automatically updated. 1301 1302 > **Note**: 1303 > Unlike host entries in the `/etc/hosts` file, IP addresses stored in the 1304 > environment variables are not automatically updated if the source container is 1305 > restarted. We recommend using the host entries in `/etc/hosts` to resolve the 1306 > IP address of linked containers. 1307 1308 ### VOLUME (shared filesystems) 1309 1310 -v=[]: Create a bind mount with: [host-dir:]container-dir[:<options>], where 1311 options are comma delimited and selected from [rw|ro] and [z|Z]. 1312 If 'host-dir' is missing, then docker creates a new volume. 1313 If neither 'rw' or 'ro' is specified then the volume is mounted 1314 in read-write mode. 1315 --volumes-from="": Mount all volumes from the given container(s) 1316 1317 > **Note**: 1318 > The auto-creation of the host path has been [*deprecated*](../misc/deprecated.md#auto-creating-missing-host-paths-for-bind-mounts). 1319 1320 The volumes commands are complex enough to have their own documentation 1321 in section [*Managing data in 1322 containers*](../userguide/dockervolumes.md). A developer can define 1323 one or more `VOLUME`'s associated with an image, but only the operator 1324 can give access from one container to another (or from a container to a 1325 volume mounted on the host). 1326 1327 The `container-dir` must always be an absolute path such as `/src/docs`. 1328 The `host-dir` can either be an absolute path or a `name` value. If you 1329 supply an absolute path for the `host-dir`, Docker bind-mounts to the path 1330 you specify. If you supply a `name`, Docker creates a named volume by that `name`. 1331 1332 A `name` value must start with start with an alphanumeric character, 1333 followed by `a-z0-9`, `_` (underscore), `.` (period) or `-` (hyphen). 1334 An absolute path starts with a `/` (forward slash). 1335 1336 For example, you can specify either `/foo` or `foo` for a `host-dir` value. 1337 If you supply the `/foo` value, Docker creates a bind-mount. If you supply 1338 the `foo` specification, Docker creates a named volume. 1339 1340 ### USER 1341 1342 `root` (id = 0) is the default user within a container. The image developer can 1343 create additional users. Those users are accessible by name. When passing a numeric 1344 ID, the user does not have to exist in the container. 1345 1346 The developer can set a default user to run the first process with the 1347 Dockerfile `USER` instruction. When starting a container, the operator can override 1348 the `USER` instruction by passing the `-u` option. 1349 1350 -u="": Username or UID 1351 1352 > **Note:** if you pass a numeric uid, it must be in the range of 0-2147483647. 1353 1354 ### WORKDIR 1355 1356 The default working directory for running binaries within a container is the 1357 root directory (`/`), but the developer can set a different default with the 1358 Dockerfile `WORKDIR` command. The operator can override this with: 1359 1360 -w="": Working directory inside the container