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