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