github.com/kaisenlinux/docker@v0.0.0-20230510090727-ea55db55fac7/cli/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 apt-get update && DEBIAN_FRONTEND=noninteractive 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 top - 13:58:24 up 17 min, 0 users, load average: 0.00, 0.00, 0.00 1644 Tasks: 2 total, 1 running, 1 sleeping, 0 stopped, 0 zombie 1645 %Cpu(s): 16.7 us, 33.3 sy, 0.0 ni, 50.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st 1646 MiB Mem : 1990.8 total, 1354.6 free, 231.4 used, 404.7 buff/cache 1647 MiB Swap: 1024.0 total, 1024.0 free, 0.0 used. 1639.8 avail Mem 1648 1649 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1650 1 root 20 0 2612 604 536 S 0.0 0.0 0:00.02 sh 1651 6 root 20 0 5956 3188 2768 R 0.0 0.2 0:00.00 top 1652 ``` 1653 1654 You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. 1655 1656 If you then run `docker stop test`, the container will not exit cleanly - the 1657 `stop` command will be forced to send a `SIGKILL` after the timeout: 1658 1659 ```console 1660 $ docker exec -it test ps waux 1661 1662 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1663 root 1 0.4 0.0 2612 604 pts/0 Ss+ 13:58 0:00 /bin/sh -c top -b --ignored-param2 1664 root 6 0.0 0.1 5956 3188 pts/0 S+ 13:58 0:00 top -b 1665 root 7 0.0 0.1 5884 2816 pts/1 Rs+ 13:58 0:00 ps waux 1666 1667 $ /usr/bin/time docker stop test 1668 1669 test 1670 real 0m 10.19s 1671 user 0m 0.04s 1672 sys 0m 0.03s 1673 ``` 1674 1675 ### Understand how CMD and ENTRYPOINT interact 1676 1677 Both `CMD` and `ENTRYPOINT` instructions define what command gets executed when running a container. 1678 There are few rules that describe their co-operation. 1679 1680 1. Dockerfile should specify at least one of `CMD` or `ENTRYPOINT` commands. 1681 1682 2. `ENTRYPOINT` should be defined when using the container as an executable. 1683 1684 3. `CMD` should be used as a way of defining default arguments for an `ENTRYPOINT` command 1685 or for executing an ad-hoc command in a container. 1686 1687 4. `CMD` will be overridden when running the container with alternative arguments. 1688 1689 The table below shows what command is executed for different `ENTRYPOINT` / `CMD` combinations: 1690 1691 | | No ENTRYPOINT | ENTRYPOINT exec_entry p1_entry | ENTRYPOINT ["exec_entry", "p1_entry"] | 1692 |:-------------------------------|:---------------------------|:-------------------------------|:-----------------------------------------------| 1693 | **No CMD** | *error, not allowed* | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry | 1694 | **CMD ["exec_cmd", "p1_cmd"]** | exec_cmd p1_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry exec_cmd p1_cmd | 1695 | **CMD ["p1_cmd", "p2_cmd"]** | p1_cmd p2_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry p1_cmd p2_cmd | 1696 | **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 | 1697 1698 > **Note** 1699 > 1700 > If `CMD` is defined from the base image, setting `ENTRYPOINT` will 1701 > reset `CMD` to an empty value. In this scenario, `CMD` must be defined in the 1702 > current image to have a value. 1703 1704 ## VOLUME 1705 1706 ```dockerfile 1707 VOLUME ["/data"] 1708 ``` 1709 1710 The `VOLUME` instruction creates a mount point with the specified name 1711 and marks it as holding externally mounted volumes from native host or other 1712 containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain 1713 string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log 1714 /var/db`. For more information/examples and mounting instructions via the 1715 Docker client, refer to 1716 [*Share Directories via Volumes*](https://docs.docker.com/storage/volumes/) 1717 documentation. 1718 1719 The `docker run` command initializes the newly created volume with any data 1720 that exists at the specified location within the base image. For example, 1721 consider the following Dockerfile snippet: 1722 1723 ```dockerfile 1724 FROM ubuntu 1725 RUN mkdir /myvol 1726 RUN echo "hello world" > /myvol/greeting 1727 VOLUME /myvol 1728 ``` 1729 1730 This Dockerfile results in an image that causes `docker run` to 1731 create a new mount point at `/myvol` and copy the `greeting` file 1732 into the newly created volume. 1733 1734 ### Notes about specifying volumes 1735 1736 Keep the following things in mind about volumes in the `Dockerfile`. 1737 1738 - **Volumes on Windows-based containers**: When using Windows-based containers, 1739 the destination of a volume inside the container must be one of: 1740 1741 - a non-existing or empty directory 1742 - a drive other than `C:` 1743 1744 - **Changing the volume from within the Dockerfile**: If any build steps change the 1745 data within the volume after it has been declared, those changes will be discarded. 1746 1747 - **JSON formatting**: The list is parsed as a JSON array. 1748 You must enclose words with double quotes (`"`) rather than single quotes (`'`). 1749 1750 - **The host directory is declared at container run-time**: The host directory 1751 (the mountpoint) is, by its nature, host-dependent. This is to preserve image 1752 portability, since a given host directory can't be guaranteed to be available 1753 on all hosts. For this reason, you can't mount a host directory from 1754 within the Dockerfile. The `VOLUME` instruction does not support specifying a `host-dir` 1755 parameter. You must specify the mountpoint when you create or run the container. 1756 1757 ## USER 1758 1759 ```dockerfile 1760 USER <user>[:<group>] 1761 ``` 1762 1763 or 1764 1765 ```dockerfile 1766 USER <UID>[:<GID>] 1767 ``` 1768 1769 The `USER` instruction sets the user name (or UID) and optionally the user 1770 group (or GID) to use when running the image and for any `RUN`, `CMD` and 1771 `ENTRYPOINT` instructions that follow it in the `Dockerfile`. 1772 1773 > Note that when specifying a group for the user, the user will have _only_ the 1774 > specified group membership. Any other configured group memberships will be ignored. 1775 1776 > **Warning** 1777 > 1778 > When the user doesn't have a primary group then the image (or the next 1779 > instructions) will be run with the `root` group. 1780 > 1781 > On Windows, the user must be created first if it's not a built-in account. 1782 > This can be done with the `net user` command called as part of a Dockerfile. 1783 1784 ```dockerfile 1785 FROM microsoft/windowsservercore 1786 # Create Windows user in the container 1787 RUN net user /add patrick 1788 # Set it for subsequent commands 1789 USER patrick 1790 ``` 1791 1792 1793 ## WORKDIR 1794 1795 ```dockerfile 1796 WORKDIR /path/to/workdir 1797 ``` 1798 1799 The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, 1800 `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. 1801 If the `WORKDIR` doesn't exist, it will be created even if it's not used in any 1802 subsequent `Dockerfile` instruction. 1803 1804 The `WORKDIR` instruction can be used multiple times in a `Dockerfile`. If a 1805 relative path is provided, it will be relative to the path of the previous 1806 `WORKDIR` instruction. For example: 1807 1808 ```dockerfile 1809 WORKDIR /a 1810 WORKDIR b 1811 WORKDIR c 1812 RUN pwd 1813 ``` 1814 1815 The output of the final `pwd` command in this `Dockerfile` would be `/a/b/c`. 1816 1817 The `WORKDIR` instruction can resolve environment variables previously set using 1818 `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. 1819 For example: 1820 1821 ```dockerfile 1822 ENV DIRPATH=/path 1823 WORKDIR $DIRPATH/$DIRNAME 1824 RUN pwd 1825 ``` 1826 1827 The output of the final `pwd` command in this `Dockerfile` would be 1828 `/path/$DIRNAME` 1829 1830 If not specified, the default working directory is `/`. In practice, if you aren't building a Dockerfile from scratch (`FROM scratch`), 1831 the `WORKDIR` may likely be set by the base image you're using. 1832 1833 Therefore, to avoid unintended operations in unknown directories, it is best practice to set your `WORKDIR` explicitly. 1834 1835 ## ARG 1836 1837 ```dockerfile 1838 ARG <name>[=<default value>] 1839 ``` 1840 1841 The `ARG` instruction defines a variable that users can pass at build-time to 1842 the builder with the `docker build` command using the `--build-arg <varname>=<value>` 1843 flag. If a user specifies a build argument that was not 1844 defined in the Dockerfile, the build outputs a warning. 1845 1846 ```console 1847 [Warning] One or more build-args [foo] were not consumed. 1848 ``` 1849 1850 A Dockerfile may include one or more `ARG` instructions. For example, 1851 the following is a valid Dockerfile: 1852 1853 ```dockerfile 1854 FROM busybox 1855 ARG user1 1856 ARG buildno 1857 # ... 1858 ``` 1859 1860 > **Warning:** 1861 > 1862 > It is not recommended to use build-time variables for passing secrets like 1863 > github keys, user credentials etc. Build-time variable values are visible to 1864 > any user of the image with the `docker history` command. 1865 > 1866 > Refer to the ["build images with BuildKit"](https://docs.docker.com/develop/develop-images/build_enhancements/#new-docker-build-secret-information) 1867 > section to learn about secure ways to use secrets when building images. 1868 {:.warning} 1869 1870 ### Default values 1871 1872 An `ARG` instruction can optionally include a default value: 1873 1874 ```dockerfile 1875 FROM busybox 1876 ARG user1=someuser 1877 ARG buildno=1 1878 # ... 1879 ``` 1880 1881 If an `ARG` instruction has a default value and if there is no value passed 1882 at build-time, the builder uses the default. 1883 1884 ### Scope 1885 1886 An `ARG` variable definition comes into effect from the line on which it is 1887 defined in the `Dockerfile` not from the argument's use on the command-line or 1888 elsewhere. For example, consider this Dockerfile: 1889 1890 ```dockerfile 1891 FROM busybox 1892 USER ${user:-some_user} 1893 ARG user 1894 USER $user 1895 # ... 1896 ``` 1897 1898 A user builds this file by calling: 1899 1900 ```console 1901 $ docker build --build-arg user=what_user . 1902 ``` 1903 1904 The `USER` at line 2 evaluates to `some_user` as the `user` variable is defined on the 1905 subsequent line 3. The `USER` at line 4 evaluates to `what_user` as `user` is 1906 defined and the `what_user` value was passed on the command line. Prior to its definition by an 1907 `ARG` instruction, any use of a variable results in an empty string. 1908 1909 An `ARG` instruction goes out of scope at the end of the build 1910 stage where it was defined. To use an arg in multiple stages, each stage must 1911 include the `ARG` instruction. 1912 1913 ```dockerfile 1914 FROM busybox 1915 ARG SETTINGS 1916 RUN ./run/setup $SETTINGS 1917 1918 FROM busybox 1919 ARG SETTINGS 1920 RUN ./run/other $SETTINGS 1921 ``` 1922 1923 ### Using ARG variables 1924 1925 You can use an `ARG` or an `ENV` instruction to specify variables that are 1926 available to the `RUN` instruction. Environment variables defined using the 1927 `ENV` instruction always override an `ARG` instruction of the same name. Consider 1928 this Dockerfile with an `ENV` and `ARG` instruction. 1929 1930 ```dockerfile 1931 FROM ubuntu 1932 ARG CONT_IMG_VER 1933 ENV CONT_IMG_VER=v1.0.0 1934 RUN echo $CONT_IMG_VER 1935 ``` 1936 1937 Then, assume this image is built with this command: 1938 1939 ```console 1940 $ docker build --build-arg CONT_IMG_VER=v2.0.1 . 1941 ``` 1942 1943 In this case, the `RUN` instruction uses `v1.0.0` instead of the `ARG` setting 1944 passed by the user:`v2.0.1` This behavior is similar to a shell 1945 script where a locally scoped variable overrides the variables passed as 1946 arguments or inherited from environment, from its point of definition. 1947 1948 Using the example above but a different `ENV` specification you can create more 1949 useful interactions between `ARG` and `ENV` instructions: 1950 1951 ```dockerfile 1952 FROM ubuntu 1953 ARG CONT_IMG_VER 1954 ENV CONT_IMG_VER=${CONT_IMG_VER:-v1.0.0} 1955 RUN echo $CONT_IMG_VER 1956 ``` 1957 1958 Unlike an `ARG` instruction, `ENV` values are always persisted in the built 1959 image. Consider a docker build without the `--build-arg` flag: 1960 1961 ```console 1962 $ docker build . 1963 ``` 1964 1965 Using this Dockerfile example, `CONT_IMG_VER` is still persisted in the image but 1966 its value would be `v1.0.0` as it is the default set in line 3 by the `ENV` instruction. 1967 1968 The variable expansion technique in this example allows you to pass arguments 1969 from the command line and persist them in the final image by leveraging the 1970 `ENV` instruction. Variable expansion is only supported for [a limited set of 1971 Dockerfile instructions.](#environment-replacement) 1972 1973 ### Predefined ARGs 1974 1975 Docker has a set of predefined `ARG` variables that you can use without a 1976 corresponding `ARG` instruction in the Dockerfile. 1977 1978 - `HTTP_PROXY` 1979 - `http_proxy` 1980 - `HTTPS_PROXY` 1981 - `https_proxy` 1982 - `FTP_PROXY` 1983 - `ftp_proxy` 1984 - `NO_PROXY` 1985 - `no_proxy` 1986 1987 To use these, pass them on the command line using the `--build-arg` flag, for 1988 example: 1989 1990 ```console 1991 $ docker build --build-arg HTTPS_PROXY=https://my-proxy.example.com . 1992 ``` 1993 1994 By default, these pre-defined variables are excluded from the output of 1995 `docker history`. Excluding them reduces the risk of accidentally leaking 1996 sensitive authentication information in an `HTTP_PROXY` variable. 1997 1998 For example, consider building the following Dockerfile using 1999 `--build-arg HTTP_PROXY=http://user:pass@proxy.lon.example.com` 2000 2001 ```dockerfile 2002 FROM ubuntu 2003 RUN echo "Hello World" 2004 ``` 2005 2006 In this case, the value of the `HTTP_PROXY` variable is not available in the 2007 `docker history` and is not cached. If you were to change location, and your 2008 proxy server changed to `http://user:pass@proxy.sfo.example.com`, a subsequent 2009 build does not result in a cache miss. 2010 2011 If you need to override this behaviour then you may do so by adding an `ARG` 2012 statement in the Dockerfile as follows: 2013 2014 ```dockerfile 2015 FROM ubuntu 2016 ARG HTTP_PROXY 2017 RUN echo "Hello World" 2018 ``` 2019 2020 When building this Dockerfile, the `HTTP_PROXY` is preserved in the 2021 `docker history`, and changing its value invalidates the build cache. 2022 2023 ### Automatic platform ARGs in the global scope 2024 2025 This feature is only available when using the [BuildKit](#buildkit) backend. 2026 2027 Docker predefines a set of `ARG` variables with information on the platform of 2028 the node performing the build (build platform) and on the platform of the 2029 resulting image (target platform). The target platform can be specified with 2030 the `--platform` flag on `docker build`. 2031 2032 The following `ARG` variables are set automatically: 2033 2034 - `TARGETPLATFORM` - platform of the build result. Eg `linux/amd64`, `linux/arm/v7`, `windows/amd64`. 2035 - `TARGETOS` - OS component of TARGETPLATFORM 2036 - `TARGETARCH` - architecture component of TARGETPLATFORM 2037 - `TARGETVARIANT` - variant component of TARGETPLATFORM 2038 - `BUILDPLATFORM` - platform of the node performing the build. 2039 - `BUILDOS` - OS component of BUILDPLATFORM 2040 - `BUILDARCH` - architecture component of BUILDPLATFORM 2041 - `BUILDVARIANT` - variant component of BUILDPLATFORM 2042 2043 These arguments are defined in the global scope so are not automatically 2044 available inside build stages or for your `RUN` commands. To expose one of 2045 these arguments inside the build stage redefine it without value. 2046 2047 For example: 2048 2049 ```dockerfile 2050 FROM alpine 2051 ARG TARGETPLATFORM 2052 RUN echo "I'm building for $TARGETPLATFORM" 2053 ``` 2054 2055 ### Impact on build caching 2056 2057 `ARG` variables are not persisted into the built image as `ENV` variables are. 2058 However, `ARG` variables do impact the build cache in similar ways. If a 2059 Dockerfile defines an `ARG` variable whose value is different from a previous 2060 build, then a "cache miss" occurs upon its first usage, not its definition. In 2061 particular, all `RUN` instructions following an `ARG` instruction use the `ARG` 2062 variable implicitly (as an environment variable), thus can cause a cache miss. 2063 All predefined `ARG` variables are exempt from caching unless there is a 2064 matching `ARG` statement in the `Dockerfile`. 2065 2066 For example, consider these two Dockerfile: 2067 2068 ```dockerfile 2069 FROM ubuntu 2070 ARG CONT_IMG_VER 2071 RUN echo $CONT_IMG_VER 2072 ``` 2073 2074 ```dockerfile 2075 FROM ubuntu 2076 ARG CONT_IMG_VER 2077 RUN echo hello 2078 ``` 2079 2080 If you specify `--build-arg CONT_IMG_VER=<value>` on the command line, in both 2081 cases, the specification on line 2 does not cause a cache miss; line 3 does 2082 cause a cache miss.`ARG CONT_IMG_VER` causes the RUN line to be identified 2083 as the same as running `CONT_IMG_VER=<value> echo hello`, so if the `<value>` 2084 changes, we get a cache miss. 2085 2086 Consider another example under the same command line: 2087 2088 ```dockerfile 2089 FROM ubuntu 2090 ARG CONT_IMG_VER 2091 ENV CONT_IMG_VER=$CONT_IMG_VER 2092 RUN echo $CONT_IMG_VER 2093 ``` 2094 2095 In this example, the cache miss occurs on line 3. The miss happens because 2096 the variable's value in the `ENV` references the `ARG` variable and that 2097 variable is changed through the command line. In this example, the `ENV` 2098 command causes the image to include the value. 2099 2100 If an `ENV` instruction overrides an `ARG` instruction of the same name, like 2101 this Dockerfile: 2102 2103 ```dockerfile 2104 FROM ubuntu 2105 ARG CONT_IMG_VER 2106 ENV CONT_IMG_VER=hello 2107 RUN echo $CONT_IMG_VER 2108 ``` 2109 2110 Line 3 does not cause a cache miss because the value of `CONT_IMG_VER` is a 2111 constant (`hello`). As a result, the environment variables and values used on 2112 the `RUN` (line 4) doesn't change between builds. 2113 2114 ## ONBUILD 2115 2116 ```dockerfile 2117 ONBUILD <INSTRUCTION> 2118 ``` 2119 2120 The `ONBUILD` instruction adds to the image a *trigger* instruction to 2121 be executed at a later time, when the image is used as the base for 2122 another build. The trigger will be executed in the context of the 2123 downstream build, as if it had been inserted immediately after the 2124 `FROM` instruction in the downstream `Dockerfile`. 2125 2126 Any build instruction can be registered as a trigger. 2127 2128 This is useful if you are building an image which will be used as a base 2129 to build other images, for example an application build environment or a 2130 daemon which may be customized with user-specific configuration. 2131 2132 For example, if your image is a reusable Python application builder, it 2133 will require application source code to be added in a particular 2134 directory, and it might require a build script to be called *after* 2135 that. You can't just call `ADD` and `RUN` now, because you don't yet 2136 have access to the application source code, and it will be different for 2137 each application build. You could simply provide application developers 2138 with a boilerplate `Dockerfile` to copy-paste into their application, but 2139 that is inefficient, error-prone and difficult to update because it 2140 mixes with application-specific code. 2141 2142 The solution is to use `ONBUILD` to register advance instructions to 2143 run later, during the next build stage. 2144 2145 Here's how it works: 2146 2147 1. When it encounters an `ONBUILD` instruction, the builder adds a 2148 trigger to the metadata of the image being built. The instruction 2149 does not otherwise affect the current build. 2150 2. At the end of the build, a list of all triggers is stored in the 2151 image manifest, under the key `OnBuild`. They can be inspected with 2152 the `docker inspect` command. 2153 3. Later the image may be used as a base for a new build, using the 2154 `FROM` instruction. As part of processing the `FROM` instruction, 2155 the downstream builder looks for `ONBUILD` triggers, and executes 2156 them in the same order they were registered. If any of the triggers 2157 fail, the `FROM` instruction is aborted which in turn causes the 2158 build to fail. If all triggers succeed, the `FROM` instruction 2159 completes and the build continues as usual. 2160 4. Triggers are cleared from the final image after being executed. In 2161 other words they are not inherited by "grand-children" builds. 2162 2163 For example you might add something like this: 2164 2165 ```dockerfile 2166 ONBUILD ADD . /app/src 2167 ONBUILD RUN /usr/local/bin/python-build --dir /app/src 2168 ``` 2169 2170 > **Warning** 2171 > 2172 > Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. 2173 2174 > **Warning** 2175 > 2176 > The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. 2177 2178 ## STOPSIGNAL 2179 2180 ```dockerfile 2181 STOPSIGNAL signal 2182 ``` 2183 2184 The `STOPSIGNAL` instruction sets the system call signal that will be sent to the 2185 container to exit. This signal can be a signal name in the format `SIG<NAME>`, 2186 for instance `SIGKILL`, or an unsigned number that matches a position in the 2187 kernel's syscall table, for instance `9`. The default is `SIGTERM` if not 2188 defined. 2189 2190 The image's default stopsignal can be overridden per container, using the 2191 `--stop-signal` flag on `docker run` and `docker create`. 2192 2193 ## HEALTHCHECK 2194 2195 The `HEALTHCHECK` instruction has two forms: 2196 2197 - `HEALTHCHECK [OPTIONS] CMD command` (check container health by running a command inside the container) 2198 - `HEALTHCHECK NONE` (disable any healthcheck inherited from the base image) 2199 2200 The `HEALTHCHECK` instruction tells Docker how to test a container to check that 2201 it is still working. This can detect cases such as a web server that is stuck in 2202 an infinite loop and unable to handle new connections, even though the server 2203 process is still running. 2204 2205 When a container has a healthcheck specified, it has a _health status_ in 2206 addition to its normal status. This status is initially `starting`. Whenever a 2207 health check passes, it becomes `healthy` (whatever state it was previously in). 2208 After a certain number of consecutive failures, it becomes `unhealthy`. 2209 2210 The options that can appear before `CMD` are: 2211 2212 - `--interval=DURATION` (default: `30s`) 2213 - `--timeout=DURATION` (default: `30s`) 2214 - `--start-period=DURATION` (default: `0s`) 2215 - `--retries=N` (default: `3`) 2216 2217 The health check will first run **interval** seconds after the container is 2218 started, and then again **interval** seconds after each previous check completes. 2219 2220 If a single run of the check takes longer than **timeout** seconds then the check 2221 is considered to have failed. 2222 2223 It takes **retries** consecutive failures of the health check for the container 2224 to be considered `unhealthy`. 2225 2226 **start period** provides initialization time for containers that need time to bootstrap. 2227 Probe failure during that period will not be counted towards the maximum number of retries. 2228 However, if a health check succeeds during the start period, the container is considered 2229 started and all consecutive failures will be counted towards the maximum number of retries. 2230 2231 There can only be one `HEALTHCHECK` instruction in a Dockerfile. If you list 2232 more than one then only the last `HEALTHCHECK` will take effect. 2233 2234 The command after the `CMD` keyword can be either a shell command (e.g. `HEALTHCHECK 2235 CMD /bin/check-running`) or an _exec_ array (as with other Dockerfile commands; 2236 see e.g. `ENTRYPOINT` for details). 2237 2238 The command's exit status indicates the health status of the container. 2239 The possible values are: 2240 2241 - 0: success - the container is healthy and ready for use 2242 - 1: unhealthy - the container is not working correctly 2243 - 2: reserved - do not use this exit code 2244 2245 For example, to check every five minutes or so that a web-server is able to 2246 serve the site's main page within three seconds: 2247 2248 ```dockerfile 2249 HEALTHCHECK --interval=5m --timeout=3s \ 2250 CMD curl -f http://localhost/ || exit 1 2251 ``` 2252 2253 To help debug failing probes, any output text (UTF-8 encoded) that the command writes 2254 on stdout or stderr will be stored in the health status and can be queried with 2255 `docker inspect`. Such output should be kept short (only the first 4096 bytes 2256 are stored currently). 2257 2258 When the health status of a container changes, a `health_status` event is 2259 generated with the new status. 2260 2261 2262 ## SHELL 2263 2264 ```dockerfile 2265 SHELL ["executable", "parameters"] 2266 ``` 2267 2268 The `SHELL` instruction allows the default shell used for the *shell* form of 2269 commands to be overridden. The default shell on Linux is `["/bin/sh", "-c"]`, and on 2270 Windows is `["cmd", "/S", "/C"]`. The `SHELL` instruction *must* be written in JSON 2271 form in a Dockerfile. 2272 2273 The `SHELL` instruction is particularly useful on Windows where there are 2274 two commonly used and quite different native shells: `cmd` and `powershell`, as 2275 well as alternate shells available including `sh`. 2276 2277 The `SHELL` instruction can appear multiple times. Each `SHELL` instruction overrides 2278 all previous `SHELL` instructions, and affects all subsequent instructions. For example: 2279 2280 ```dockerfile 2281 FROM microsoft/windowsservercore 2282 2283 # Executed as cmd /S /C echo default 2284 RUN echo default 2285 2286 # Executed as cmd /S /C powershell -command Write-Host default 2287 RUN powershell -command Write-Host default 2288 2289 # Executed as powershell -command Write-Host hello 2290 SHELL ["powershell", "-command"] 2291 RUN Write-Host hello 2292 2293 # Executed as cmd /S /C echo hello 2294 SHELL ["cmd", "/S", "/C"] 2295 RUN echo hello 2296 ``` 2297 2298 The following instructions can be affected by the `SHELL` instruction when the 2299 *shell* form of them is used in a Dockerfile: `RUN`, `CMD` and `ENTRYPOINT`. 2300 2301 The following example is a common pattern found on Windows which can be 2302 streamlined by using the `SHELL` instruction: 2303 2304 ```dockerfile 2305 RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 2306 ``` 2307 2308 The command invoked by docker will be: 2309 2310 ```powershell 2311 cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 2312 ``` 2313 2314 This is inefficient for two reasons. First, there is an un-necessary cmd.exe command 2315 processor (aka shell) being invoked. Second, each `RUN` instruction in the *shell* 2316 form requires an extra `powershell -command` prefixing the command. 2317 2318 To make this more efficient, one of two mechanisms can be employed. One is to 2319 use the JSON form of the RUN command such as: 2320 2321 ```dockerfile 2322 RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""] 2323 ``` 2324 2325 While the JSON form is unambiguous and does not use the un-necessary cmd.exe, 2326 it does require more verbosity through double-quoting and escaping. The alternate 2327 mechanism is to use the `SHELL` instruction and the *shell* form, 2328 making a more natural syntax for Windows users, especially when combined with 2329 the `escape` parser directive: 2330 2331 ```dockerfile 2332 # escape=` 2333 2334 FROM microsoft/nanoserver 2335 SHELL ["powershell","-command"] 2336 RUN New-Item -ItemType Directory C:\Example 2337 ADD Execute-MyCmdlet.ps1 c:\example\ 2338 RUN c:\example\Execute-MyCmdlet -sample 'hello world' 2339 ``` 2340 2341 Resulting in: 2342 2343 ```console 2344 PS E:\myproject> docker build -t shell . 2345 2346 Sending build context to Docker daemon 4.096 kB 2347 Step 1/5 : FROM microsoft/nanoserver 2348 ---> 22738ff49c6d 2349 Step 2/5 : SHELL powershell -command 2350 ---> Running in 6fcdb6855ae2 2351 ---> 6331462d4300 2352 Removing intermediate container 6fcdb6855ae2 2353 Step 3/5 : RUN New-Item -ItemType Directory C:\Example 2354 ---> Running in d0eef8386e97 2355 2356 2357 Directory: C:\ 2358 2359 2360 Mode LastWriteTime Length Name 2361 ---- ------------- ------ ---- 2362 d----- 10/28/2016 11:26 AM Example 2363 2364 2365 ---> 3f2fbf1395d9 2366 Removing intermediate container d0eef8386e97 2367 Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\ 2368 ---> a955b2621c31 2369 Removing intermediate container b825593d39fc 2370 Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world' 2371 ---> Running in be6d8e63fe75 2372 hello world 2373 ---> 8e559e9bf424 2374 Removing intermediate container be6d8e63fe75 2375 Successfully built 8e559e9bf424 2376 PS E:\myproject> 2377 ``` 2378 2379 The `SHELL` instruction could also be used to modify the way in which 2380 a shell operates. For example, using `SHELL cmd /S /C /V:ON|OFF` on Windows, delayed 2381 environment variable expansion semantics could be modified. 2382 2383 The `SHELL` instruction can also be used on Linux should an alternate shell be 2384 required such as `zsh`, `csh`, `tcsh` and others. 2385 2386 ## Dockerfile examples 2387 2388 For examples of Dockerfiles, refer to: 2389 2390 - The ["build images" section](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) 2391 - The ["get started](https://docs.docker.com/get-started/) 2392 - The [language-specific getting started guides](https://docs.docker.com/language/)