github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/docs/reference/builder.md (about) 1 --- 2 description: "Dockerfiles use a simple DSL which allows you to automate the steps you would normally manually take to create an image." 3 keywords: "builder, docker, Dockerfile, automation, image creation" 4 redirect_from: 5 - /reference/builder/ 6 --- 7 8 <!-- This file is maintained within the docker/cli GitHub 9 repository at https://github.com/docker/cli/. Make all 10 pull requests against that repo. If you see this file in 11 another repository, consider it read-only there, as it will 12 periodically be overwritten by the definitive file. Pull 13 requests which include edits to this file in other repositories 14 will be rejected. 15 --> 16 17 # Dockerfile reference 18 19 Docker can build images automatically by reading the instructions from a 20 `Dockerfile`. A `Dockerfile` is a text document that contains all the commands a 21 user could call on the command line to assemble an image. Using `docker build` 22 users can create an automated build that executes several command-line 23 instructions in succession. 24 25 This page describes the commands you can use in a `Dockerfile`. When you are 26 done reading this page, refer to the [`Dockerfile` Best 27 Practices](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/) for a tip-oriented guide. 28 29 ## Usage 30 31 The [`docker build`](commandline/build.md) command builds an image from 32 a `Dockerfile` and a *context*. The build's context is the set of files at a 33 specified location `PATH` or `URL`. The `PATH` is a directory on your local 34 filesystem. The `URL` is a Git repository location. 35 36 A context is processed recursively. So, a `PATH` includes any subdirectories and 37 the `URL` includes the repository and its submodules. This example shows a 38 build command that uses the current directory as context: 39 40 $ docker build . 41 Sending build context to Docker daemon 6.51 MB 42 ... 43 44 The build is run by the Docker daemon, not by the CLI. The first thing a build 45 process does is send the entire context (recursively) to the daemon. In most 46 cases, it's best to start with an empty directory as context and keep your 47 Dockerfile in that directory. Add only the files needed for building the 48 Dockerfile. 49 50 >**Warning**: Do not use your root directory, `/`, as the `PATH` as it causes 51 >the build to transfer the entire contents of your hard drive to the Docker 52 >daemon. 53 54 To use a file in the build context, the `Dockerfile` refers to the file specified 55 in an instruction, for example, a `COPY` instruction. To increase the build's 56 performance, exclude files and directories by adding a `.dockerignore` file to 57 the context directory. For information about how to [create a `.dockerignore` 58 file](#dockerignore-file) see the documentation on this page. 59 60 Traditionally, the `Dockerfile` is called `Dockerfile` and located in the root 61 of the context. You use the `-f` flag with `docker build` to point to a Dockerfile 62 anywhere in your file system. 63 64 $ docker build -f /path/to/a/Dockerfile . 65 66 You can specify a repository and tag at which to save the new image if 67 the build succeeds: 68 69 $ docker build -t shykes/myapp . 70 71 To tag the image into multiple repositories after the build, 72 add multiple `-t` parameters when you run the `build` command: 73 74 $ docker build -t shykes/myapp:1.0.2 -t shykes/myapp:latest . 75 76 Before the Docker daemon runs the instructions in the `Dockerfile`, it performs 77 a preliminary validation of the `Dockerfile` and returns an error if the syntax is incorrect: 78 79 $ docker build -t test/myapp . 80 Sending build context to Docker daemon 2.048 kB 81 Error response from daemon: Unknown instruction: RUNCMD 82 83 The Docker daemon runs the instructions in the `Dockerfile` one-by-one, 84 committing the result of each instruction 85 to a new image if necessary, before finally outputting the ID of your 86 new image. The Docker daemon will automatically clean up the context you 87 sent. 88 89 Note that each instruction is run independently, and causes a new image 90 to be created - so `RUN cd /tmp` will not have any effect on the next 91 instructions. 92 93 Whenever possible, Docker will re-use the intermediate images (cache), 94 to accelerate the `docker build` process significantly. This is indicated by 95 the `Using cache` message in the console output. 96 (For more information, see the [Build cache section](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#build-cache) in the 97 `Dockerfile` best practices guide): 98 99 $ docker build -t svendowideit/ambassador . 100 Sending build context to Docker daemon 15.36 kB 101 Step 1/4 : FROM alpine:3.2 102 ---> 31f630c65071 103 Step 2/4 : MAINTAINER SvenDowideit@home.org.au 104 ---> Using cache 105 ---> 2a1c91448f5f 106 Step 3/4 : RUN apk update && apk add socat && rm -r /var/cache/ 107 ---> Using cache 108 ---> 21ed6e7fbb73 109 Step 4/4 : CMD env | grep _TCP= | (sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat -t 100000000 TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/' && echo wait) | sh 110 ---> Using cache 111 ---> 7ea8aef582cc 112 Successfully built 7ea8aef582cc 113 114 Build cache is only used from images that have a local parent chain. This means 115 that these images were created by previous builds or the whole chain of images 116 was loaded with `docker load`. If you wish to use build cache of a specific 117 image you can specify it with `--cache-from` option. Images specified with 118 `--cache-from` do not need to have a parent chain and may be pulled from other 119 registries. 120 121 When you're done with your build, you're ready to look into [*Pushing a 122 repository to its registry*](https://docs.docker.com/engine/tutorials/dockerrepos/#/contributing-to-docker-hub). 123 124 ## Format 125 126 Here is the format of the `Dockerfile`: 127 128 ```Dockerfile 129 # Comment 130 INSTRUCTION arguments 131 ``` 132 133 The instruction is not case-sensitive. However, convention is for them to 134 be UPPERCASE to distinguish them from arguments more easily. 135 136 137 Docker runs instructions in a `Dockerfile` in order. A `Dockerfile` **must 138 start with a \`FROM\` instruction**. The `FROM` instruction specifies the [*Base 139 Image*](glossary.md#base-image) from which you are building. `FROM` may only be 140 preceded by one or more `ARG` instructions, which declare arguments that are used 141 in `FROM` lines in the `Dockerfile`. 142 143 Docker treats lines that *begin* with `#` as a comment, unless the line is 144 a valid [parser directive](#parser-directives). A `#` marker anywhere 145 else in a line is treated as an argument. This allows statements like: 146 147 ```Dockerfile 148 # Comment 149 RUN echo 'we are running some # of cool things' 150 ``` 151 152 Line continuation characters are not supported in comments. 153 154 ## Parser directives 155 156 Parser directives are optional, and affect the way in which subsequent lines 157 in a `Dockerfile` are handled. Parser directives do not add layers to the build, 158 and will not be shown as a build step. Parser directives are written as a 159 special type of comment in the form `# directive=value`. A single directive 160 may only be used once. 161 162 Once a comment, empty line or builder instruction has been processed, Docker 163 no longer looks for parser directives. Instead it treats anything formatted 164 as a parser directive as a comment and does not attempt to validate if it might 165 be a parser directive. Therefore, all parser directives must be at the very 166 top of a `Dockerfile`. 167 168 Parser directives are not case-sensitive. However, convention is for them to 169 be lowercase. Convention is also to include a blank line following any 170 parser directives. Line continuation characters are not supported in parser 171 directives. 172 173 Due to these rules, the following examples are all invalid: 174 175 Invalid due to line continuation: 176 177 ```Dockerfile 178 # direc \ 179 tive=value 180 ``` 181 182 Invalid due to appearing twice: 183 184 ```Dockerfile 185 # directive=value1 186 # directive=value2 187 188 FROM ImageName 189 ``` 190 191 Treated as a comment due to appearing after a builder instruction: 192 193 ```Dockerfile 194 FROM ImageName 195 # directive=value 196 ``` 197 198 Treated as a comment due to appearing after a comment which is not a parser 199 directive: 200 201 ```Dockerfile 202 # About my dockerfile 203 # directive=value 204 FROM ImageName 205 ``` 206 207 The unknown directive is treated as a comment due to not being recognized. In 208 addition, the known directive is treated as a comment due to appearing after 209 a comment which is not a parser directive. 210 211 ```Dockerfile 212 # unknowndirective=value 213 # knowndirective=value 214 ``` 215 216 Non line-breaking whitespace is permitted in a parser directive. Hence, the 217 following lines are all treated identically: 218 219 ```Dockerfile 220 #directive=value 221 # directive =value 222 # directive= value 223 # directive = value 224 # dIrEcTiVe=value 225 ``` 226 227 The following parser directive is supported: 228 229 * `escape` 230 231 ## escape 232 233 # escape=\ (backslash) 234 235 Or 236 237 # escape=` (backtick) 238 239 The `escape` directive sets the character used to escape characters in a 240 `Dockerfile`. If not specified, the default escape character is `\`. 241 242 The escape character is used both to escape characters in a line, and to 243 escape a newline. This allows a `Dockerfile` instruction to 244 span multiple lines. Note that regardless of whether the `escape` parser 245 directive is included in a `Dockerfile`, *escaping is not performed in 246 a `RUN` command, except at the end of a line.* 247 248 Setting the escape character to `` ` `` is especially useful on 249 `Windows`, where `\` is the directory path separator. `` ` `` is consistent 250 with [Windows PowerShell](https://technet.microsoft.com/en-us/library/hh847755.aspx). 251 252 Consider the following example which would fail in a non-obvious way on 253 `Windows`. The second `\` at the end of the second line would be interpreted as an 254 escape for the newline, instead of a target of the escape from the first `\`. 255 Similarly, the `\` at the end of the third line would, assuming it was actually 256 handled as an instruction, cause it be treated as a line continuation. The result 257 of this dockerfile is that second and third lines are considered a single 258 instruction: 259 260 ```Dockerfile 261 FROM microsoft/nanoserver 262 COPY testfile.txt c:\\ 263 RUN dir c:\ 264 ``` 265 266 Results in: 267 268 PS C:\John> docker build -t cmd . 269 Sending build context to Docker daemon 3.072 kB 270 Step 1/2 : FROM microsoft/nanoserver 271 ---> 22738ff49c6d 272 Step 2/2 : COPY testfile.txt c:\RUN dir c: 273 GetFileAttributesEx c:RUN: The system cannot find the file specified. 274 PS C:\John> 275 276 One solution to the above would be to use `/` as the target of both the `COPY` 277 instruction, and `dir`. However, this syntax is, at best, confusing as it is not 278 natural for paths on `Windows`, and at worst, error prone as not all commands on 279 `Windows` support `/` as the path separator. 280 281 By adding the `escape` parser directive, the following `Dockerfile` succeeds as 282 expected with the use of natural platform semantics for file paths on `Windows`: 283 284 # escape=` 285 286 FROM microsoft/nanoserver 287 COPY testfile.txt c:\ 288 RUN dir c:\ 289 290 Results in: 291 292 PS C:\John> docker build -t succeeds --no-cache=true . 293 Sending build context to Docker daemon 3.072 kB 294 Step 1/3 : FROM microsoft/nanoserver 295 ---> 22738ff49c6d 296 Step 2/3 : COPY testfile.txt c:\ 297 ---> 96655de338de 298 Removing intermediate container 4db9acbb1682 299 Step 3/3 : RUN dir c:\ 300 ---> Running in a2c157f842f5 301 Volume in drive C has no label. 302 Volume Serial Number is 7E6D-E0F7 303 304 Directory of c:\ 305 306 10/05/2016 05:04 PM 1,894 License.txt 307 10/05/2016 02:22 PM <DIR> Program Files 308 10/05/2016 02:14 PM <DIR> Program Files (x86) 309 10/28/2016 11:18 AM 62 testfile.txt 310 10/28/2016 11:20 AM <DIR> Users 311 10/28/2016 11:20 AM <DIR> Windows 312 2 File(s) 1,956 bytes 313 4 Dir(s) 21,259,096,064 bytes free 314 ---> 01c7f3bef04f 315 Removing intermediate container a2c157f842f5 316 Successfully built 01c7f3bef04f 317 PS C:\John> 318 319 ## Environment replacement 320 321 Environment variables (declared with [the `ENV` statement](#env)) can also be 322 used in certain instructions as variables to be interpreted by the 323 `Dockerfile`. Escapes are also handled for including variable-like syntax 324 into a statement literally. 325 326 Environment variables are notated in the `Dockerfile` either with 327 `$variable_name` or `${variable_name}`. They are treated equivalently and the 328 brace syntax is typically used to address issues with variable names with no 329 whitespace, like `${foo}_bar`. 330 331 The `${variable_name}` syntax also supports a few of the standard `bash` 332 modifiers as specified below: 333 334 * `${variable:-word}` indicates that if `variable` is set then the result 335 will be that value. If `variable` is not set then `word` will be the result. 336 * `${variable:+word}` indicates that if `variable` is set then `word` will be 337 the result, otherwise the result is the empty string. 338 339 In all cases, `word` can be any string, including additional environment 340 variables. 341 342 Escaping is possible by adding a `\` before the variable: `\$foo` or `\${foo}`, 343 for example, will translate to `$foo` and `${foo}` literals respectively. 344 345 Example (parsed representation is displayed after the `#`): 346 347 FROM busybox 348 ENV foo /bar 349 WORKDIR ${foo} # WORKDIR /bar 350 ADD . $foo # ADD . /bar 351 COPY \$foo /quux # COPY $foo /quux 352 353 Environment variables are supported by the following list of instructions in 354 the `Dockerfile`: 355 356 * `ADD` 357 * `COPY` 358 * `ENV` 359 * `EXPOSE` 360 * `FROM` 361 * `LABEL` 362 * `STOPSIGNAL` 363 * `USER` 364 * `VOLUME` 365 * `WORKDIR` 366 367 as well as: 368 369 * `ONBUILD` (when combined with one of the supported instructions above) 370 371 > **Note**: 372 > prior to 1.4, `ONBUILD` instructions did **NOT** support environment 373 > variable, even when combined with any of the instructions listed above. 374 375 Environment variable substitution will use the same value for each variable 376 throughout the entire instruction. In other words, in this example: 377 378 ENV abc=hello 379 ENV abc=bye def=$abc 380 ENV ghi=$abc 381 382 will result in `def` having a value of `hello`, not `bye`. However, 383 `ghi` will have a value of `bye` because it is not part of the same instruction 384 that set `abc` to `bye`. 385 386 ## .dockerignore file 387 388 Before the docker CLI sends the context to the docker daemon, it looks 389 for a file named `.dockerignore` in the root directory of the context. 390 If this file exists, the CLI modifies the context to exclude files and 391 directories that match patterns in it. This helps to avoid 392 unnecessarily sending large or sensitive files and directories to the 393 daemon and potentially adding them to images using `ADD` or `COPY`. 394 395 The CLI interprets the `.dockerignore` file as a newline-separated 396 list of patterns similar to the file globs of Unix shells. For the 397 purposes of matching, the root of the context is considered to be both 398 the working and the root directory. For example, the patterns 399 `/foo/bar` and `foo/bar` both exclude a file or directory named `bar` 400 in the `foo` subdirectory of `PATH` or in the root of the git 401 repository located at `URL`. Neither excludes anything else. 402 403 If a line in `.dockerignore` file starts with `#` in column 1, then this line is 404 considered as a comment and is ignored before interpreted by the CLI. 405 406 Here is an example `.dockerignore` file: 407 408 ``` 409 # comment 410 */temp* 411 */*/temp* 412 temp? 413 ``` 414 415 This file causes the following build behavior: 416 417 | Rule | Behavior | 418 |:------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 419 | `# comment` | Ignored. | 420 | `*/temp*` | Exclude files and directories whose names start with `temp` in any immediate subdirectory of the root. For example, the plain file `/somedir/temporary.txt` is excluded, as is the directory `/somedir/temp`. | 421 | `*/*/temp*` | Exclude files and directories starting with `temp` from any subdirectory that is two levels below the root. For example, `/somedir/subdir/temporary.txt` is excluded. | 422 | `temp?` | Exclude files and directories in the root directory whose names are a one-character extension of `temp`. For example, `/tempa` and `/tempb` are excluded. | 423 424 425 Matching is done using Go's 426 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. A 427 preprocessing step removes leading and trailing whitespace and 428 eliminates `.` and `..` elements using Go's 429 [filepath.Clean](http://golang.org/pkg/path/filepath/#Clean). Lines 430 that are blank after preprocessing are ignored. 431 432 Beyond Go's filepath.Match rules, Docker also supports a special 433 wildcard string `**` that matches any number of directories (including 434 zero). For example, `**/*.go` will exclude all files that end with `.go` 435 that are found in all directories, including the root of the build context. 436 437 Lines starting with `!` (exclamation mark) can be used to make exceptions 438 to exclusions. The following is an example `.dockerignore` file that 439 uses this mechanism: 440 441 ``` 442 *.md 443 !README.md 444 ``` 445 446 All markdown files *except* `README.md` are excluded from the context. 447 448 The placement of `!` exception rules influences the behavior: the last 449 line of the `.dockerignore` that matches a particular file determines 450 whether it is included or excluded. Consider the following example: 451 452 ``` 453 *.md 454 !README*.md 455 README-secret.md 456 ``` 457 458 No markdown files are included in the context except README files other than 459 `README-secret.md`. 460 461 Now consider this example: 462 463 ``` 464 *.md 465 README-secret.md 466 !README*.md 467 ``` 468 469 All of the README files are included. The middle line has no effect because 470 `!README*.md` matches `README-secret.md` and comes last. 471 472 You can even use the `.dockerignore` file to exclude the `Dockerfile` 473 and `.dockerignore` files. These files are still sent to the daemon 474 because it needs them to do its job. But the `ADD` and `COPY` instructions 475 do not copy them to the image. 476 477 Finally, you may want to specify which files to include in the 478 context, rather than which to exclude. To achieve this, specify `*` as 479 the first pattern, followed by one or more `!` exception patterns. 480 481 **Note**: For historical reasons, the pattern `.` is ignored. 482 483 ## FROM 484 485 FROM <image> [AS <name>] 486 487 Or 488 489 FROM <image>[:<tag>] [AS <name>] 490 491 Or 492 493 FROM <image>[@<digest>] [AS <name>] 494 495 The `FROM` instruction initializes a new build stage and sets the 496 [*Base Image*](glossary.md#base-image) for subsequent instructions. As such, a 497 valid `Dockerfile` must start with a `FROM` instruction. The image can be 498 any valid image – it is especially easy to start by **pulling an image** from 499 the [*Public Repositories*](https://docs.docker.com/engine/tutorials/dockerrepos/). 500 501 - `ARG` is the only instruction that may precede `FROM` in the `Dockerfile`. 502 See [Understand how ARG and FROM interact](#understand-how-arg-and-from-interact). 503 504 - `FROM` can appear multiple times within a single `Dockerfile` to 505 create multiple images or use one build stage as a dependency for another. 506 Simply make a note of the last image ID output by the commit before each new 507 `FROM` instruction. Each `FROM` instruction clears any state created by previous 508 instructions. 509 510 - Optionally a name can be given to a new build stage by adding `AS name` to the 511 `FROM` instruction. The name can be used in subsequent `FROM` and 512 `COPY --from=<name|index>` instructions to refer to the image built in this stage. 513 514 - The `tag` or `digest` values are optional. If you omit either of them, the 515 builder assumes a `latest` tag by default. The builder returns an error if it 516 cannot find the `tag` value. 517 518 ### Understand how ARG and FROM interact 519 520 `FROM` instructions support variables that are declared by any `ARG` 521 instructions that occur before the first `FROM`. 522 523 ```Dockerfile 524 ARG CODE_VERSION=latest 525 FROM base:${CODE_VERSION} 526 CMD /code/run-app 527 528 FROM extras:${CODE_VERSION} 529 CMD /code/run-extras 530 ``` 531 532 An `ARG` declared before a `FROM` is outside of a build stage, so it 533 can't be used in any instruction after a `FROM`. To use the default value of 534 an `ARG` declared before the first `FROM` use an `ARG` instruction without 535 a value inside of a build stage: 536 537 ```Dockerfile 538 ARG VERSION=latest 539 FROM busybox:$VERSION 540 ARG VERSION 541 RUN echo $VERSION > image_version 542 ``` 543 544 ## RUN 545 546 RUN has 2 forms: 547 548 - `RUN <command>` (*shell* form, the command is run in a shell, which by 549 default is `/bin/sh -c` on Linux or `cmd /S /C` on Windows) 550 - `RUN ["executable", "param1", "param2"]` (*exec* form) 551 552 The `RUN` instruction will execute any commands in a new layer on top of the 553 current image and commit the results. The resulting committed image will be 554 used for the next step in the `Dockerfile`. 555 556 Layering `RUN` instructions and generating commits conforms to the core 557 concepts of Docker where commits are cheap and containers can be created from 558 any point in an image's history, much like source control. 559 560 The *exec* form makes it possible to avoid shell string munging, and to `RUN` 561 commands using a base image that does not contain the specified shell executable. 562 563 The default shell for the *shell* form can be changed using the `SHELL` 564 command. 565 566 In the *shell* form you can use a `\` (backslash) to continue a single 567 RUN instruction onto the next line. For example, consider these two lines: 568 569 ``` 570 RUN /bin/bash -c 'source $HOME/.bashrc; \ 571 echo $HOME' 572 ``` 573 Together they are equivalent to this single line: 574 575 ``` 576 RUN /bin/bash -c 'source $HOME/.bashrc; echo $HOME' 577 ``` 578 579 > **Note**: 580 > To use a different shell, other than '/bin/sh', use the *exec* form 581 > passing in the desired shell. For example, 582 > `RUN ["/bin/bash", "-c", "echo hello"]` 583 584 > **Note**: 585 > The *exec* form is parsed as a JSON array, which means that 586 > you must use double-quotes (") around words not single-quotes ('). 587 588 > **Note**: 589 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 590 > This means that normal shell processing does not happen. For example, 591 > `RUN [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 592 > If you want shell processing then either use the *shell* form or execute 593 > a shell directly, for example: `RUN [ "sh", "-c", "echo $HOME" ]`. 594 > When using the exec form and executing a shell directly, as in the case for 595 > the shell form, it is the shell that is doing the environment variable 596 > expansion, not docker. 597 > 598 > **Note**: 599 > In the *JSON* form, it is necessary to escape backslashes. This is 600 > particularly relevant on Windows where the backslash is the path separator. 601 > The following line would otherwise be treated as *shell* form due to not 602 > being valid JSON, and fail in an unexpected way: 603 > `RUN ["c:\windows\system32\tasklist.exe"]` 604 > The correct syntax for this example is: 605 > `RUN ["c:\\windows\\system32\\tasklist.exe"]` 606 607 The cache for `RUN` instructions isn't invalidated automatically during 608 the next build. The cache for an instruction like 609 `RUN apt-get dist-upgrade -y` will be reused during the next build. The 610 cache for `RUN` instructions can be invalidated by using the `--no-cache` 611 flag, for example `docker build --no-cache`. 612 613 See the [`Dockerfile` Best Practices 614 guide](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#/build-cache) for more information. 615 616 The cache for `RUN` instructions can be invalidated by `ADD` instructions. See 617 [below](#add) for details. 618 619 ### Known issues (RUN) 620 621 - [Issue 783](https://github.com/docker/docker/issues/783) is about file 622 permissions problems that can occur when using the AUFS file system. You 623 might notice it during an attempt to `rm` a file, for example. 624 625 For systems that have recent aufs version (i.e., `dirperm1` mount option can 626 be set), docker will attempt to fix the issue automatically by mounting 627 the layers with `dirperm1` option. More details on `dirperm1` option can be 628 found at [`aufs` man page](https://github.com/sfjro/aufs3-linux/tree/aufs3.18/Documentation/filesystems/aufs) 629 630 If your system doesn't have support for `dirperm1`, the issue describes a workaround. 631 632 ## CMD 633 634 The `CMD` instruction has three forms: 635 636 - `CMD ["executable","param1","param2"]` (*exec* form, this is the preferred form) 637 - `CMD ["param1","param2"]` (as *default parameters to ENTRYPOINT*) 638 - `CMD command param1 param2` (*shell* form) 639 640 There can only be one `CMD` instruction in a `Dockerfile`. If you list more than one `CMD` 641 then only the last `CMD` will take effect. 642 643 **The main purpose of a `CMD` is to provide defaults for an executing 644 container.** These defaults can include an executable, or they can omit 645 the executable, in which case you must specify an `ENTRYPOINT` 646 instruction as well. 647 648 > **Note**: 649 > If `CMD` is used to provide default arguments for the `ENTRYPOINT` 650 > instruction, both the `CMD` and `ENTRYPOINT` instructions should be specified 651 > with the JSON array format. 652 653 > **Note**: 654 > The *exec* form is parsed as a JSON array, which means that 655 > you must use double-quotes (") around words not single-quotes ('). 656 657 > **Note**: 658 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 659 > This means that normal shell processing does not happen. For example, 660 > `CMD [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 661 > If you want shell processing then either use the *shell* form or execute 662 > a shell directly, for example: `CMD [ "sh", "-c", "echo $HOME" ]`. 663 > When using the exec form and executing a shell directly, as in the case for 664 > the shell form, it is the shell that is doing the environment variable 665 > expansion, not docker. 666 667 When used in the shell or exec formats, the `CMD` instruction sets the command 668 to be executed when running the image. 669 670 If you use the *shell* form of the `CMD`, then the `<command>` will execute in 671 `/bin/sh -c`: 672 673 FROM ubuntu 674 CMD echo "This is a test." | wc - 675 676 If you want to **run your** `<command>` **without a shell** then you must 677 express the command as a JSON array and give the full path to the executable. 678 **This array form is the preferred format of `CMD`.** Any additional parameters 679 must be individually expressed as strings in the array: 680 681 FROM ubuntu 682 CMD ["/usr/bin/wc","--help"] 683 684 If you would like your container to run the same executable every time, then 685 you should consider using `ENTRYPOINT` in combination with `CMD`. See 686 [*ENTRYPOINT*](#entrypoint). 687 688 If the user specifies arguments to `docker run` then they will override the 689 default specified in `CMD`. 690 691 > **Note**: 692 > Don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits 693 > the result; `CMD` does not execute anything at build time, but specifies 694 > the intended command for the image. 695 696 ## LABEL 697 698 LABEL <key>=<value> <key>=<value> <key>=<value> ... 699 700 The `LABEL` instruction adds metadata to an image. A `LABEL` is a 701 key-value pair. To include spaces within a `LABEL` value, use quotes and 702 backslashes as you would in command-line parsing. A few usage examples: 703 704 LABEL "com.example.vendor"="ACME Incorporated" 705 LABEL com.example.label-with-value="foo" 706 LABEL version="1.0" 707 LABEL description="This text illustrates \ 708 that label-values can span multiple lines." 709 710 An image can have more than one label. You can specify multiple labels on a 711 single line. Prior to Docker 1.10, this decreased the size of the final image, 712 but this is no longer the case. You may still choose to specify multiple labels 713 in a single instruction, in one of the following two ways: 714 715 ```none 716 LABEL multi.label1="value1" multi.label2="value2" other="value3" 717 ``` 718 719 ```none 720 LABEL multi.label1="value1" \ 721 multi.label2="value2" \ 722 other="value3" 723 ``` 724 725 Labels included in base or parent images (images in the `FROM` line) are 726 inherited by your image. If a label already exists but with a different value, 727 the most-recently-applied value overrides any previously-set value. 728 729 To view an image's labels, use the `docker inspect` command. 730 731 "Labels": { 732 "com.example.vendor": "ACME Incorporated" 733 "com.example.label-with-value": "foo", 734 "version": "1.0", 735 "description": "This text illustrates that label-values can span multiple lines.", 736 "multi.label1": "value1", 737 "multi.label2": "value2", 738 "other": "value3" 739 }, 740 741 ## MAINTAINER (deprecated) 742 743 MAINTAINER <name> 744 745 The `MAINTAINER` instruction sets the *Author* field of the generated images. 746 The `LABEL` instruction is a much more flexible version of this and you should use 747 it instead, as it enables setting any metadata you require, and can be viewed 748 easily, for example with `docker inspect`. To set a label corresponding to the 749 `MAINTAINER` field you could use: 750 751 LABEL maintainer="SvenDowideit@home.org.au" 752 753 This will then be visible from `docker inspect` with the other labels. 754 755 ## EXPOSE 756 757 EXPOSE <port> [<port>/<protocol>...] 758 759 The `EXPOSE` instruction informs Docker that the container listens on the 760 specified network ports at runtime. You can specify whether the port listens on 761 TCP or UDP, and the default is TCP if the protocol is not specified. 762 763 The `EXPOSE` instruction does not actually publish the port. It functions as a 764 type of documentation between the person who builds the image and the person who 765 runs the container, about which ports are intended to be published. To actually 766 publish the port when running the container, use the `-p` flag on `docker run` 767 to publish and map one or more ports, or the `-P` flag to publish all exposed 768 ports and map them to high-order ports. 769 770 By default, `EXPOSE` assumes TCP. You can also specify UDP: 771 772 ```Dockerfile 773 EXPOSE 80/udp 774 ``` 775 776 To expose on both TCP and UDP, include two lines: 777 778 ```Dockerfile 779 EXPOSE 80/tcp 780 EXPOSE 80/udp 781 ``` 782 783 In this case, if you use `-P` with `docker run`, the port will be exposed once 784 for TCP and once for UDP. Remember that `-P` uses an ephemeral high-ordered host 785 port on the host, so the port will not be the same for TCP and UDP. 786 787 Regardless of the `EXPOSE` settings, you can override them at runtime by using 788 the `-p` flag. For example 789 790 ```bash 791 docker run -p 80:80/tcp -p 80:80/udp ... 792 ``` 793 794 To set up port redirection on the host system, see [using the -P 795 flag](run.md#expose-incoming-ports). The `docker network` command supports 796 creating networks for communication among containers without the need to 797 expose or publish specific ports, because the containers connected to the 798 network can communicate with each other over any port. For detailed information, 799 see the 800 [overview of this feature](https://docs.docker.com/engine/userguide/networking/)). 801 802 ## ENV 803 804 ENV <key> <value> 805 ENV <key>=<value> ... 806 807 The `ENV` instruction sets the environment variable `<key>` to the value 808 `<value>`. This value will be in the environment for all subsequent instructions 809 in the build stage and can be [replaced inline](#environment-replacement) in 810 many as well. 811 812 The `ENV` instruction has two forms. The first form, `ENV <key> <value>`, 813 will set a single variable to a value. The entire string after the first 814 space will be treated as the `<value>` - including whitespace characters. The 815 value will be interpreted for other environment variables, so quote characters 816 will be removed if they are not escaped. 817 818 The second form, `ENV <key>=<value> ...`, allows for multiple variables to 819 be set at one time. Notice that the second form uses the equals sign (=) 820 in the syntax, while the first form does not. Like command line parsing, 821 quotes and backslashes can be used to include spaces within values. 822 823 For example: 824 825 ENV myName="John Doe" myDog=Rex\ The\ Dog \ 826 myCat=fluffy 827 828 and 829 830 ENV myName John Doe 831 ENV myDog Rex The Dog 832 ENV myCat fluffy 833 834 will yield the same net results in the final image. 835 836 The environment variables set using `ENV` will persist when a container is run 837 from the resulting image. You can view the values using `docker inspect`, and 838 change them using `docker run --env <key>=<value>`. 839 840 > **Note**: 841 > Environment persistence can cause unexpected side effects. For example, 842 > setting `ENV DEBIAN_FRONTEND noninteractive` may confuse apt-get 843 > users on a Debian-based image. To set a value for a single command, use 844 > `RUN <key>=<value> <command>`. 845 846 ## ADD 847 848 ADD has two forms: 849 850 - `ADD [--chown=<user>:<group>] <src>... <dest>` 851 - `ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]` (this form is required for paths containing 852 whitespace) 853 854 > **Note**: 855 > The `--chown` feature is only supported on Dockerfiles used to build Linux containers, 856 > and will not work on Windows containers. Since user and group ownership concepts do 857 > not translate between Linux and Windows, the use of `/etc/passwd` and `/etc/group` for 858 > translating user and group names to IDs restricts this feature to only be viable 859 > for Linux OS-based containers. 860 861 The `ADD` instruction copies new files, directories or remote file URLs from `<src>` 862 and adds them to the filesystem of the image at the path `<dest>`. 863 864 Multiple `<src>` resources may be specified but if they are files or 865 directories, their paths are interpreted as relative to the source of 866 the context of the build. 867 868 Each `<src>` may contain wildcards and matching will be done using Go's 869 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 870 871 ADD hom* /mydir/ # adds all files starting with "hom" 872 ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 873 874 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 875 the source will be copied inside the destination container. 876 877 ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 878 ADD test /absoluteDir/ # adds "test" to /absoluteDir/ 879 880 When adding files or directories that contain special characters (such as `[` 881 and `]`), you need to escape those paths following the Golang rules to prevent 882 them from being treated as a matching pattern. For example, to add a file 883 named `arr[0].txt`, use the following; 884 885 ADD arr[[]0].txt /mydir/ # copy a file named "arr[0].txt" to /mydir/ 886 887 888 All new files and directories are created with a UID and GID of 0, unless the 889 optional `--chown` flag specifies a given username, groupname, or UID/GID 890 combination to request specific ownership of the content added. The 891 format of the `--chown` flag allows for either username and groupname strings 892 or direct integer UID and GID in any combination. Providing a username without 893 groupname or a UID without GID will use the same numeric UID as the GID. If a 894 username or groupname is provided, the container's root filesystem 895 `/etc/passwd` and `/etc/group` files will be used to perform the translation 896 from name to integer UID or GID respectively. The following examples show 897 valid definitions for the `--chown` flag: 898 899 ADD --chown=55:mygroup files* /somedir/ 900 ADD --chown=bin files* /somedir/ 901 ADD --chown=1 files* /somedir/ 902 ADD --chown=10:11 files* /somedir/ 903 904 If the container root filesystem does not contain either `/etc/passwd` or 905 `/etc/group` files and either user or group names are used in the `--chown` 906 flag, the build will fail on the `ADD` operation. Using numeric IDs requires 907 no lookup and will not depend on container root filesystem content. 908 909 In the case where `<src>` is a remote file URL, the destination will 910 have permissions of 600. If the remote file being retrieved has an HTTP 911 `Last-Modified` header, the timestamp from that header will be used 912 to set the `mtime` on the destination file. However, like any other file 913 processed during an `ADD`, `mtime` will not be included in the determination 914 of whether or not the file has changed and the cache should be updated. 915 916 > **Note**: 917 > If you build by passing a `Dockerfile` through STDIN (`docker 918 > build - < somefile`), there is no build context, so the `Dockerfile` 919 > can only contain a URL based `ADD` instruction. You can also pass a 920 > compressed archive through STDIN: (`docker build - < archive.tar.gz`), 921 > the `Dockerfile` at the root of the archive and the rest of the 922 > archive will be used as the context of the build. 923 924 > **Note**: 925 > If your URL files are protected using authentication, you 926 > will need to use `RUN wget`, `RUN curl` or use another tool from 927 > within the container as the `ADD` instruction does not support 928 > authentication. 929 930 > **Note**: 931 > The first encountered `ADD` instruction will invalidate the cache for all 932 > following instructions from the Dockerfile if the contents of `<src>` have 933 > changed. This includes invalidating the cache for `RUN` instructions. 934 > See the [`Dockerfile` Best Practices 935 guide](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#/build-cache) for more information. 936 937 938 `ADD` obeys the following rules: 939 940 - The `<src>` path must be inside the *context* of the build; 941 you cannot `ADD ../something /something`, because the first step of a 942 `docker build` is to send the context directory (and subdirectories) to the 943 docker daemon. 944 945 - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a 946 file is downloaded from the URL and copied to `<dest>`. 947 948 - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the 949 filename is inferred from the URL and the file is downloaded to 950 `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would 951 create the file `/foobar`. The URL must have a nontrivial path so that an 952 appropriate filename can be discovered in this case (`http://example.com` 953 will not work). 954 955 - If `<src>` is a directory, the entire contents of the directory are copied, 956 including filesystem metadata. 957 958 > **Note**: 959 > The directory itself is not copied, just its contents. 960 961 - If `<src>` is a *local* tar archive in a recognized compression format 962 (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources 963 from *remote* URLs are **not** decompressed. When a directory is copied or 964 unpacked, it has the same behavior as `tar -x`, the result is the union of: 965 966 1. Whatever existed at the destination path and 967 2. The contents of the source tree, with conflicts resolved in favor 968 of "2." on a file-by-file basis. 969 970 > **Note**: 971 > Whether a file is identified as a recognized compression format or not 972 > is done solely based on the contents of the file, not the name of the file. 973 > For example, if an empty file happens to end with `.tar.gz` this will not 974 > be recognized as a compressed file and **will not** generate any kind of 975 > decompression error message, rather the file will simply be copied to the 976 > destination. 977 978 - If `<src>` is any other kind of file, it is copied individually along with 979 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 980 will be considered a directory and the contents of `<src>` will be written 981 at `<dest>/base(<src>)`. 982 983 - If multiple `<src>` resources are specified, either directly or due to the 984 use of a wildcard, then `<dest>` must be a directory, and it must end with 985 a slash `/`. 986 987 - If `<dest>` does not end with a trailing slash, it will be considered a 988 regular file and the contents of `<src>` will be written at `<dest>`. 989 990 - If `<dest>` doesn't exist, it is created along with all missing directories 991 in its path. 992 993 ## COPY 994 995 COPY has two forms: 996 997 - `COPY [--chown=<user>:<group>] <src>... <dest>` 998 - `COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]` (this form is required for paths containing 999 whitespace) 1000 1001 > **Note**: 1002 > The `--chown` feature is only supported on Dockerfiles used to build Linux containers, 1003 > and will not work on Windows containers. Since user and group ownership concepts do 1004 > not translate between Linux and Windows, the use of `/etc/passwd` and `/etc/group` for 1005 > translating user and group names to IDs restricts this feature to only be viable for 1006 > Linux OS-based containers. 1007 1008 The `COPY` instruction copies new files or directories from `<src>` 1009 and adds them to the filesystem of the container at the path `<dest>`. 1010 1011 Multiple `<src>` resources may be specified but the paths of files and 1012 directories will be interpreted as relative to the source of the context 1013 of the build. 1014 1015 Each `<src>` may contain wildcards and matching will be done using Go's 1016 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 1017 1018 COPY hom* /mydir/ # adds all files starting with "hom" 1019 COPY hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 1020 1021 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 1022 the source will be copied inside the destination container. 1023 1024 COPY test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 1025 COPY test /absoluteDir/ # adds "test" to /absoluteDir/ 1026 1027 1028 When copying files or directories that contain special characters (such as `[` 1029 and `]`), you need to escape those paths following the Golang rules to prevent 1030 them from being treated as a matching pattern. For example, to copy a file 1031 named `arr[0].txt`, use the following; 1032 1033 COPY arr[[]0].txt /mydir/ # copy a file named "arr[0].txt" to /mydir/ 1034 1035 All new files and directories are created with a UID and GID of 0, unless the 1036 optional `--chown` flag specifies a given username, groupname, or UID/GID 1037 combination to request specific ownership of the copied content. The 1038 format of the `--chown` flag allows for either username and groupname strings 1039 or direct integer UID and GID in any combination. Providing a username without 1040 groupname or a UID without GID will use the same numeric UID as the GID. If a 1041 username or groupname is provided, the container's root filesystem 1042 `/etc/passwd` and `/etc/group` files will be used to perform the translation 1043 from name to integer UID or GID respectively. The following examples show 1044 valid definitions for the `--chown` flag: 1045 1046 COPY --chown=55:mygroup files* /somedir/ 1047 COPY --chown=bin files* /somedir/ 1048 COPY --chown=1 files* /somedir/ 1049 COPY --chown=10:11 files* /somedir/ 1050 1051 If the container root filesystem does not contain either `/etc/passwd` or 1052 `/etc/group` files and either user or group names are used in the `--chown` 1053 flag, the build will fail on the `COPY` operation. Using numeric IDs requires 1054 no lookup and will not depend on container root filesystem content. 1055 1056 > **Note**: 1057 > If you build using STDIN (`docker build - < somefile`), there is no 1058 > build context, so `COPY` can't be used. 1059 1060 Optionally `COPY` accepts a flag `--from=<name|index>` that can be used to set 1061 the source location to a previous build stage (created with `FROM .. AS <name>`) 1062 that will be used instead of a build context sent by the user. The flag also 1063 accepts a numeric index assigned for all previous build stages started with 1064 `FROM` instruction. In case a build stage with a specified name can't be found an 1065 image with the same name is attempted to be used instead. 1066 1067 `COPY` obeys the following rules: 1068 1069 - The `<src>` path must be inside the *context* of the build; 1070 you cannot `COPY ../something /something`, because the first step of a 1071 `docker build` is to send the context directory (and subdirectories) to the 1072 docker daemon. 1073 1074 - If `<src>` is a directory, the entire contents of the directory are copied, 1075 including filesystem metadata. 1076 1077 > **Note**: 1078 > The directory itself is not copied, just its contents. 1079 1080 - If `<src>` is any other kind of file, it is copied individually along with 1081 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 1082 will be considered a directory and the contents of `<src>` will be written 1083 at `<dest>/base(<src>)`. 1084 1085 - If multiple `<src>` resources are specified, either directly or due to the 1086 use of a wildcard, then `<dest>` must be a directory, and it must end with 1087 a slash `/`. 1088 1089 - If `<dest>` does not end with a trailing slash, it will be considered a 1090 regular file and the contents of `<src>` will be written at `<dest>`. 1091 1092 - If `<dest>` doesn't exist, it is created along with all missing directories 1093 in its path. 1094 1095 ## ENTRYPOINT 1096 1097 ENTRYPOINT has two forms: 1098 1099 - `ENTRYPOINT ["executable", "param1", "param2"]` 1100 (*exec* form, preferred) 1101 - `ENTRYPOINT command param1 param2` 1102 (*shell* form) 1103 1104 An `ENTRYPOINT` allows you to configure a container that will run as an executable. 1105 1106 For example, the following will start nginx with its default content, listening 1107 on port 80: 1108 1109 docker run -i -t --rm -p 80:80 nginx 1110 1111 Command line arguments to `docker run <image>` will be appended after all 1112 elements in an *exec* form `ENTRYPOINT`, and will override all elements specified 1113 using `CMD`. 1114 This allows arguments to be passed to the entry point, i.e., `docker run <image> -d` 1115 will pass the `-d` argument to the entry point. 1116 You can override the `ENTRYPOINT` instruction using the `docker run --entrypoint` 1117 flag. 1118 1119 The *shell* form prevents any `CMD` or `run` command line arguments from being 1120 used, but has the disadvantage that your `ENTRYPOINT` will be started as a 1121 subcommand of `/bin/sh -c`, which does not pass signals. 1122 This means that the executable will not be the container's `PID 1` - and 1123 will _not_ receive Unix signals - so your executable will not receive a 1124 `SIGTERM` from `docker stop <container>`. 1125 1126 Only the last `ENTRYPOINT` instruction in the `Dockerfile` will have an effect. 1127 1128 ### Exec form ENTRYPOINT example 1129 1130 You can use the *exec* form of `ENTRYPOINT` to set fairly stable default commands 1131 and arguments and then use either form of `CMD` to set additional defaults that 1132 are more likely to be changed. 1133 1134 FROM ubuntu 1135 ENTRYPOINT ["top", "-b"] 1136 CMD ["-c"] 1137 1138 When you run the container, you can see that `top` is the only process: 1139 1140 $ docker run -it --rm --name test top -H 1141 top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05 1142 Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie 1143 %Cpu(s): 0.1 us, 0.1 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st 1144 KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers 1145 KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem 1146 1147 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1148 1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top 1149 1150 To examine the result further, you can use `docker exec`: 1151 1152 $ docker exec -it test ps aux 1153 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1154 root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H 1155 root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux 1156 1157 And you can gracefully request `top` to shut down using `docker stop test`. 1158 1159 The following `Dockerfile` shows using the `ENTRYPOINT` to run Apache in the 1160 foreground (i.e., as `PID 1`): 1161 1162 ``` 1163 FROM debian:stable 1164 RUN apt-get update && apt-get install -y --force-yes apache2 1165 EXPOSE 80 443 1166 VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"] 1167 ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] 1168 ``` 1169 1170 If you need to write a starter script for a single executable, you can ensure that 1171 the final executable receives the Unix signals by using `exec` and `gosu` 1172 commands: 1173 1174 ```bash 1175 #!/usr/bin/env bash 1176 set -e 1177 1178 if [ "$1" = 'postgres' ]; then 1179 chown -R postgres "$PGDATA" 1180 1181 if [ -z "$(ls -A "$PGDATA")" ]; then 1182 gosu postgres initdb 1183 fi 1184 1185 exec gosu postgres "$@" 1186 fi 1187 1188 exec "$@" 1189 ``` 1190 1191 Lastly, if you need to do some extra cleanup (or communicate with other containers) 1192 on shutdown, or are co-ordinating more than one executable, you may need to ensure 1193 that the `ENTRYPOINT` script receives the Unix signals, passes them on, and then 1194 does some more work: 1195 1196 ``` 1197 #!/bin/sh 1198 # Note: I've written this using sh so it works in the busybox container too 1199 1200 # USE the trap if you need to also do manual cleanup after the service is stopped, 1201 # or need to start multiple services in the one container 1202 trap "echo TRAPed signal" HUP INT QUIT TERM 1203 1204 # start service in background here 1205 /usr/sbin/apachectl start 1206 1207 echo "[hit enter key to exit] or run 'docker stop <container>'" 1208 read 1209 1210 # stop service and clean up here 1211 echo "stopping apache" 1212 /usr/sbin/apachectl stop 1213 1214 echo "exited $0" 1215 ``` 1216 1217 If you run this image with `docker run -it --rm -p 80:80 --name test apache`, 1218 you can then examine the container's processes with `docker exec`, or `docker top`, 1219 and then ask the script to stop Apache: 1220 1221 ```bash 1222 $ docker exec -it test ps aux 1223 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1224 root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123 cmd cmd2 1225 root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start 1226 www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 1227 www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 1228 root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux 1229 $ docker top test 1230 PID USER COMMAND 1231 10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2 1232 10054 root /usr/sbin/apache2 -k start 1233 10055 33 /usr/sbin/apache2 -k start 1234 10056 33 /usr/sbin/apache2 -k start 1235 $ /usr/bin/time docker stop test 1236 test 1237 real 0m 0.27s 1238 user 0m 0.03s 1239 sys 0m 0.03s 1240 ``` 1241 1242 > **Note:** you can override the `ENTRYPOINT` setting using `--entrypoint`, 1243 > but this can only set the binary to *exec* (no `sh -c` will be used). 1244 1245 > **Note**: 1246 > The *exec* form is parsed as a JSON array, which means that 1247 > you must use double-quotes (") around words not single-quotes ('). 1248 1249 > **Note**: 1250 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 1251 > This means that normal shell processing does not happen. For example, 1252 > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 1253 > If you want shell processing then either use the *shell* form or execute 1254 > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo $HOME" ]`. 1255 > When using the exec form and executing a shell directly, as in the case for 1256 > the shell form, it is the shell that is doing the environment variable 1257 > expansion, not docker. 1258 1259 ### Shell form ENTRYPOINT example 1260 1261 You can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`. 1262 This form will use shell processing to substitute shell environment variables, 1263 and will ignore any `CMD` or `docker run` command line arguments. 1264 To ensure that `docker stop` will signal any long running `ENTRYPOINT` executable 1265 correctly, you need to remember to start it with `exec`: 1266 1267 FROM ubuntu 1268 ENTRYPOINT exec top -b 1269 1270 When you run this image, you'll see the single `PID 1` process: 1271 1272 $ docker run -it --rm --name test top 1273 Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached 1274 CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq 1275 Load average: 0.08 0.03 0.05 2/98 6 1276 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1277 1 0 root R 3164 0% 0% top -b 1278 1279 Which will exit cleanly on `docker stop`: 1280 1281 $ /usr/bin/time docker stop test 1282 test 1283 real 0m 0.20s 1284 user 0m 0.02s 1285 sys 0m 0.04s 1286 1287 If you forget to add `exec` to the beginning of your `ENTRYPOINT`: 1288 1289 FROM ubuntu 1290 ENTRYPOINT top -b 1291 CMD --ignored-param1 1292 1293 You can then run it (giving it a name for the next step): 1294 1295 $ docker run -it --name test top --ignored-param2 1296 Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached 1297 CPU: 9% usr 2% sys 0% nic 88% idle 0% io 0% irq 0% sirq 1298 Load average: 0.01 0.02 0.05 2/101 7 1299 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1300 1 0 root S 3168 0% 0% /bin/sh -c top -b cmd cmd2 1301 7 1 root R 3164 0% 0% top -b 1302 1303 You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. 1304 1305 If you then run `docker stop test`, the container will not exit cleanly - the 1306 `stop` command will be forced to send a `SIGKILL` after the timeout: 1307 1308 $ docker exec -it test ps aux 1309 PID USER COMMAND 1310 1 root /bin/sh -c top -b cmd cmd2 1311 7 root top -b 1312 8 root ps aux 1313 $ /usr/bin/time docker stop test 1314 test 1315 real 0m 10.19s 1316 user 0m 0.04s 1317 sys 0m 0.03s 1318 1319 ### Understand how CMD and ENTRYPOINT interact 1320 1321 Both `CMD` and `ENTRYPOINT` instructions define what command gets executed when running a container. 1322 There are few rules that describe their co-operation. 1323 1324 1. Dockerfile should specify at least one of `CMD` or `ENTRYPOINT` commands. 1325 1326 2. `ENTRYPOINT` should be defined when using the container as an executable. 1327 1328 3. `CMD` should be used as a way of defining default arguments for an `ENTRYPOINT` command 1329 or for executing an ad-hoc command in a container. 1330 1331 4. `CMD` will be overridden when running the container with alternative arguments. 1332 1333 The table below shows what command is executed for different `ENTRYPOINT` / `CMD` combinations: 1334 1335 | | No ENTRYPOINT | ENTRYPOINT exec_entry p1_entry | ENTRYPOINT ["exec_entry", "p1_entry"] | 1336 |:-------------------------------|:---------------------------|:-------------------------------|:-----------------------------------------------| 1337 | **No CMD** | *error, not allowed* | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry | 1338 | **CMD ["exec_cmd", "p1_cmd"]** | exec_cmd p1_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry exec_cmd p1_cmd | 1339 | **CMD ["p1_cmd", "p2_cmd"]** | p1_cmd p2_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry p1_cmd p2_cmd | 1340 | **CMD exec_cmd p1_cmd** | /bin/sh -c exec_cmd p1_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry /bin/sh -c exec_cmd p1_cmd | 1341 1342 ## VOLUME 1343 1344 VOLUME ["/data"] 1345 1346 The `VOLUME` instruction creates a mount point with the specified name 1347 and marks it as holding externally mounted volumes from native host or other 1348 containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain 1349 string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log 1350 /var/db`. For more information/examples and mounting instructions via the 1351 Docker client, refer to 1352 [*Share Directories via Volumes*](https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-host-directory-as-a-data-volume) 1353 documentation. 1354 1355 The `docker run` command initializes the newly created volume with any data 1356 that exists at the specified location within the base image. For example, 1357 consider the following Dockerfile snippet: 1358 1359 FROM ubuntu 1360 RUN mkdir /myvol 1361 RUN echo "hello world" > /myvol/greeting 1362 VOLUME /myvol 1363 1364 This Dockerfile results in an image that causes `docker run` to 1365 create a new mount point at `/myvol` and copy the `greeting` file 1366 into the newly created volume. 1367 1368 ### Notes about specifying volumes 1369 1370 Keep the following things in mind about volumes in the `Dockerfile`. 1371 1372 - **Volumes on Windows-based containers**: When using Windows-based containers, 1373 the destination of a volume inside the container must be one of: 1374 1375 - a non-existing or empty directory 1376 - a drive other than `C:` 1377 1378 - **Changing the volume from within the Dockerfile**: If any build steps change the 1379 data within the volume after it has been declared, those changes will be discarded. 1380 1381 - **JSON formatting**: The list is parsed as a JSON array. 1382 You must enclose words with double quotes (`"`) rather than single quotes (`'`). 1383 1384 - **The host directory is declared at container run-time**: The host directory 1385 (the mountpoint) is, by its nature, host-dependent. This is to preserve image 1386 portability, since a given host directory can't be guaranteed to be available 1387 on all hosts. For this reason, you can't mount a host directory from 1388 within the Dockerfile. The `VOLUME` instruction does not support specifying a `host-dir` 1389 parameter. You must specify the mountpoint when you create or run the container. 1390 1391 ## USER 1392 1393 USER <user>[:<group>] 1394 or 1395 USER <UID>[:<GID>] 1396 1397 The `USER` instruction sets the user name (or UID) and optionally the user 1398 group (or GID) to use when running the image and for any `RUN`, `CMD` and 1399 `ENTRYPOINT` instructions that follow it in the `Dockerfile`. 1400 1401 > **Warning**: 1402 > When the user doesn't have a primary group then the image (or the next 1403 > instructions) will be run with the `root` group. 1404 1405 > On Windows, the user must be created first if it's not a built-in account. 1406 > This can be done with the `net user` command called as part of a Dockerfile. 1407 1408 ```Dockerfile 1409 FROM microsoft/windowsservercore 1410 # Create Windows user in the container 1411 RUN net user /add patrick 1412 # Set it for subsequent commands 1413 USER patrick 1414 ``` 1415 1416 1417 ## WORKDIR 1418 1419 WORKDIR /path/to/workdir 1420 1421 The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, 1422 `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. 1423 If the `WORKDIR` doesn't exist, it will be created even if it's not used in any 1424 subsequent `Dockerfile` instruction. 1425 1426 The `WORKDIR` instruction can be used multiple times in a `Dockerfile`. If a 1427 relative path is provided, it will be relative to the path of the previous 1428 `WORKDIR` instruction. For example: 1429 1430 WORKDIR /a 1431 WORKDIR b 1432 WORKDIR c 1433 RUN pwd 1434 1435 The output of the final `pwd` command in this `Dockerfile` would be 1436 `/a/b/c`. 1437 1438 The `WORKDIR` instruction can resolve environment variables previously set using 1439 `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. 1440 For example: 1441 1442 ENV DIRPATH /path 1443 WORKDIR $DIRPATH/$DIRNAME 1444 RUN pwd 1445 1446 The output of the final `pwd` command in this `Dockerfile` would be 1447 `/path/$DIRNAME` 1448 1449 ## ARG 1450 1451 ARG <name>[=<default value>] 1452 1453 The `ARG` instruction defines a variable that users can pass at build-time to 1454 the builder with the `docker build` command using the `--build-arg <varname>=<value>` 1455 flag. If a user specifies a build argument that was not 1456 defined in the Dockerfile, the build outputs a warning. 1457 1458 ``` 1459 [Warning] One or more build-args [foo] were not consumed. 1460 ``` 1461 1462 A Dockerfile may include one or more `ARG` instructions. For example, 1463 the following is a valid Dockerfile: 1464 1465 ``` 1466 FROM busybox 1467 ARG user1 1468 ARG buildno 1469 ... 1470 ``` 1471 1472 > **Warning:** It is not recommended to use build-time variables for 1473 > passing secrets like github keys, user credentials etc. Build-time variable 1474 > values are visible to any user of the image with the `docker history` command. 1475 1476 ### Default values 1477 1478 An `ARG` instruction can optionally include a default value: 1479 1480 ``` 1481 FROM busybox 1482 ARG user1=someuser 1483 ARG buildno=1 1484 ... 1485 ``` 1486 1487 If an `ARG` instruction has a default value and if there is no value passed 1488 at build-time, the builder uses the default. 1489 1490 ### Scope 1491 1492 An `ARG` variable definition comes into effect from the line on which it is 1493 defined in the `Dockerfile` not from the argument's use on the command-line or 1494 elsewhere. For example, consider this Dockerfile: 1495 1496 ``` 1497 1 FROM busybox 1498 2 USER ${user:-some_user} 1499 3 ARG user 1500 4 USER $user 1501 ... 1502 ``` 1503 A user builds this file by calling: 1504 1505 ``` 1506 $ docker build --build-arg user=what_user . 1507 ``` 1508 1509 The `USER` at line 2 evaluates to `some_user` as the `user` variable is defined on the 1510 subsequent line 3. The `USER` at line 4 evaluates to `what_user` as `user` is 1511 defined and the `what_user` value was passed on the command line. Prior to its definition by an 1512 `ARG` instruction, any use of a variable results in an empty string. 1513 1514 An `ARG` instruction goes out of scope at the end of the build 1515 stage where it was defined. To use an arg in multiple stages, each stage must 1516 include the `ARG` instruction. 1517 1518 ``` 1519 FROM busybox 1520 ARG SETTINGS 1521 RUN ./run/setup $SETTINGS 1522 1523 FROM busybox 1524 ARG SETTINGS 1525 RUN ./run/other $SETTINGS 1526 ``` 1527 1528 ### Using ARG variables 1529 1530 You can use an `ARG` or an `ENV` instruction to specify variables that are 1531 available to the `RUN` instruction. Environment variables defined using the 1532 `ENV` instruction always override an `ARG` instruction of the same name. Consider 1533 this Dockerfile with an `ENV` and `ARG` instruction. 1534 1535 ``` 1536 1 FROM ubuntu 1537 2 ARG CONT_IMG_VER 1538 3 ENV CONT_IMG_VER v1.0.0 1539 4 RUN echo $CONT_IMG_VER 1540 ``` 1541 Then, assume this image is built with this command: 1542 1543 ``` 1544 $ docker build --build-arg CONT_IMG_VER=v2.0.1 . 1545 ``` 1546 1547 In this case, the `RUN` instruction uses `v1.0.0` instead of the `ARG` setting 1548 passed by the user:`v2.0.1` This behavior is similar to a shell 1549 script where a locally scoped variable overrides the variables passed as 1550 arguments or inherited from environment, from its point of definition. 1551 1552 Using the example above but a different `ENV` specification you can create more 1553 useful interactions between `ARG` and `ENV` instructions: 1554 1555 ``` 1556 1 FROM ubuntu 1557 2 ARG CONT_IMG_VER 1558 3 ENV CONT_IMG_VER ${CONT_IMG_VER:-v1.0.0} 1559 4 RUN echo $CONT_IMG_VER 1560 ``` 1561 1562 Unlike an `ARG` instruction, `ENV` values are always persisted in the built 1563 image. Consider a docker build without the `--build-arg` flag: 1564 1565 ``` 1566 $ docker build . 1567 ``` 1568 1569 Using this Dockerfile example, `CONT_IMG_VER` is still persisted in the image but 1570 its value would be `v1.0.0` as it is the default set in line 3 by the `ENV` instruction. 1571 1572 The variable expansion technique in this example allows you to pass arguments 1573 from the command line and persist them in the final image by leveraging the 1574 `ENV` instruction. Variable expansion is only supported for [a limited set of 1575 Dockerfile instructions.](#environment-replacement) 1576 1577 ### Predefined ARGs 1578 1579 Docker has a set of predefined `ARG` variables that you can use without a 1580 corresponding `ARG` instruction in the Dockerfile. 1581 1582 * `HTTP_PROXY` 1583 * `http_proxy` 1584 * `HTTPS_PROXY` 1585 * `https_proxy` 1586 * `FTP_PROXY` 1587 * `ftp_proxy` 1588 * `NO_PROXY` 1589 * `no_proxy` 1590 1591 To use these, simply pass them on the command line using the flag: 1592 1593 ``` 1594 --build-arg <varname>=<value> 1595 ``` 1596 1597 By default, these pre-defined variables are excluded from the output of 1598 `docker history`. Excluding them reduces the risk of accidentally leaking 1599 sensitive authentication information in an `HTTP_PROXY` variable. 1600 1601 For example, consider building the following Dockerfile using 1602 `--build-arg HTTP_PROXY=http://user:pass@proxy.lon.example.com` 1603 1604 ``` Dockerfile 1605 FROM ubuntu 1606 RUN echo "Hello World" 1607 ``` 1608 1609 In this case, the value of the `HTTP_PROXY` variable is not available in the 1610 `docker history` and is not cached. If you were to change location, and your 1611 proxy server changed to `http://user:pass@proxy.sfo.example.com`, a subsequent 1612 build does not result in a cache miss. 1613 1614 If you need to override this behaviour then you may do so by adding an `ARG` 1615 statement in the Dockerfile as follows: 1616 1617 ``` Dockerfile 1618 FROM ubuntu 1619 ARG HTTP_PROXY 1620 RUN echo "Hello World" 1621 ``` 1622 1623 When building this Dockerfile, the `HTTP_PROXY` is preserved in the 1624 `docker history`, and changing its value invalidates the build cache. 1625 1626 ### Impact on build caching 1627 1628 `ARG` variables are not persisted into the built image as `ENV` variables are. 1629 However, `ARG` variables do impact the build cache in similar ways. If a 1630 Dockerfile defines an `ARG` variable whose value is different from a previous 1631 build, then a "cache miss" occurs upon its first usage, not its definition. In 1632 particular, all `RUN` instructions following an `ARG` instruction use the `ARG` 1633 variable implicitly (as an environment variable), thus can cause a cache miss. 1634 All predefined `ARG` variables are exempt from caching unless there is a 1635 matching `ARG` statement in the `Dockerfile`. 1636 1637 For example, consider these two Dockerfile: 1638 1639 ``` 1640 1 FROM ubuntu 1641 2 ARG CONT_IMG_VER 1642 3 RUN echo $CONT_IMG_VER 1643 ``` 1644 1645 ``` 1646 1 FROM ubuntu 1647 2 ARG CONT_IMG_VER 1648 3 RUN echo hello 1649 ``` 1650 1651 If you specify `--build-arg CONT_IMG_VER=<value>` on the command line, in both 1652 cases, the specification on line 2 does not cause a cache miss; line 3 does 1653 cause a cache miss.`ARG CONT_IMG_VER` causes the RUN line to be identified 1654 as the same as running `CONT_IMG_VER=<value>` echo hello, so if the `<value>` 1655 changes, we get a cache miss. 1656 1657 Consider another example under the same command line: 1658 1659 ``` 1660 1 FROM ubuntu 1661 2 ARG CONT_IMG_VER 1662 3 ENV CONT_IMG_VER $CONT_IMG_VER 1663 4 RUN echo $CONT_IMG_VER 1664 ``` 1665 In this example, the cache miss occurs on line 3. The miss happens because 1666 the variable's value in the `ENV` references the `ARG` variable and that 1667 variable is changed through the command line. In this example, the `ENV` 1668 command causes the image to include the value. 1669 1670 If an `ENV` instruction overrides an `ARG` instruction of the same name, like 1671 this Dockerfile: 1672 1673 ``` 1674 1 FROM ubuntu 1675 2 ARG CONT_IMG_VER 1676 3 ENV CONT_IMG_VER hello 1677 4 RUN echo $CONT_IMG_VER 1678 ``` 1679 1680 Line 3 does not cause a cache miss because the value of `CONT_IMG_VER` is a 1681 constant (`hello`). As a result, the environment variables and values used on 1682 the `RUN` (line 4) doesn't change between builds. 1683 1684 ## ONBUILD 1685 1686 ONBUILD [INSTRUCTION] 1687 1688 The `ONBUILD` instruction adds to the image a *trigger* instruction to 1689 be executed at a later time, when the image is used as the base for 1690 another build. The trigger will be executed in the context of the 1691 downstream build, as if it had been inserted immediately after the 1692 `FROM` instruction in the downstream `Dockerfile`. 1693 1694 Any build instruction can be registered as a trigger. 1695 1696 This is useful if you are building an image which will be used as a base 1697 to build other images, for example an application build environment or a 1698 daemon which may be customized with user-specific configuration. 1699 1700 For example, if your image is a reusable Python application builder, it 1701 will require application source code to be added in a particular 1702 directory, and it might require a build script to be called *after* 1703 that. You can't just call `ADD` and `RUN` now, because you don't yet 1704 have access to the application source code, and it will be different for 1705 each application build. You could simply provide application developers 1706 with a boilerplate `Dockerfile` to copy-paste into their application, but 1707 that is inefficient, error-prone and difficult to update because it 1708 mixes with application-specific code. 1709 1710 The solution is to use `ONBUILD` to register advance instructions to 1711 run later, during the next build stage. 1712 1713 Here's how it works: 1714 1715 1. When it encounters an `ONBUILD` instruction, the builder adds a 1716 trigger to the metadata of the image being built. The instruction 1717 does not otherwise affect the current build. 1718 2. At the end of the build, a list of all triggers is stored in the 1719 image manifest, under the key `OnBuild`. They can be inspected with 1720 the `docker inspect` command. 1721 3. Later the image may be used as a base for a new build, using the 1722 `FROM` instruction. As part of processing the `FROM` instruction, 1723 the downstream builder looks for `ONBUILD` triggers, and executes 1724 them in the same order they were registered. If any of the triggers 1725 fail, the `FROM` instruction is aborted which in turn causes the 1726 build to fail. If all triggers succeed, the `FROM` instruction 1727 completes and the build continues as usual. 1728 4. Triggers are cleared from the final image after being executed. In 1729 other words they are not inherited by "grand-children" builds. 1730 1731 For example you might add something like this: 1732 1733 [...] 1734 ONBUILD ADD . /app/src 1735 ONBUILD RUN /usr/local/bin/python-build --dir /app/src 1736 [...] 1737 1738 > **Warning**: Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. 1739 1740 > **Warning**: The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. 1741 1742 ## STOPSIGNAL 1743 1744 STOPSIGNAL signal 1745 1746 The `STOPSIGNAL` instruction sets the system call signal that will be sent to the container to exit. 1747 This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9, 1748 or a signal name in the format SIGNAME, for instance SIGKILL. 1749 1750 ## HEALTHCHECK 1751 1752 The `HEALTHCHECK` instruction has two forms: 1753 1754 * `HEALTHCHECK [OPTIONS] CMD command` (check container health by running a command inside the container) 1755 * `HEALTHCHECK NONE` (disable any healthcheck inherited from the base image) 1756 1757 The `HEALTHCHECK` instruction tells Docker how to test a container to check that 1758 it is still working. This can detect cases such as a web server that is stuck in 1759 an infinite loop and unable to handle new connections, even though the server 1760 process is still running. 1761 1762 When a container has a healthcheck specified, it has a _health status_ in 1763 addition to its normal status. This status is initially `starting`. Whenever a 1764 health check passes, it becomes `healthy` (whatever state it was previously in). 1765 After a certain number of consecutive failures, it becomes `unhealthy`. 1766 1767 The options that can appear before `CMD` are: 1768 1769 * `--interval=DURATION` (default: `30s`) 1770 * `--timeout=DURATION` (default: `30s`) 1771 * `--start-period=DURATION` (default: `0s`) 1772 * `--retries=N` (default: `3`) 1773 1774 The health check will first run **interval** seconds after the container is 1775 started, and then again **interval** seconds after each previous check completes. 1776 1777 If a single run of the check takes longer than **timeout** seconds then the check 1778 is considered to have failed. 1779 1780 It takes **retries** consecutive failures of the health check for the container 1781 to be considered `unhealthy`. 1782 1783 **start period** provides initialization time for containers that need time to bootstrap. 1784 Probe failure during that period will not be counted towards the maximum number of retries. 1785 However, if a health check succeeds during the start period, the container is considered 1786 started and all consecutive failures will be counted towards the maximum number of retries. 1787 1788 There can only be one `HEALTHCHECK` instruction in a Dockerfile. If you list 1789 more than one then only the last `HEALTHCHECK` will take effect. 1790 1791 The command after the `CMD` keyword can be either a shell command (e.g. `HEALTHCHECK 1792 CMD /bin/check-running`) or an _exec_ array (as with other Dockerfile commands; 1793 see e.g. `ENTRYPOINT` for details). 1794 1795 The command's exit status indicates the health status of the container. 1796 The possible values are: 1797 1798 - 0: success - the container is healthy and ready for use 1799 - 1: unhealthy - the container is not working correctly 1800 - 2: reserved - do not use this exit code 1801 1802 For example, to check every five minutes or so that a web-server is able to 1803 serve the site's main page within three seconds: 1804 1805 HEALTHCHECK --interval=5m --timeout=3s \ 1806 CMD curl -f http://localhost/ || exit 1 1807 1808 To help debug failing probes, any output text (UTF-8 encoded) that the command writes 1809 on stdout or stderr will be stored in the health status and can be queried with 1810 `docker inspect`. Such output should be kept short (only the first 4096 bytes 1811 are stored currently). 1812 1813 When the health status of a container changes, a `health_status` event is 1814 generated with the new status. 1815 1816 The `HEALTHCHECK` feature was added in Docker 1.12. 1817 1818 1819 ## SHELL 1820 1821 SHELL ["executable", "parameters"] 1822 1823 The `SHELL` instruction allows the default shell used for the *shell* form of 1824 commands to be overridden. The default shell on Linux is `["/bin/sh", "-c"]`, and on 1825 Windows is `["cmd", "/S", "/C"]`. The `SHELL` instruction *must* be written in JSON 1826 form in a Dockerfile. 1827 1828 The `SHELL` instruction is particularly useful on Windows where there are 1829 two commonly used and quite different native shells: `cmd` and `powershell`, as 1830 well as alternate shells available including `sh`. 1831 1832 The `SHELL` instruction can appear multiple times. Each `SHELL` instruction overrides 1833 all previous `SHELL` instructions, and affects all subsequent instructions. For example: 1834 1835 FROM microsoft/windowsservercore 1836 1837 # Executed as cmd /S /C echo default 1838 RUN echo default 1839 1840 # Executed as cmd /S /C powershell -command Write-Host default 1841 RUN powershell -command Write-Host default 1842 1843 # Executed as powershell -command Write-Host hello 1844 SHELL ["powershell", "-command"] 1845 RUN Write-Host hello 1846 1847 # Executed as cmd /S /C echo hello 1848 SHELL ["cmd", "/S", "/C"] 1849 RUN echo hello 1850 1851 The following instructions can be affected by the `SHELL` instruction when the 1852 *shell* form of them is used in a Dockerfile: `RUN`, `CMD` and `ENTRYPOINT`. 1853 1854 The following example is a common pattern found on Windows which can be 1855 streamlined by using the `SHELL` instruction: 1856 1857 ... 1858 RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 1859 ... 1860 1861 The command invoked by docker will be: 1862 1863 cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 1864 1865 This is inefficient for two reasons. First, there is an un-necessary cmd.exe command 1866 processor (aka shell) being invoked. Second, each `RUN` instruction in the *shell* 1867 form requires an extra `powershell -command` prefixing the command. 1868 1869 To make this more efficient, one of two mechanisms can be employed. One is to 1870 use the JSON form of the RUN command such as: 1871 1872 ... 1873 RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""] 1874 ... 1875 1876 While the JSON form is unambiguous and does not use the un-necessary cmd.exe, 1877 it does require more verbosity through double-quoting and escaping. The alternate 1878 mechanism is to use the `SHELL` instruction and the *shell* form, 1879 making a more natural syntax for Windows users, especially when combined with 1880 the `escape` parser directive: 1881 1882 # escape=` 1883 1884 FROM microsoft/nanoserver 1885 SHELL ["powershell","-command"] 1886 RUN New-Item -ItemType Directory C:\Example 1887 ADD Execute-MyCmdlet.ps1 c:\example\ 1888 RUN c:\example\Execute-MyCmdlet -sample 'hello world' 1889 1890 Resulting in: 1891 1892 PS E:\docker\build\shell> docker build -t shell . 1893 Sending build context to Docker daemon 4.096 kB 1894 Step 1/5 : FROM microsoft/nanoserver 1895 ---> 22738ff49c6d 1896 Step 2/5 : SHELL powershell -command 1897 ---> Running in 6fcdb6855ae2 1898 ---> 6331462d4300 1899 Removing intermediate container 6fcdb6855ae2 1900 Step 3/5 : RUN New-Item -ItemType Directory C:\Example 1901 ---> Running in d0eef8386e97 1902 1903 1904 Directory: C:\ 1905 1906 1907 Mode LastWriteTime Length Name 1908 ---- ------------- ------ ---- 1909 d----- 10/28/2016 11:26 AM Example 1910 1911 1912 ---> 3f2fbf1395d9 1913 Removing intermediate container d0eef8386e97 1914 Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\ 1915 ---> a955b2621c31 1916 Removing intermediate container b825593d39fc 1917 Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world' 1918 ---> Running in be6d8e63fe75 1919 hello world 1920 ---> 8e559e9bf424 1921 Removing intermediate container be6d8e63fe75 1922 Successfully built 8e559e9bf424 1923 PS E:\docker\build\shell> 1924 1925 The `SHELL` instruction could also be used to modify the way in which 1926 a shell operates. For example, using `SHELL cmd /S /C /V:ON|OFF` on Windows, delayed 1927 environment variable expansion semantics could be modified. 1928 1929 The `SHELL` instruction can also be used on Linux should an alternate shell be 1930 required such as `zsh`, `csh`, `tcsh` and others. 1931 1932 The `SHELL` feature was added in Docker 1.12. 1933 1934 ## Dockerfile examples 1935 1936 Below you can see some examples of Dockerfile syntax. If you're interested in 1937 something more realistic, take a look at the list of [Dockerization examples](https://docs.docker.com/engine/examples/). 1938 1939 ``` 1940 # Nginx 1941 # 1942 # VERSION 0.0.1 1943 1944 FROM ubuntu 1945 LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0" 1946 RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server 1947 ``` 1948 1949 ``` 1950 # Firefox over VNC 1951 # 1952 # VERSION 0.3 1953 1954 FROM ubuntu 1955 1956 # Install vnc, xvfb in order to create a 'fake' display and firefox 1957 RUN apt-get update && apt-get install -y x11vnc xvfb firefox 1958 RUN mkdir ~/.vnc 1959 # Setup a password 1960 RUN x11vnc -storepasswd 1234 ~/.vnc/passwd 1961 # Autostart firefox (might not be the best way, but it does the trick) 1962 RUN bash -c 'echo "firefox" >> /.bashrc' 1963 1964 EXPOSE 5900 1965 CMD ["x11vnc", "-forever", "-usepw", "-create"] 1966 ``` 1967 1968 ``` 1969 # Multiple images example 1970 # 1971 # VERSION 0.1 1972 1973 FROM ubuntu 1974 RUN echo foo > bar 1975 # Will output something like ===> 907ad6c2736f 1976 1977 FROM ubuntu 1978 RUN echo moo > oink 1979 # Will output something like ===> 695d7793cbe4 1980 1981 # You'll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with 1982 # /oink. 1983 ```