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