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