github.com/docker/docker-ce@v17.12.1-ce-rc2+incompatible/components/cli/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 To set up port redirection on the host system, see [using the -P 771 flag](run.md#expose-incoming-ports). The `docker network` command supports 772 creating networks for communication among containers without the need to 773 expose or publish specific ports, because the containers connected to the 774 network can communicate with each other over any port. For detailed information, 775 see the 776 [overview of this feature](https://docs.docker.com/engine/userguide/networking/)). 777 778 ## ENV 779 780 ENV <key> <value> 781 ENV <key>=<value> ... 782 783 The `ENV` instruction sets the environment variable `<key>` to the value 784 `<value>`. This value will be in the environment of all "descendant" 785 `Dockerfile` commands and can be [replaced inline](#environment-replacement) in 786 many as well. 787 788 The `ENV` instruction has two forms. The first form, `ENV <key> <value>`, 789 will set a single variable to a value. The entire string after the first 790 space will be treated as the `<value>` - including characters such as 791 spaces and quotes. 792 793 The second form, `ENV <key>=<value> ...`, allows for multiple variables to 794 be set at one time. Notice that the second form uses the equals sign (=) 795 in the syntax, while the first form does not. Like command line parsing, 796 quotes and backslashes can be used to include spaces within values. 797 798 For example: 799 800 ENV myName="John Doe" myDog=Rex\ The\ Dog \ 801 myCat=fluffy 802 803 and 804 805 ENV myName John Doe 806 ENV myDog Rex The Dog 807 ENV myCat fluffy 808 809 will yield the same net results in the final image, but the first form 810 is preferred because it produces a single cache layer. 811 812 The environment variables set using `ENV` will persist when a container is run 813 from the resulting image. You can view the values using `docker inspect`, and 814 change them using `docker run --env <key>=<value>`. 815 816 > **Note**: 817 > Environment persistence can cause unexpected side effects. For example, 818 > setting `ENV DEBIAN_FRONTEND noninteractive` may confuse apt-get 819 > users on a Debian-based image. To set a value for a single command, use 820 > `RUN <key>=<value> <command>`. 821 822 ## ADD 823 824 ADD has two forms: 825 826 - `ADD [--chown=<user>:<group>] <src>... <dest>` 827 - `ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]` (this form is required for paths containing 828 whitespace) 829 830 > **Note**: 831 > The `--chown` feature is only supported on Dockerfiles used to build Linux containers, 832 > and will not work on Windows containers. Since user and group ownership concepts do 833 > not translate between Linux and Windows, the use of `/etc/passwd` and `/etc/group` for 834 > translating user and group names to IDs restricts this feature to only be viable for 835 > for Linux OS-based containers. 836 837 The `ADD` instruction copies new files, directories or remote file URLs from `<src>` 838 and adds them to the filesystem of the image at the path `<dest>`. 839 840 Multiple `<src>` resources may be specified but if they are files or 841 directories, their paths are interpreted as relative to the source of 842 the context of the build. 843 844 Each `<src>` may contain wildcards and matching will be done using Go's 845 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 846 847 ADD hom* /mydir/ # adds all files starting with "hom" 848 ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 849 850 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 851 the source will be copied inside the destination container. 852 853 ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 854 ADD test /absoluteDir/ # adds "test" to /absoluteDir/ 855 856 When adding files or directories that contain special characters (such as `[` 857 and `]`), you need to escape those paths following the Golang rules to prevent 858 them from being treated as a matching pattern. For example, to add a file 859 named `arr[0].txt`, use the following; 860 861 ADD arr[[]0].txt /mydir/ # copy a file named "arr[0].txt" to /mydir/ 862 863 864 All new files and directories are created with a UID and GID of 0, unless the 865 optional `--chown` flag specifies a given username, groupname, or UID/GID 866 combination to request specific ownership of the content added. The 867 format of the `--chown` flag allows for either username and groupname strings 868 or direct integer UID and GID in any combination. Providing a username without 869 groupname or a UID without GID will use the same numeric UID as the GID. If a 870 username or groupname is provided, the container's root filesystem 871 `/etc/passwd` and `/etc/group` files will be used to perform the translation 872 from name to integer UID or GID respectively. The following examples show 873 valid definitions for the `--chown` flag: 874 875 ADD --chown=55:mygroup files* /somedir/ 876 ADD --chown=bin files* /somedir/ 877 ADD --chown=1 files* /somedir/ 878 ADD --chown=10:11 files* /somedir/ 879 880 If the container root filesystem does not contain either `/etc/passwd` or 881 `/etc/group` files and either user or group names are used in the `--chown` 882 flag, the build will fail on the `ADD` operation. Using numeric IDs requires 883 no lookup and will not depend on container root filesystem content. 884 885 In the case where `<src>` is a remote file URL, the destination will 886 have permissions of 600. If the remote file being retrieved has an HTTP 887 `Last-Modified` header, the timestamp from that header will be used 888 to set the `mtime` on the destination file. However, like any other file 889 processed during an `ADD`, `mtime` will not be included in the determination 890 of whether or not the file has changed and the cache should be updated. 891 892 > **Note**: 893 > If you build by passing a `Dockerfile` through STDIN (`docker 894 > build - < somefile`), there is no build context, so the `Dockerfile` 895 > can only contain a URL based `ADD` instruction. You can also pass a 896 > compressed archive through STDIN: (`docker build - < archive.tar.gz`), 897 > the `Dockerfile` at the root of the archive and the rest of the 898 > archive will be used as the context of the build. 899 900 > **Note**: 901 > If your URL files are protected using authentication, you 902 > will need to use `RUN wget`, `RUN curl` or use another tool from 903 > within the container as the `ADD` instruction does not support 904 > authentication. 905 906 > **Note**: 907 > The first encountered `ADD` instruction will invalidate the cache for all 908 > following instructions from the Dockerfile if the contents of `<src>` have 909 > changed. This includes invalidating the cache for `RUN` instructions. 910 > See the [`Dockerfile` Best Practices 911 guide](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#/build-cache) for more information. 912 913 914 `ADD` obeys the following rules: 915 916 - The `<src>` path must be inside the *context* of the build; 917 you cannot `ADD ../something /something`, because the first step of a 918 `docker build` is to send the context directory (and subdirectories) to the 919 docker daemon. 920 921 - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a 922 file is downloaded from the URL and copied to `<dest>`. 923 924 - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the 925 filename is inferred from the URL and the file is downloaded to 926 `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would 927 create the file `/foobar`. The URL must have a nontrivial path so that an 928 appropriate filename can be discovered in this case (`http://example.com` 929 will not work). 930 931 - If `<src>` is a directory, the entire contents of the directory are copied, 932 including filesystem metadata. 933 934 > **Note**: 935 > The directory itself is not copied, just its contents. 936 937 - If `<src>` is a *local* tar archive in a recognized compression format 938 (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources 939 from *remote* URLs are **not** decompressed. When a directory is copied or 940 unpacked, it has the same behavior as `tar -x`, the result is the union of: 941 942 1. Whatever existed at the destination path and 943 2. The contents of the source tree, with conflicts resolved in favor 944 of "2." on a file-by-file basis. 945 946 > **Note**: 947 > Whether a file is identified as a recognized compression format or not 948 > is done solely based on the contents of the file, not the name of the file. 949 > For example, if an empty file happens to end with `.tar.gz` this will not 950 > be recognized as a compressed file and **will not** generate any kind of 951 > decompression error message, rather the file will simply be copied to the 952 > destination. 953 954 - If `<src>` is any other kind of file, it is copied individually along with 955 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 956 will be considered a directory and the contents of `<src>` will be written 957 at `<dest>/base(<src>)`. 958 959 - If multiple `<src>` resources are specified, either directly or due to the 960 use of a wildcard, then `<dest>` must be a directory, and it must end with 961 a slash `/`. 962 963 - If `<dest>` does not end with a trailing slash, it will be considered a 964 regular file and the contents of `<src>` will be written at `<dest>`. 965 966 - If `<dest>` doesn't exist, it is created along with all missing directories 967 in its path. 968 969 ## COPY 970 971 COPY has two forms: 972 973 - `COPY [--chown=<user>:<group>] <src>... <dest>` 974 - `COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]` (this form is required for paths containing 975 whitespace) 976 977 > **Note**: 978 > The `--chown` feature is only supported on Dockerfiles used to build Linux containers, 979 > and will not work on Windows containers. Since user and group ownership concepts do 980 > not translate between Linux and Windows, the use of `/etc/passwd` and `/etc/group` for 981 > translating user and group names to IDs restricts this feature to only be viable for 982 > for Linux OS-based containers. 983 984 The `COPY` instruction copies new files or directories from `<src>` 985 and adds them to the filesystem of the container at the path `<dest>`. 986 987 Multiple `<src>` resources may be specified but the paths of files and 988 directories will be interpreted as relative to the source of the context 989 of the build. 990 991 Each `<src>` may contain wildcards and matching will be done using Go's 992 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 993 994 COPY hom* /mydir/ # adds all files starting with "hom" 995 COPY hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 996 997 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 998 the source will be copied inside the destination container. 999 1000 COPY test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 1001 COPY test /absoluteDir/ # adds "test" to /absoluteDir/ 1002 1003 1004 When copying files or directories that contain special characters (such as `[` 1005 and `]`), you need to escape those paths following the Golang rules to prevent 1006 them from being treated as a matching pattern. For example, to copy a file 1007 named `arr[0].txt`, use the following; 1008 1009 COPY arr[[]0].txt /mydir/ # copy a file named "arr[0].txt" to /mydir/ 1010 1011 All new files and directories are created with a UID and GID of 0, unless the 1012 optional `--chown` flag specifies a given username, groupname, or UID/GID 1013 combination to request specific ownership of the copied content. The 1014 format of the `--chown` flag allows for either username and groupname strings 1015 or direct integer UID and GID in any combination. Providing a username without 1016 groupname or a UID without GID will use the same numeric UID as the GID. If a 1017 username or groupname is provided, the container's root filesystem 1018 `/etc/passwd` and `/etc/group` files will be used to perform the translation 1019 from name to integer UID or GID respectively. The following examples show 1020 valid definitions for the `--chown` flag: 1021 1022 COPY --chown=55:mygroup files* /somedir/ 1023 COPY --chown=bin files* /somedir/ 1024 COPY --chown=1 files* /somedir/ 1025 COPY --chown=10:11 files* /somedir/ 1026 1027 If the container root filesystem does not contain either `/etc/passwd` or 1028 `/etc/group` files and either user or group names are used in the `--chown` 1029 flag, the build will fail on the `COPY` operation. Using numeric IDs requires 1030 no lookup and will not depend on container root filesystem content. 1031 1032 > **Note**: 1033 > If you build using STDIN (`docker build - < somefile`), there is no 1034 > build context, so `COPY` can't be used. 1035 1036 Optionally `COPY` accepts a flag `--from=<name|index>` that can be used to set 1037 the source location to a previous build stage (created with `FROM .. AS <name>`) 1038 that will be used instead of a build context sent by the user. The flag also 1039 accepts a numeric index assigned for all previous build stages started with 1040 `FROM` instruction. In case a build stage with a specified name can't be found an 1041 image with the same name is attempted to be used instead. 1042 1043 `COPY` obeys the following rules: 1044 1045 - The `<src>` path must be inside the *context* of the build; 1046 you cannot `COPY ../something /something`, because the first step of a 1047 `docker build` is to send the context directory (and subdirectories) to the 1048 docker daemon. 1049 1050 - If `<src>` is a directory, the entire contents of the directory are copied, 1051 including filesystem metadata. 1052 1053 > **Note**: 1054 > The directory itself is not copied, just its contents. 1055 1056 - If `<src>` is any other kind of file, it is copied individually along with 1057 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 1058 will be considered a directory and the contents of `<src>` will be written 1059 at `<dest>/base(<src>)`. 1060 1061 - If multiple `<src>` resources are specified, either directly or due to the 1062 use of a wildcard, then `<dest>` must be a directory, and it must end with 1063 a slash `/`. 1064 1065 - If `<dest>` does not end with a trailing slash, it will be considered a 1066 regular file and the contents of `<src>` will be written at `<dest>`. 1067 1068 - If `<dest>` doesn't exist, it is created along with all missing directories 1069 in its path. 1070 1071 ## ENTRYPOINT 1072 1073 ENTRYPOINT has two forms: 1074 1075 - `ENTRYPOINT ["executable", "param1", "param2"]` 1076 (*exec* form, preferred) 1077 - `ENTRYPOINT command param1 param2` 1078 (*shell* form) 1079 1080 An `ENTRYPOINT` allows you to configure a container that will run as an executable. 1081 1082 For example, the following will start nginx with its default content, listening 1083 on port 80: 1084 1085 docker run -i -t --rm -p 80:80 nginx 1086 1087 Command line arguments to `docker run <image>` will be appended after all 1088 elements in an *exec* form `ENTRYPOINT`, and will override all elements specified 1089 using `CMD`. 1090 This allows arguments to be passed to the entry point, i.e., `docker run <image> -d` 1091 will pass the `-d` argument to the entry point. 1092 You can override the `ENTRYPOINT` instruction using the `docker run --entrypoint` 1093 flag. 1094 1095 The *shell* form prevents any `CMD` or `run` command line arguments from being 1096 used, but has the disadvantage that your `ENTRYPOINT` will be started as a 1097 subcommand of `/bin/sh -c`, which does not pass signals. 1098 This means that the executable will not be the container's `PID 1` - and 1099 will _not_ receive Unix signals - so your executable will not receive a 1100 `SIGTERM` from `docker stop <container>`. 1101 1102 Only the last `ENTRYPOINT` instruction in the `Dockerfile` will have an effect. 1103 1104 ### Exec form ENTRYPOINT example 1105 1106 You can use the *exec* form of `ENTRYPOINT` to set fairly stable default commands 1107 and arguments and then use either form of `CMD` to set additional defaults that 1108 are more likely to be changed. 1109 1110 FROM ubuntu 1111 ENTRYPOINT ["top", "-b"] 1112 CMD ["-c"] 1113 1114 When you run the container, you can see that `top` is the only process: 1115 1116 $ docker run -it --rm --name test top -H 1117 top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05 1118 Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie 1119 %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 1120 KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers 1121 KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem 1122 1123 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1124 1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top 1125 1126 To examine the result further, you can use `docker exec`: 1127 1128 $ docker exec -it test ps aux 1129 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1130 root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H 1131 root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux 1132 1133 And you can gracefully request `top` to shut down using `docker stop test`. 1134 1135 The following `Dockerfile` shows using the `ENTRYPOINT` to run Apache in the 1136 foreground (i.e., as `PID 1`): 1137 1138 ``` 1139 FROM debian:stable 1140 RUN apt-get update && apt-get install -y --force-yes apache2 1141 EXPOSE 80 443 1142 VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"] 1143 ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] 1144 ``` 1145 1146 If you need to write a starter script for a single executable, you can ensure that 1147 the final executable receives the Unix signals by using `exec` and `gosu` 1148 commands: 1149 1150 ```bash 1151 #!/usr/bin/env bash 1152 set -e 1153 1154 if [ "$1" = 'postgres' ]; then 1155 chown -R postgres "$PGDATA" 1156 1157 if [ -z "$(ls -A "$PGDATA")" ]; then 1158 gosu postgres initdb 1159 fi 1160 1161 exec gosu postgres "$@" 1162 fi 1163 1164 exec "$@" 1165 ``` 1166 1167 Lastly, if you need to do some extra cleanup (or communicate with other containers) 1168 on shutdown, or are co-ordinating more than one executable, you may need to ensure 1169 that the `ENTRYPOINT` script receives the Unix signals, passes them on, and then 1170 does some more work: 1171 1172 ``` 1173 #!/bin/sh 1174 # Note: I've written this using sh so it works in the busybox container too 1175 1176 # USE the trap if you need to also do manual cleanup after the service is stopped, 1177 # or need to start multiple services in the one container 1178 trap "echo TRAPed signal" HUP INT QUIT TERM 1179 1180 # start service in background here 1181 /usr/sbin/apachectl start 1182 1183 echo "[hit enter key to exit] or run 'docker stop <container>'" 1184 read 1185 1186 # stop service and clean up here 1187 echo "stopping apache" 1188 /usr/sbin/apachectl stop 1189 1190 echo "exited $0" 1191 ``` 1192 1193 If you run this image with `docker run -it --rm -p 80:80 --name test apache`, 1194 you can then examine the container's processes with `docker exec`, or `docker top`, 1195 and then ask the script to stop Apache: 1196 1197 ```bash 1198 $ docker exec -it test ps aux 1199 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1200 root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123 cmd cmd2 1201 root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start 1202 www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 1203 www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 1204 root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux 1205 $ docker top test 1206 PID USER COMMAND 1207 10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2 1208 10054 root /usr/sbin/apache2 -k start 1209 10055 33 /usr/sbin/apache2 -k start 1210 10056 33 /usr/sbin/apache2 -k start 1211 $ /usr/bin/time docker stop test 1212 test 1213 real 0m 0.27s 1214 user 0m 0.03s 1215 sys 0m 0.03s 1216 ``` 1217 1218 > **Note:** you can override the `ENTRYPOINT` setting using `--entrypoint`, 1219 > but this can only set the binary to *exec* (no `sh -c` will be used). 1220 1221 > **Note**: 1222 > The *exec* form is parsed as a JSON array, which means that 1223 > you must use double-quotes (") around words not single-quotes ('). 1224 1225 > **Note**: 1226 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 1227 > This means that normal shell processing does not happen. For example, 1228 > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 1229 > If you want shell processing then either use the *shell* form or execute 1230 > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo $HOME" ]`. 1231 > When using the exec form and executing a shell directly, as in the case for 1232 > the shell form, it is the shell that is doing the environment variable 1233 > expansion, not docker. 1234 1235 ### Shell form ENTRYPOINT example 1236 1237 You can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`. 1238 This form will use shell processing to substitute shell environment variables, 1239 and will ignore any `CMD` or `docker run` command line arguments. 1240 To ensure that `docker stop` will signal any long running `ENTRYPOINT` executable 1241 correctly, you need to remember to start it with `exec`: 1242 1243 FROM ubuntu 1244 ENTRYPOINT exec top -b 1245 1246 When you run this image, you'll see the single `PID 1` process: 1247 1248 $ docker run -it --rm --name test top 1249 Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached 1250 CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq 1251 Load average: 0.08 0.03 0.05 2/98 6 1252 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1253 1 0 root R 3164 0% 0% top -b 1254 1255 Which will exit cleanly on `docker stop`: 1256 1257 $ /usr/bin/time docker stop test 1258 test 1259 real 0m 0.20s 1260 user 0m 0.02s 1261 sys 0m 0.04s 1262 1263 If you forget to add `exec` to the beginning of your `ENTRYPOINT`: 1264 1265 FROM ubuntu 1266 ENTRYPOINT top -b 1267 CMD --ignored-param1 1268 1269 You can then run it (giving it a name for the next step): 1270 1271 $ docker run -it --name test top --ignored-param2 1272 Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached 1273 CPU: 9% usr 2% sys 0% nic 88% idle 0% io 0% irq 0% sirq 1274 Load average: 0.01 0.02 0.05 2/101 7 1275 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1276 1 0 root S 3168 0% 0% /bin/sh -c top -b cmd cmd2 1277 7 1 root R 3164 0% 0% top -b 1278 1279 You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. 1280 1281 If you then run `docker stop test`, the container will not exit cleanly - the 1282 `stop` command will be forced to send a `SIGKILL` after the timeout: 1283 1284 $ docker exec -it test ps aux 1285 PID USER COMMAND 1286 1 root /bin/sh -c top -b cmd cmd2 1287 7 root top -b 1288 8 root ps aux 1289 $ /usr/bin/time docker stop test 1290 test 1291 real 0m 10.19s 1292 user 0m 0.04s 1293 sys 0m 0.03s 1294 1295 ### Understand how CMD and ENTRYPOINT interact 1296 1297 Both `CMD` and `ENTRYPOINT` instructions define what command gets executed when running a container. 1298 There are few rules that describe their co-operation. 1299 1300 1. Dockerfile should specify at least one of `CMD` or `ENTRYPOINT` commands. 1301 1302 2. `ENTRYPOINT` should be defined when using the container as an executable. 1303 1304 3. `CMD` should be used as a way of defining default arguments for an `ENTRYPOINT` command 1305 or for executing an ad-hoc command in a container. 1306 1307 4. `CMD` will be overridden when running the container with alternative arguments. 1308 1309 The table below shows what command is executed for different `ENTRYPOINT` / `CMD` combinations: 1310 1311 | | No ENTRYPOINT | ENTRYPOINT exec_entry p1_entry | ENTRYPOINT ["exec_entry", "p1_entry"] | 1312 |:-------------------------------|:---------------------------|:-------------------------------|:-----------------------------------------------| 1313 | **No CMD** | *error, not allowed* | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry | 1314 | **CMD ["exec_cmd", "p1_cmd"]** | exec_cmd p1_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry exec_cmd p1_cmd | 1315 | **CMD ["p1_cmd", "p2_cmd"]** | p1_cmd p2_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry p1_cmd p2_cmd | 1316 | **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 | 1317 1318 ## VOLUME 1319 1320 VOLUME ["/data"] 1321 1322 The `VOLUME` instruction creates a mount point with the specified name 1323 and marks it as holding externally mounted volumes from native host or other 1324 containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain 1325 string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log 1326 /var/db`. For more information/examples and mounting instructions via the 1327 Docker client, refer to 1328 [*Share Directories via Volumes*](https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-host-directory-as-a-data-volume) 1329 documentation. 1330 1331 The `docker run` command initializes the newly created volume with any data 1332 that exists at the specified location within the base image. For example, 1333 consider the following Dockerfile snippet: 1334 1335 FROM ubuntu 1336 RUN mkdir /myvol 1337 RUN echo "hello world" > /myvol/greeting 1338 VOLUME /myvol 1339 1340 This Dockerfile results in an image that causes `docker run` to 1341 create a new mount point at `/myvol` and copy the `greeting` file 1342 into the newly created volume. 1343 1344 ### Notes about specifying volumes 1345 1346 Keep the following things in mind about volumes in the `Dockerfile`. 1347 1348 - **Volumes on Windows-based containers**: When using Windows-based containers, 1349 the destination of a volume inside the container must be one of: 1350 1351 - a non-existing or empty directory 1352 - a drive other than `C:` 1353 1354 - **Changing the volume from within the Dockerfile**: If any build steps change the 1355 data within the volume after it has been declared, those changes will be discarded. 1356 1357 - **JSON formatting**: The list is parsed as a JSON array. 1358 You must enclose words with double quotes (`"`)rather than single quotes (`'`). 1359 1360 - **The host directory is declared at container run-time**: The host directory 1361 (the mountpoint) is, by its nature, host-dependent. This is to preserve image 1362 portability, since a given host directory can't be guaranteed to be available 1363 on all hosts. For this reason, you can't mount a host directory from 1364 within the Dockerfile. The `VOLUME` instruction does not support specifying a `host-dir` 1365 parameter. You must specify the mountpoint when you create or run the container. 1366 1367 ## USER 1368 1369 USER <user>[:<group>] 1370 or 1371 USER <UID>[:<GID>] 1372 1373 The `USER` instruction sets the user name (or UID) and optionally the user 1374 group (or GID) to use when running the image and for any `RUN`, `CMD` and 1375 `ENTRYPOINT` instructions that follow it in the `Dockerfile`. 1376 1377 > **Warning**: 1378 > When the user doesn't have a primary group then the image (or the next 1379 > instructions) will be run with the `root` group. 1380 1381 > On Windows, the user must be created first if it's not a built-in account. 1382 > This can be done with the `net user` command called as part of a Dockerfile. 1383 1384 ```Dockerfile 1385 FROM microsoft/windowsservercore 1386 # Create Windows user in the container 1387 RUN net user /add patrick 1388 # Set it for subsequent commands 1389 USER patrick 1390 ``` 1391 1392 1393 ## WORKDIR 1394 1395 WORKDIR /path/to/workdir 1396 1397 The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, 1398 `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. 1399 If the `WORKDIR` doesn't exist, it will be created even if it's not used in any 1400 subsequent `Dockerfile` instruction. 1401 1402 The `WORKDIR` instruction can be used multiple times in a `Dockerfile`. If a 1403 relative path is provided, it will be relative to the path of the previous 1404 `WORKDIR` instruction. For example: 1405 1406 WORKDIR /a 1407 WORKDIR b 1408 WORKDIR c 1409 RUN pwd 1410 1411 The output of the final `pwd` command in this `Dockerfile` would be 1412 `/a/b/c`. 1413 1414 The `WORKDIR` instruction can resolve environment variables previously set using 1415 `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. 1416 For example: 1417 1418 ENV DIRPATH /path 1419 WORKDIR $DIRPATH/$DIRNAME 1420 RUN pwd 1421 1422 The output of the final `pwd` command in this `Dockerfile` would be 1423 `/path/$DIRNAME` 1424 1425 ## ARG 1426 1427 ARG <name>[=<default value>] 1428 1429 The `ARG` instruction defines a variable that users can pass at build-time to 1430 the builder with the `docker build` command using the `--build-arg <varname>=<value>` 1431 flag. If a user specifies a build argument that was not 1432 defined in the Dockerfile, the build outputs a warning. 1433 1434 ``` 1435 [Warning] One or more build-args [foo] were not consumed. 1436 ``` 1437 1438 A Dockerfile may include one or more `ARG` instructions. For example, 1439 the following is a valid Dockerfile: 1440 1441 ``` 1442 FROM busybox 1443 ARG user1 1444 ARG buildno 1445 ... 1446 ``` 1447 1448 > **Warning:** It is not recommended to use build-time variables for 1449 > passing secrets like github keys, user credentials etc. Build-time variable 1450 > values are visible to any user of the image with the `docker history` command. 1451 1452 ### Default values 1453 1454 An `ARG` instruction can optionally include a default value: 1455 1456 ``` 1457 FROM busybox 1458 ARG user1=someuser 1459 ARG buildno=1 1460 ... 1461 ``` 1462 1463 If an `ARG` instruction has a default value and if there is no value passed 1464 at build-time, the builder uses the default. 1465 1466 ### Scope 1467 1468 An `ARG` variable definition comes into effect from the line on which it is 1469 defined in the `Dockerfile` not from the argument's use on the command-line or 1470 elsewhere. For example, consider this Dockerfile: 1471 1472 ``` 1473 1 FROM busybox 1474 2 USER ${user:-some_user} 1475 3 ARG user 1476 4 USER $user 1477 ... 1478 ``` 1479 A user builds this file by calling: 1480 1481 ``` 1482 $ docker build --build-arg user=what_user . 1483 ``` 1484 1485 The `USER` at line 2 evaluates to `some_user` as the `user` variable is defined on the 1486 subsequent line 3. The `USER` at line 4 evaluates to `what_user` as `user` is 1487 defined and the `what_user` value was passed on the command line. Prior to its definition by an 1488 `ARG` instruction, any use of a variable results in an empty string. 1489 1490 An `ARG` instruction goes out of scope at the end of the build 1491 stage where it was defined. To use an arg in multiple stages, each stage must 1492 include the `ARG` instruction. 1493 1494 ``` 1495 FROM busybox 1496 ARG SETTINGS 1497 RUN ./run/setup $SETTINGS 1498 1499 FROM busybox 1500 ARG SETTINGS 1501 RUN ./run/other $SETTINGS 1502 ``` 1503 1504 ### Using ARG variables 1505 1506 You can use an `ARG` or an `ENV` instruction to specify variables that are 1507 available to the `RUN` instruction. Environment variables defined using the 1508 `ENV` instruction always override an `ARG` instruction of the same name. Consider 1509 this Dockerfile with an `ENV` and `ARG` instruction. 1510 1511 ``` 1512 1 FROM ubuntu 1513 2 ARG CONT_IMG_VER 1514 3 ENV CONT_IMG_VER v1.0.0 1515 4 RUN echo $CONT_IMG_VER 1516 ``` 1517 Then, assume this image is built with this command: 1518 1519 ``` 1520 $ docker build --build-arg CONT_IMG_VER=v2.0.1 . 1521 ``` 1522 1523 In this case, the `RUN` instruction uses `v1.0.0` instead of the `ARG` setting 1524 passed by the user:`v2.0.1` This behavior is similar to a shell 1525 script where a locally scoped variable overrides the variables passed as 1526 arguments or inherited from environment, from its point of definition. 1527 1528 Using the example above but a different `ENV` specification you can create more 1529 useful interactions between `ARG` and `ENV` instructions: 1530 1531 ``` 1532 1 FROM ubuntu 1533 2 ARG CONT_IMG_VER 1534 3 ENV CONT_IMG_VER ${CONT_IMG_VER:-v1.0.0} 1535 4 RUN echo $CONT_IMG_VER 1536 ``` 1537 1538 Unlike an `ARG` instruction, `ENV` values are always persisted in the built 1539 image. Consider a docker build without the `--build-arg` flag: 1540 1541 ``` 1542 $ docker build . 1543 ``` 1544 1545 Using this Dockerfile example, `CONT_IMG_VER` is still persisted in the image but 1546 its value would be `v1.0.0` as it is the default set in line 3 by the `ENV` instruction. 1547 1548 The variable expansion technique in this example allows you to pass arguments 1549 from the command line and persist them in the final image by leveraging the 1550 `ENV` instruction. Variable expansion is only supported for [a limited set of 1551 Dockerfile instructions.](#environment-replacement) 1552 1553 ### Predefined ARGs 1554 1555 Docker has a set of predefined `ARG` variables that you can use without a 1556 corresponding `ARG` instruction in the Dockerfile. 1557 1558 * `HTTP_PROXY` 1559 * `http_proxy` 1560 * `HTTPS_PROXY` 1561 * `https_proxy` 1562 * `FTP_PROXY` 1563 * `ftp_proxy` 1564 * `NO_PROXY` 1565 * `no_proxy` 1566 1567 To use these, simply pass them on the command line using the flag: 1568 1569 ``` 1570 --build-arg <varname>=<value> 1571 ``` 1572 1573 By default, these pre-defined variables are excluded from the output of 1574 `docker history`. Excluding them reduces the risk of accidentally leaking 1575 sensitive authentication information in an `HTTP_PROXY` variable. 1576 1577 For example, consider building the following Dockerfile using 1578 `--build-arg HTTP_PROXY=http://user:pass@proxy.lon.example.com` 1579 1580 ``` Dockerfile 1581 FROM ubuntu 1582 RUN echo "Hello World" 1583 ``` 1584 1585 In this case, the value of the `HTTP_PROXY` variable is not available in the 1586 `docker history` and is not cached. If you were to change location, and your 1587 proxy server changed to `http://user:pass@proxy.sfo.example.com`, a subsequent 1588 build does not result in a cache miss. 1589 1590 If you need to override this behaviour then you may do so by adding an `ARG` 1591 statement in the Dockerfile as follows: 1592 1593 ``` Dockerfile 1594 FROM ubuntu 1595 ARG HTTP_PROXY 1596 RUN echo "Hello World" 1597 ``` 1598 1599 When building this Dockerfile, the `HTTP_PROXY` is preserved in the 1600 `docker history`, and changing its value invalidates the build cache. 1601 1602 ### Impact on build caching 1603 1604 `ARG` variables are not persisted into the built image as `ENV` variables are. 1605 However, `ARG` variables do impact the build cache in similar ways. If a 1606 Dockerfile defines an `ARG` variable whose value is different from a previous 1607 build, then a "cache miss" occurs upon its first usage, not its definition. In 1608 particular, all `RUN` instructions following an `ARG` instruction use the `ARG` 1609 variable implicitly (as an environment variable), thus can cause a cache miss. 1610 All predefined `ARG` variables are exempt from caching unless there is a 1611 matching `ARG` statement in the `Dockerfile`. 1612 1613 For example, consider these two Dockerfile: 1614 1615 ``` 1616 1 FROM ubuntu 1617 2 ARG CONT_IMG_VER 1618 3 RUN echo $CONT_IMG_VER 1619 ``` 1620 1621 ``` 1622 1 FROM ubuntu 1623 2 ARG CONT_IMG_VER 1624 3 RUN echo hello 1625 ``` 1626 1627 If you specify `--build-arg CONT_IMG_VER=<value>` on the command line, in both 1628 cases, the specification on line 2 does not cause a cache miss; line 3 does 1629 cause a cache miss.`ARG CONT_IMG_VER` causes the RUN line to be identified 1630 as the same as running `CONT_IMG_VER=<value>` echo hello, so if the `<value>` 1631 changes, we get a cache miss. 1632 1633 Consider another example under the same command line: 1634 1635 ``` 1636 1 FROM ubuntu 1637 2 ARG CONT_IMG_VER 1638 3 ENV CONT_IMG_VER $CONT_IMG_VER 1639 4 RUN echo $CONT_IMG_VER 1640 ``` 1641 In this example, the cache miss occurs on line 3. The miss happens because 1642 the variable's value in the `ENV` references the `ARG` variable and that 1643 variable is changed through the command line. In this example, the `ENV` 1644 command causes the image to include the value. 1645 1646 If an `ENV` instruction overrides an `ARG` instruction of the same name, like 1647 this Dockerfile: 1648 1649 ``` 1650 1 FROM ubuntu 1651 2 ARG CONT_IMG_VER 1652 3 ENV CONT_IMG_VER hello 1653 4 RUN echo $CONT_IMG_VER 1654 ``` 1655 1656 Line 3 does not cause a cache miss because the value of `CONT_IMG_VER` is a 1657 constant (`hello`). As a result, the environment variables and values used on 1658 the `RUN` (line 4) doesn't change between builds. 1659 1660 ## ONBUILD 1661 1662 ONBUILD [INSTRUCTION] 1663 1664 The `ONBUILD` instruction adds to the image a *trigger* instruction to 1665 be executed at a later time, when the image is used as the base for 1666 another build. The trigger will be executed in the context of the 1667 downstream build, as if it had been inserted immediately after the 1668 `FROM` instruction in the downstream `Dockerfile`. 1669 1670 Any build instruction can be registered as a trigger. 1671 1672 This is useful if you are building an image which will be used as a base 1673 to build other images, for example an application build environment or a 1674 daemon which may be customized with user-specific configuration. 1675 1676 For example, if your image is a reusable Python application builder, it 1677 will require application source code to be added in a particular 1678 directory, and it might require a build script to be called *after* 1679 that. You can't just call `ADD` and `RUN` now, because you don't yet 1680 have access to the application source code, and it will be different for 1681 each application build. You could simply provide application developers 1682 with a boilerplate `Dockerfile` to copy-paste into their application, but 1683 that is inefficient, error-prone and difficult to update because it 1684 mixes with application-specific code. 1685 1686 The solution is to use `ONBUILD` to register advance instructions to 1687 run later, during the next build stage. 1688 1689 Here's how it works: 1690 1691 1. When it encounters an `ONBUILD` instruction, the builder adds a 1692 trigger to the metadata of the image being built. The instruction 1693 does not otherwise affect the current build. 1694 2. At the end of the build, a list of all triggers is stored in the 1695 image manifest, under the key `OnBuild`. They can be inspected with 1696 the `docker inspect` command. 1697 3. Later the image may be used as a base for a new build, using the 1698 `FROM` instruction. As part of processing the `FROM` instruction, 1699 the downstream builder looks for `ONBUILD` triggers, and executes 1700 them in the same order they were registered. If any of the triggers 1701 fail, the `FROM` instruction is aborted which in turn causes the 1702 build to fail. If all triggers succeed, the `FROM` instruction 1703 completes and the build continues as usual. 1704 4. Triggers are cleared from the final image after being executed. In 1705 other words they are not inherited by "grand-children" builds. 1706 1707 For example you might add something like this: 1708 1709 [...] 1710 ONBUILD ADD . /app/src 1711 ONBUILD RUN /usr/local/bin/python-build --dir /app/src 1712 [...] 1713 1714 > **Warning**: Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. 1715 1716 > **Warning**: The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. 1717 1718 ## STOPSIGNAL 1719 1720 STOPSIGNAL signal 1721 1722 The `STOPSIGNAL` instruction sets the system call signal that will be sent to the container to exit. 1723 This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9, 1724 or a signal name in the format SIGNAME, for instance SIGKILL. 1725 1726 ## HEALTHCHECK 1727 1728 The `HEALTHCHECK` instruction has two forms: 1729 1730 * `HEALTHCHECK [OPTIONS] CMD command` (check container health by running a command inside the container) 1731 * `HEALTHCHECK NONE` (disable any healthcheck inherited from the base image) 1732 1733 The `HEALTHCHECK` instruction tells Docker how to test a container to check that 1734 it is still working. This can detect cases such as a web server that is stuck in 1735 an infinite loop and unable to handle new connections, even though the server 1736 process is still running. 1737 1738 When a container has a healthcheck specified, it has a _health status_ in 1739 addition to its normal status. This status is initially `starting`. Whenever a 1740 health check passes, it becomes `healthy` (whatever state it was previously in). 1741 After a certain number of consecutive failures, it becomes `unhealthy`. 1742 1743 The options that can appear before `CMD` are: 1744 1745 * `--interval=DURATION` (default: `30s`) 1746 * `--timeout=DURATION` (default: `30s`) 1747 * `--start-period=DURATION` (default: `0s`) 1748 * `--retries=N` (default: `3`) 1749 1750 The health check will first run **interval** seconds after the container is 1751 started, and then again **interval** seconds after each previous check completes. 1752 1753 If a single run of the check takes longer than **timeout** seconds then the check 1754 is considered to have failed. 1755 1756 It takes **retries** consecutive failures of the health check for the container 1757 to be considered `unhealthy`. 1758 1759 **start period** provides initialization time for containers that need time to bootstrap. 1760 Probe failure during that period will not be counted towards the maximum number of retries. 1761 However, if a health check succeeds during the start period, the container is considered 1762 started and all consecutive failures will be counted towards the maximum number of retries. 1763 1764 There can only be one `HEALTHCHECK` instruction in a Dockerfile. If you list 1765 more than one then only the last `HEALTHCHECK` will take effect. 1766 1767 The command after the `CMD` keyword can be either a shell command (e.g. `HEALTHCHECK 1768 CMD /bin/check-running`) or an _exec_ array (as with other Dockerfile commands; 1769 see e.g. `ENTRYPOINT` for details). 1770 1771 The command's exit status indicates the health status of the container. 1772 The possible values are: 1773 1774 - 0: success - the container is healthy and ready for use 1775 - 1: unhealthy - the container is not working correctly 1776 - 2: reserved - do not use this exit code 1777 1778 For example, to check every five minutes or so that a web-server is able to 1779 serve the site's main page within three seconds: 1780 1781 HEALTHCHECK --interval=5m --timeout=3s \ 1782 CMD curl -f http://localhost/ || exit 1 1783 1784 To help debug failing probes, any output text (UTF-8 encoded) that the command writes 1785 on stdout or stderr will be stored in the health status and can be queried with 1786 `docker inspect`. Such output should be kept short (only the first 4096 bytes 1787 are stored currently). 1788 1789 When the health status of a container changes, a `health_status` event is 1790 generated with the new status. 1791 1792 The `HEALTHCHECK` feature was added in Docker 1.12. 1793 1794 1795 ## SHELL 1796 1797 SHELL ["executable", "parameters"] 1798 1799 The `SHELL` instruction allows the default shell used for the *shell* form of 1800 commands to be overridden. The default shell on Linux is `["/bin/sh", "-c"]`, and on 1801 Windows is `["cmd", "/S", "/C"]`. The `SHELL` instruction *must* be written in JSON 1802 form in a Dockerfile. 1803 1804 The `SHELL` instruction is particularly useful on Windows where there are 1805 two commonly used and quite different native shells: `cmd` and `powershell`, as 1806 well as alternate shells available including `sh`. 1807 1808 The `SHELL` instruction can appear multiple times. Each `SHELL` instruction overrides 1809 all previous `SHELL` instructions, and affects all subsequent instructions. For example: 1810 1811 FROM microsoft/windowsservercore 1812 1813 # Executed as cmd /S /C echo default 1814 RUN echo default 1815 1816 # Executed as cmd /S /C powershell -command Write-Host default 1817 RUN powershell -command Write-Host default 1818 1819 # Executed as powershell -command Write-Host hello 1820 SHELL ["powershell", "-command"] 1821 RUN Write-Host hello 1822 1823 # Executed as cmd /S /C echo hello 1824 SHELL ["cmd", "/S"", "/C"] 1825 RUN echo hello 1826 1827 The following instructions can be affected by the `SHELL` instruction when the 1828 *shell* form of them is used in a Dockerfile: `RUN`, `CMD` and `ENTRYPOINT`. 1829 1830 The following example is a common pattern found on Windows which can be 1831 streamlined by using the `SHELL` instruction: 1832 1833 ... 1834 RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 1835 ... 1836 1837 The command invoked by docker will be: 1838 1839 cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 1840 1841 This is inefficient for two reasons. First, there is an un-necessary cmd.exe command 1842 processor (aka shell) being invoked. Second, each `RUN` instruction in the *shell* 1843 form requires an extra `powershell -command` prefixing the command. 1844 1845 To make this more efficient, one of two mechanisms can be employed. One is to 1846 use the JSON form of the RUN command such as: 1847 1848 ... 1849 RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""] 1850 ... 1851 1852 While the JSON form is unambiguous and does not use the un-necessary cmd.exe, 1853 it does require more verbosity through double-quoting and escaping. The alternate 1854 mechanism is to use the `SHELL` instruction and the *shell* form, 1855 making a more natural syntax for Windows users, especially when combined with 1856 the `escape` parser directive: 1857 1858 # escape=` 1859 1860 FROM microsoft/nanoserver 1861 SHELL ["powershell","-command"] 1862 RUN New-Item -ItemType Directory C:\Example 1863 ADD Execute-MyCmdlet.ps1 c:\example\ 1864 RUN c:\example\Execute-MyCmdlet -sample 'hello world' 1865 1866 Resulting in: 1867 1868 PS E:\docker\build\shell> docker build -t shell . 1869 Sending build context to Docker daemon 4.096 kB 1870 Step 1/5 : FROM microsoft/nanoserver 1871 ---> 22738ff49c6d 1872 Step 2/5 : SHELL powershell -command 1873 ---> Running in 6fcdb6855ae2 1874 ---> 6331462d4300 1875 Removing intermediate container 6fcdb6855ae2 1876 Step 3/5 : RUN New-Item -ItemType Directory C:\Example 1877 ---> Running in d0eef8386e97 1878 1879 1880 Directory: C:\ 1881 1882 1883 Mode LastWriteTime Length Name 1884 ---- ------------- ------ ---- 1885 d----- 10/28/2016 11:26 AM Example 1886 1887 1888 ---> 3f2fbf1395d9 1889 Removing intermediate container d0eef8386e97 1890 Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\ 1891 ---> a955b2621c31 1892 Removing intermediate container b825593d39fc 1893 Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world' 1894 ---> Running in be6d8e63fe75 1895 hello world 1896 ---> 8e559e9bf424 1897 Removing intermediate container be6d8e63fe75 1898 Successfully built 8e559e9bf424 1899 PS E:\docker\build\shell> 1900 1901 The `SHELL` instruction could also be used to modify the way in which 1902 a shell operates. For example, using `SHELL cmd /S /C /V:ON|OFF` on Windows, delayed 1903 environment variable expansion semantics could be modified. 1904 1905 The `SHELL` instruction can also be used on Linux should an alternate shell be 1906 required such as `zsh`, `csh`, `tcsh` and others. 1907 1908 The `SHELL` feature was added in Docker 1.12. 1909 1910 ## Dockerfile examples 1911 1912 Below you can see some examples of Dockerfile syntax. If you're interested in 1913 something more realistic, take a look at the list of [Dockerization examples](https://docs.docker.com/engine/examples/). 1914 1915 ``` 1916 # Nginx 1917 # 1918 # VERSION 0.0.1 1919 1920 FROM ubuntu 1921 LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0" 1922 RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server 1923 ``` 1924 1925 ``` 1926 # Firefox over VNC 1927 # 1928 # VERSION 0.3 1929 1930 FROM ubuntu 1931 1932 # Install vnc, xvfb in order to create a 'fake' display and firefox 1933 RUN apt-get update && apt-get install -y x11vnc xvfb firefox 1934 RUN mkdir ~/.vnc 1935 # Setup a password 1936 RUN x11vnc -storepasswd 1234 ~/.vnc/passwd 1937 # Autostart firefox (might not be the best way, but it does the trick) 1938 RUN bash -c 'echo "firefox" >> /.bashrc' 1939 1940 EXPOSE 5900 1941 CMD ["x11vnc", "-forever", "-usepw", "-create"] 1942 ``` 1943 1944 ``` 1945 # Multiple images example 1946 # 1947 # VERSION 0.1 1948 1949 FROM ubuntu 1950 RUN echo foo > bar 1951 # Will output something like ===> 907ad6c2736f 1952 1953 FROM ubuntu 1954 RUN echo moo > oink 1955 # Will output something like ===> 695d7793cbe4 1956 1957 # You'll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with 1958 # /oink. 1959 ```