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