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