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