github.com/brahmaroutu/docker@v1.2.1-0.20160809185609-eb28dde01f16/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 0 : FROM alpine:3.2 90 ---> 31f630c65071 91 Step 1 : MAINTAINER SvenDowideit@home.org.au 92 ---> Using cache 93 ---> 2a1c91448f5f 94 Step 2 : RUN apk update && apk add socat && rm -r /var/cache/ 95 ---> Using cache 96 ---> 21ed6e7fbb73 97 Step 3 : 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 > 545 > **Note**: 546 > In the *JSON* form, it is necessary to escape backslashes. This is 547 > particularly relevant on Windows where the backslash is the path separator. 548 > The following line would otherwise be treated as *shell* form due to not 549 > being valid JSON, and fail in an unexpected way: 550 > `RUN ["c:\windows\system32\tasklist.exe"]` 551 > The correct syntax for this example is: 552 > `RUN ["c:\\windows\\system32\\tasklist.exe"]` 553 554 The cache for `RUN` instructions isn't invalidated automatically during 555 the next build. The cache for an instruction like 556 `RUN apt-get dist-upgrade -y` will be reused during the next build. The 557 cache for `RUN` instructions can be invalidated by using the `--no-cache` 558 flag, for example `docker build --no-cache`. 559 560 See the [`Dockerfile` Best Practices 561 guide](../userguide/eng-image/dockerfile_best-practices.md#build-cache) for more information. 562 563 The cache for `RUN` instructions can be invalidated by `ADD` instructions. See 564 [below](#add) for details. 565 566 ### Known issues (RUN) 567 568 - [Issue 783](https://github.com/docker/docker/issues/783) is about file 569 permissions problems that can occur when using the AUFS file system. You 570 might notice it during an attempt to `rm` a file, for example. 571 572 For systems that have recent aufs version (i.e., `dirperm1` mount option can 573 be set), docker will attempt to fix the issue automatically by mounting 574 the layers with `dirperm1` option. More details on `dirperm1` option can be 575 found at [`aufs` man page](https://github.com/sfjro/aufs3-linux/tree/aufs3.18/Documentation/filesystems/aufs) 576 577 If your system doesn't have support for `dirperm1`, the issue describes a workaround. 578 579 ## CMD 580 581 The `CMD` instruction has three forms: 582 583 - `CMD ["executable","param1","param2"]` (*exec* form, this is the preferred form) 584 - `CMD ["param1","param2"]` (as *default parameters to ENTRYPOINT*) 585 - `CMD command param1 param2` (*shell* form) 586 587 There can only be one `CMD` instruction in a `Dockerfile`. If you list more than one `CMD` 588 then only the last `CMD` will take effect. 589 590 **The main purpose of a `CMD` is to provide defaults for an executing 591 container.** These defaults can include an executable, or they can omit 592 the executable, in which case you must specify an `ENTRYPOINT` 593 instruction as well. 594 595 > **Note**: 596 > If `CMD` is used to provide default arguments for the `ENTRYPOINT` 597 > instruction, both the `CMD` and `ENTRYPOINT` instructions should be specified 598 > with the JSON array format. 599 600 > **Note**: 601 > The *exec* form is parsed as a JSON array, which means that 602 > you must use double-quotes (") around words not single-quotes ('). 603 604 > **Note**: 605 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 606 > This means that normal shell processing does not happen. For example, 607 > `CMD [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 608 > If you want shell processing then either use the *shell* form or execute 609 > a shell directly, for example: `CMD [ "sh", "-c", "echo $HOME" ]`. 610 611 When used in the shell or exec formats, the `CMD` instruction sets the command 612 to be executed when running the image. 613 614 If you use the *shell* form of the `CMD`, then the `<command>` will execute in 615 `/bin/sh -c`: 616 617 FROM ubuntu 618 CMD echo "This is a test." | wc - 619 620 If you want to **run your** `<command>` **without a shell** then you must 621 express the command as a JSON array and give the full path to the executable. 622 **This array form is the preferred format of `CMD`.** Any additional parameters 623 must be individually expressed as strings in the array: 624 625 FROM ubuntu 626 CMD ["/usr/bin/wc","--help"] 627 628 If you would like your container to run the same executable every time, then 629 you should consider using `ENTRYPOINT` in combination with `CMD`. See 630 [*ENTRYPOINT*](#entrypoint). 631 632 If the user specifies arguments to `docker run` then they will override the 633 default specified in `CMD`. 634 635 > **Note**: 636 > don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits 637 > the result; `CMD` does not execute anything at build time, but specifies 638 > the intended command for the image. 639 640 ## LABEL 641 642 LABEL <key>=<value> <key>=<value> <key>=<value> ... 643 644 The `LABEL` instruction adds metadata to an image. A `LABEL` is a 645 key-value pair. To include spaces within a `LABEL` value, use quotes and 646 backslashes as you would in command-line parsing. A few usage examples: 647 648 LABEL "com.example.vendor"="ACME Incorporated" 649 LABEL com.example.label-with-value="foo" 650 LABEL version="1.0" 651 LABEL description="This text illustrates \ 652 that label-values can span multiple lines." 653 654 An image can have more than one label. To specify multiple labels, 655 Docker recommends combining labels into a single `LABEL` instruction where 656 possible. Each `LABEL` instruction produces a new layer which can result in an 657 inefficient image if you use many labels. This example results in a single image 658 layer. 659 660 LABEL multi.label1="value1" multi.label2="value2" other="value3" 661 662 The above can also be written as: 663 664 LABEL multi.label1="value1" \ 665 multi.label2="value2" \ 666 other="value3" 667 668 Labels are additive including `LABEL`s in `FROM` images. If Docker 669 encounters a label/key that already exists, the new value overrides any previous 670 labels with identical keys. 671 672 To view an image's labels, use the `docker inspect` command. 673 674 "Labels": { 675 "com.example.vendor": "ACME Incorporated" 676 "com.example.label-with-value": "foo", 677 "version": "1.0", 678 "description": "This text illustrates that label-values can span multiple lines.", 679 "multi.label1": "value1", 680 "multi.label2": "value2", 681 "other": "value3" 682 }, 683 684 ## EXPOSE 685 686 EXPOSE <port> [<port>...] 687 688 The `EXPOSE` instruction informs Docker that the container listens on the 689 specified network ports at runtime. `EXPOSE` does not make the ports of the 690 container accessible to the host. To do that, you must use either the `-p` flag 691 to publish a range of ports or the `-P` flag to publish all of the exposed 692 ports. You can expose one port number and publish it externally under another 693 number. 694 695 To set up port redirection on the host system, see [using the -P 696 flag](run.md#expose-incoming-ports). The Docker network feature supports 697 creating networks without the need to expose ports within the network, for 698 detailed information see the [overview of this 699 feature](../userguide/networking/index.md)). 700 701 ## ENV 702 703 ENV <key> <value> 704 ENV <key>=<value> ... 705 706 The `ENV` instruction sets the environment variable `<key>` to the value 707 `<value>`. This value will be in the environment of all "descendant" 708 `Dockerfile` commands and can be [replaced inline](#environment-replacement) in 709 many as well. 710 711 The `ENV` instruction has two forms. The first form, `ENV <key> <value>`, 712 will set a single variable to a value. The entire string after the first 713 space will be treated as the `<value>` - including characters such as 714 spaces and quotes. 715 716 The second form, `ENV <key>=<value> ...`, allows for multiple variables to 717 be set at one time. Notice that the second form uses the equals sign (=) 718 in the syntax, while the first form does not. Like command line parsing, 719 quotes and backslashes can be used to include spaces within values. 720 721 For example: 722 723 ENV myName="John Doe" myDog=Rex\ The\ Dog \ 724 myCat=fluffy 725 726 and 727 728 ENV myName John Doe 729 ENV myDog Rex The Dog 730 ENV myCat fluffy 731 732 will yield the same net results in the final container, but the first form 733 is preferred because it produces a single cache layer. 734 735 The environment variables set using `ENV` will persist when a container is run 736 from the resulting image. You can view the values using `docker inspect`, and 737 change them using `docker run --env <key>=<value>`. 738 739 > **Note**: 740 > Environment persistence can cause unexpected side effects. For example, 741 > setting `ENV DEBIAN_FRONTEND noninteractive` may confuse apt-get 742 > users on a Debian-based image. To set a value for a single command, use 743 > `RUN <key>=<value> <command>`. 744 745 ## ADD 746 747 ADD has two forms: 748 749 - `ADD <src>... <dest>` 750 - `ADD ["<src>",... "<dest>"]` (this form is required for paths containing 751 whitespace) 752 753 The `ADD` instruction copies new files, directories or remote file URLs from `<src>` 754 and adds them to the filesystem of the container at the path `<dest>`. 755 756 Multiple `<src>` resource may be specified but if they are files or 757 directories then they must be relative to the source directory that is 758 being built (the context of the build). 759 760 Each `<src>` may contain wildcards and matching will be done using Go's 761 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 762 763 ADD hom* /mydir/ # adds all files starting with "hom" 764 ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 765 766 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 767 the source will be copied inside the destination container. 768 769 ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 770 ADD test /absoluteDir/ # adds "test" to /absoluteDir/ 771 772 All new files and directories are created with a UID and GID of 0. 773 774 In the case where `<src>` is a remote file URL, the destination will 775 have permissions of 600. If the remote file being retrieved has an HTTP 776 `Last-Modified` header, the timestamp from that header will be used 777 to set the `mtime` on the destination file. However, like any other file 778 processed during an `ADD`, `mtime` will not be included in the determination 779 of whether or not the file has changed and the cache should be updated. 780 781 > **Note**: 782 > If you build by passing a `Dockerfile` through STDIN (`docker 783 > build - < somefile`), there is no build context, so the `Dockerfile` 784 > can only contain a URL based `ADD` instruction. You can also pass a 785 > compressed archive through STDIN: (`docker build - < archive.tar.gz`), 786 > the `Dockerfile` at the root of the archive and the rest of the 787 > archive will get used at the context of the build. 788 789 > **Note**: 790 > If your URL files are protected using authentication, you 791 > will need to use `RUN wget`, `RUN curl` or use another tool from 792 > within the container as the `ADD` instruction does not support 793 > authentication. 794 795 > **Note**: 796 > The first encountered `ADD` instruction will invalidate the cache for all 797 > following instructions from the Dockerfile if the contents of `<src>` have 798 > changed. This includes invalidating the cache for `RUN` instructions. 799 > See the [`Dockerfile` Best Practices 800 guide](../userguide/eng-image/dockerfile_best-practices.md#build-cache) for more information. 801 802 803 `ADD` obeys the following rules: 804 805 - The `<src>` path must be inside the *context* of the build; 806 you cannot `ADD ../something /something`, because the first step of a 807 `docker build` is to send the context directory (and subdirectories) to the 808 docker daemon. 809 810 - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a 811 file is downloaded from the URL and copied to `<dest>`. 812 813 - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the 814 filename is inferred from the URL and the file is downloaded to 815 `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would 816 create the file `/foobar`. The URL must have a nontrivial path so that an 817 appropriate filename can be discovered in this case (`http://example.com` 818 will not work). 819 820 - If `<src>` is a directory, the entire contents of the directory are copied, 821 including filesystem metadata. 822 823 > **Note**: 824 > The directory itself is not copied, just its contents. 825 826 - If `<src>` is a *local* tar archive in a recognized compression format 827 (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources 828 from *remote* URLs are **not** decompressed. When a directory is copied or 829 unpacked, it has the same behavior as `tar -x`: the result is the union of: 830 831 1. Whatever existed at the destination path and 832 2. The contents of the source tree, with conflicts resolved in favor 833 of "2." on a file-by-file basis. 834 835 > **Note**: 836 > Whether a file is identified as a recognized compression format or not 837 > is done solely based on the contents of the file, not the name of the file. 838 > For example, if an empty file happens to end with `.tar.gz` this will not 839 > be recognized as a compressed file and **will not** generate any kind of 840 > decompression error message, rather the file will simply be copied to the 841 > destination. 842 843 - If `<src>` is any other kind of file, it is copied individually along with 844 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 845 will be considered a directory and the contents of `<src>` will be written 846 at `<dest>/base(<src>)`. 847 848 - If multiple `<src>` resources are specified, either directly or due to the 849 use of a wildcard, then `<dest>` must be a directory, and it must end with 850 a slash `/`. 851 852 - If `<dest>` does not end with a trailing slash, it will be considered a 853 regular file and the contents of `<src>` will be written at `<dest>`. 854 855 - If `<dest>` doesn't exist, it is created along with all missing directories 856 in its path. 857 858 ## COPY 859 860 COPY has two forms: 861 862 - `COPY <src>... <dest>` 863 - `COPY ["<src>",... "<dest>"]` (this form is required for paths containing 864 whitespace) 865 866 The `COPY` instruction copies new files or directories from `<src>` 867 and adds them to the filesystem of the container at the path `<dest>`. 868 869 Multiple `<src>` resource may be specified but they must be relative 870 to the source directory that is being built (the context of the build). 871 872 Each `<src>` may contain wildcards and matching will be done using Go's 873 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 874 875 COPY hom* /mydir/ # adds all files starting with "hom" 876 COPY hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 877 878 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 879 the source will be copied inside the destination container. 880 881 COPY test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 882 COPY test /absoluteDir/ # adds "test" to /absoluteDir/ 883 884 All new files and directories are created with a UID and GID of 0. 885 886 > **Note**: 887 > If you build using STDIN (`docker build - < somefile`), there is no 888 > build context, so `COPY` can't be used. 889 890 `COPY` obeys the following rules: 891 892 - The `<src>` path must be inside the *context* of the build; 893 you cannot `COPY ../something /something`, because the first step of a 894 `docker build` is to send the context directory (and subdirectories) to the 895 docker daemon. 896 897 - If `<src>` is a directory, the entire contents of the directory are copied, 898 including filesystem metadata. 899 900 > **Note**: 901 > The directory itself is not copied, just its contents. 902 903 - If `<src>` is any other kind of file, it is copied individually along with 904 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 905 will be considered a directory and the contents of `<src>` will be written 906 at `<dest>/base(<src>)`. 907 908 - If multiple `<src>` resources are specified, either directly or due to the 909 use of a wildcard, then `<dest>` must be a directory, and it must end with 910 a slash `/`. 911 912 - If `<dest>` does not end with a trailing slash, it will be considered a 913 regular file and the contents of `<src>` will be written at `<dest>`. 914 915 - If `<dest>` doesn't exist, it is created along with all missing directories 916 in its path. 917 918 ## ENTRYPOINT 919 920 ENTRYPOINT has two forms: 921 922 - `ENTRYPOINT ["executable", "param1", "param2"]` 923 (*exec* form, preferred) 924 - `ENTRYPOINT command param1 param2` 925 (*shell* form) 926 927 An `ENTRYPOINT` allows you to configure a container that will run as an executable. 928 929 For example, the following will start nginx with its default content, listening 930 on port 80: 931 932 docker run -i -t --rm -p 80:80 nginx 933 934 Command line arguments to `docker run <image>` will be appended after all 935 elements in an *exec* form `ENTRYPOINT`, and will override all elements specified 936 using `CMD`. 937 This allows arguments to be passed to the entry point, i.e., `docker run <image> -d` 938 will pass the `-d` argument to the entry point. 939 You can override the `ENTRYPOINT` instruction using the `docker run --entrypoint` 940 flag. 941 942 The *shell* form prevents any `CMD` or `run` command line arguments from being 943 used, but has the disadvantage that your `ENTRYPOINT` will be started as a 944 subcommand of `/bin/sh -c`, which does not pass signals. 945 This means that the executable will not be the container's `PID 1` - and 946 will _not_ receive Unix signals - so your executable will not receive a 947 `SIGTERM` from `docker stop <container>`. 948 949 Only the last `ENTRYPOINT` instruction in the `Dockerfile` will have an effect. 950 951 ### Exec form ENTRYPOINT example 952 953 You can use the *exec* form of `ENTRYPOINT` to set fairly stable default commands 954 and arguments and then use either form of `CMD` to set additional defaults that 955 are more likely to be changed. 956 957 FROM ubuntu 958 ENTRYPOINT ["top", "-b"] 959 CMD ["-c"] 960 961 When you run the container, you can see that `top` is the only process: 962 963 $ docker run -it --rm --name test top -H 964 top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05 965 Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie 966 %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 967 KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers 968 KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem 969 970 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 971 1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top 972 973 To examine the result further, you can use `docker exec`: 974 975 $ docker exec -it test ps aux 976 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 977 root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H 978 root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux 979 980 And you can gracefully request `top` to shut down using `docker stop test`. 981 982 The following `Dockerfile` shows using the `ENTRYPOINT` to run Apache in the 983 foreground (i.e., as `PID 1`): 984 985 ``` 986 FROM debian:stable 987 RUN apt-get update && apt-get install -y --force-yes apache2 988 EXPOSE 80 443 989 VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"] 990 ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] 991 ``` 992 993 If you need to write a starter script for a single executable, you can ensure that 994 the final executable receives the Unix signals by using `exec` and `gosu` 995 commands: 996 997 ```bash 998 #!/bin/bash 999 set -e 1000 1001 if [ "$1" = 'postgres' ]; then 1002 chown -R postgres "$PGDATA" 1003 1004 if [ -z "$(ls -A "$PGDATA")" ]; then 1005 gosu postgres initdb 1006 fi 1007 1008 exec gosu postgres "$@" 1009 fi 1010 1011 exec "$@" 1012 ``` 1013 1014 Lastly, if you need to do some extra cleanup (or communicate with other containers) 1015 on shutdown, or are co-ordinating more than one executable, you may need to ensure 1016 that the `ENTRYPOINT` script receives the Unix signals, passes them on, and then 1017 does some more work: 1018 1019 ``` 1020 #!/bin/sh 1021 # Note: I've written this using sh so it works in the busybox container too 1022 1023 # USE the trap if you need to also do manual cleanup after the service is stopped, 1024 # or need to start multiple services in the one container 1025 trap "echo TRAPed signal" HUP INT QUIT TERM 1026 1027 # start service in background here 1028 /usr/sbin/apachectl start 1029 1030 echo "[hit enter key to exit] or run 'docker stop <container>'" 1031 read 1032 1033 # stop service and clean up here 1034 echo "stopping apache" 1035 /usr/sbin/apachectl stop 1036 1037 echo "exited $0" 1038 ``` 1039 1040 If you run this image with `docker run -it --rm -p 80:80 --name test apache`, 1041 you can then examine the container's processes with `docker exec`, or `docker top`, 1042 and then ask the script to stop Apache: 1043 1044 ```bash 1045 $ docker exec -it test ps aux 1046 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 1047 root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123 cmd cmd2 1048 root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start 1049 www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 1050 www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 1051 root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux 1052 $ docker top test 1053 PID USER COMMAND 1054 10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2 1055 10054 root /usr/sbin/apache2 -k start 1056 10055 33 /usr/sbin/apache2 -k start 1057 10056 33 /usr/sbin/apache2 -k start 1058 $ /usr/bin/time docker stop test 1059 test 1060 real 0m 0.27s 1061 user 0m 0.03s 1062 sys 0m 0.03s 1063 ``` 1064 1065 > **Note:** you can over ride the `ENTRYPOINT` setting using `--entrypoint`, 1066 > but this can only set the binary to *exec* (no `sh -c` will be used). 1067 1068 > **Note**: 1069 > The *exec* form is parsed as a JSON array, which means that 1070 > you must use double-quotes (") around words not single-quotes ('). 1071 1072 > **Note**: 1073 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 1074 > This means that normal shell processing does not happen. For example, 1075 > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 1076 > If you want shell processing then either use the *shell* form or execute 1077 > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo $HOME" ]`. 1078 > Variables that are defined in the `Dockerfile`using `ENV`, will be substituted by 1079 > the `Dockerfile` parser. 1080 1081 ### Shell form ENTRYPOINT example 1082 1083 You can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`. 1084 This form will use shell processing to substitute shell environment variables, 1085 and will ignore any `CMD` or `docker run` command line arguments. 1086 To ensure that `docker stop` will signal any long running `ENTRYPOINT` executable 1087 correctly, you need to remember to start it with `exec`: 1088 1089 FROM ubuntu 1090 ENTRYPOINT exec top -b 1091 1092 When you run this image, you'll see the single `PID 1` process: 1093 1094 $ docker run -it --rm --name test top 1095 Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached 1096 CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq 1097 Load average: 0.08 0.03 0.05 2/98 6 1098 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1099 1 0 root R 3164 0% 0% top -b 1100 1101 Which will exit cleanly on `docker stop`: 1102 1103 $ /usr/bin/time docker stop test 1104 test 1105 real 0m 0.20s 1106 user 0m 0.02s 1107 sys 0m 0.04s 1108 1109 If you forget to add `exec` to the beginning of your `ENTRYPOINT`: 1110 1111 FROM ubuntu 1112 ENTRYPOINT top -b 1113 CMD --ignored-param1 1114 1115 You can then run it (giving it a name for the next step): 1116 1117 $ docker run -it --name test top --ignored-param2 1118 Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached 1119 CPU: 9% usr 2% sys 0% nic 88% idle 0% io 0% irq 0% sirq 1120 Load average: 0.01 0.02 0.05 2/101 7 1121 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1122 1 0 root S 3168 0% 0% /bin/sh -c top -b cmd cmd2 1123 7 1 root R 3164 0% 0% top -b 1124 1125 You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. 1126 1127 If you then run `docker stop test`, the container will not exit cleanly - the 1128 `stop` command will be forced to send a `SIGKILL` after the timeout: 1129 1130 $ docker exec -it test ps aux 1131 PID USER COMMAND 1132 1 root /bin/sh -c top -b cmd cmd2 1133 7 root top -b 1134 8 root ps aux 1135 $ /usr/bin/time docker stop test 1136 test 1137 real 0m 10.19s 1138 user 0m 0.04s 1139 sys 0m 0.03s 1140 1141 ### Understand how CMD and ENTRYPOINT interact 1142 1143 Both `CMD` and `ENTRYPOINT` instructions define what command gets executed when running a container. 1144 There are few rules that describe their co-operation. 1145 1146 1. Dockerfile should specify at least one of `CMD` or `ENTRYPOINT` commands. 1147 1148 2. `ENTRYPOINT` should be defined when using the container as an executable. 1149 1150 3. `CMD` should be used as a way of defining default arguments for an `ENTRYPOINT` command 1151 or for executing an ad-hoc command in a container. 1152 1153 4. `CMD` will be overridden when running the container with alternative arguments. 1154 1155 The table below shows what command is executed for different `ENTRYPOINT` / `CMD` combinations: 1156 1157 | | No ENTRYPOINT | ENTRYPOINT exec_entry p1_entry | ENTRYPOINT ["exec_entry", "p1_entry"] | 1158 |--------------------------------|----------------------------|-----------------------------------------------------------|------------------------------------------------| 1159 | **No CMD** | *error, not allowed* | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry | 1160 | **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 | 1161 | **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 | 1162 | **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 | 1163 1164 ## VOLUME 1165 1166 VOLUME ["/data"] 1167 1168 The `VOLUME` instruction creates a mount point with the specified name 1169 and marks it as holding externally mounted volumes from native host or other 1170 containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain 1171 string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log 1172 /var/db`. For more information/examples and mounting instructions via the 1173 Docker client, refer to 1174 [*Share Directories via Volumes*](../tutorials/dockervolumes.md#mount-a-host-directory-as-a-data-volume) 1175 documentation. 1176 1177 The `docker run` command initializes the newly created volume with any data 1178 that exists at the specified location within the base image. For example, 1179 consider the following Dockerfile snippet: 1180 1181 FROM ubuntu 1182 RUN mkdir /myvol 1183 RUN echo "hello world" > /myvol/greeting 1184 VOLUME /myvol 1185 1186 This Dockerfile results in an image that causes `docker run`, to 1187 create a new mount point at `/myvol` and copy the `greeting` file 1188 into the newly created volume. 1189 1190 > **Note**: 1191 > If any build steps change the data within the volume after it has been 1192 > declared, those changes will be discarded. 1193 1194 > **Note**: 1195 > The list is parsed as a JSON array, which means that 1196 > you must use double-quotes (") around words not single-quotes ('). 1197 1198 ## USER 1199 1200 USER daemon 1201 1202 The `USER` instruction sets the user name or UID to use when running the image 1203 and for any `RUN`, `CMD` and `ENTRYPOINT` instructions that follow it in the 1204 `Dockerfile`. 1205 1206 ## WORKDIR 1207 1208 WORKDIR /path/to/workdir 1209 1210 The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, 1211 `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. 1212 If the `WORKDIR` doesn't exist, it will be created even if it's not used in any 1213 subsequent `Dockerfile` instruction. 1214 1215 It can be used multiple times in the one `Dockerfile`. If a relative path 1216 is provided, it will be relative to the path of the previous `WORKDIR` 1217 instruction. For example: 1218 1219 WORKDIR /a 1220 WORKDIR b 1221 WORKDIR c 1222 RUN pwd 1223 1224 The output of the final `pwd` command in this `Dockerfile` would be 1225 `/a/b/c`. 1226 1227 The `WORKDIR` instruction can resolve environment variables previously set using 1228 `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. 1229 For example: 1230 1231 ENV DIRPATH /path 1232 WORKDIR $DIRPATH/$DIRNAME 1233 RUN pwd 1234 1235 The output of the final `pwd` command in this `Dockerfile` would be 1236 `/path/$DIRNAME` 1237 1238 ## ARG 1239 1240 ARG <name>[=<default value>] 1241 1242 The `ARG` instruction defines a variable that users can pass at build-time to 1243 the builder with the `docker build` command using the `--build-arg 1244 <varname>=<value>` flag. If a user specifies a build argument that was not 1245 defined in the Dockerfile, the build outputs an error. 1246 1247 ``` 1248 One or more build-args were not consumed, failing build. 1249 ``` 1250 1251 The Dockerfile author can define a single variable by specifying `ARG` once or many 1252 variables by specifying `ARG` more than once. For example, a valid Dockerfile: 1253 1254 ``` 1255 FROM busybox 1256 ARG user1 1257 ARG buildno 1258 ... 1259 ``` 1260 1261 A Dockerfile author may optionally specify a default value for an `ARG` instruction: 1262 1263 ``` 1264 FROM busybox 1265 ARG user1=someuser 1266 ARG buildno=1 1267 ... 1268 ``` 1269 1270 If an `ARG` value has a default and if there is no value passed at build-time, the 1271 builder uses the default. 1272 1273 An `ARG` variable definition comes into effect from the line on which it is 1274 defined in the `Dockerfile` not from the argument's use on the command-line or 1275 elsewhere. For example, consider this Dockerfile: 1276 1277 ``` 1278 1 FROM busybox 1279 2 USER ${user:-some_user} 1280 3 ARG user 1281 4 USER $user 1282 ... 1283 ``` 1284 A user builds this file by calling: 1285 1286 ``` 1287 $ docker build --build-arg user=what_user Dockerfile 1288 ``` 1289 1290 The `USER` at line 2 evaluates to `some_user` as the `user` variable is defined on the 1291 subsequent line 3. The `USER` at line 4 evaluates to `what_user` as `user` is 1292 defined and the `what_user` value was passed on the command line. Prior to its definition by an 1293 `ARG` instruction, any use of a variable results in an empty string. 1294 1295 > **Warning:** It is not recommended to use build-time variables for 1296 > passing secrets like github keys, user credentials etc. Build-time variable 1297 > values are visible to any user of the image with the `docker history` command. 1298 1299 You can use an `ARG` or an `ENV` instruction to specify variables that are 1300 available to the `RUN` instruction. Environment variables defined using the 1301 `ENV` instruction always override an `ARG` instruction of the same name. Consider 1302 this Dockerfile with an `ENV` and `ARG` instruction. 1303 1304 ``` 1305 1 FROM ubuntu 1306 2 ARG CONT_IMG_VER 1307 3 ENV CONT_IMG_VER v1.0.0 1308 4 RUN echo $CONT_IMG_VER 1309 ``` 1310 Then, assume this image is built with this command: 1311 1312 ``` 1313 $ docker build --build-arg CONT_IMG_VER=v2.0.1 Dockerfile 1314 ``` 1315 1316 In this case, the `RUN` instruction uses `v1.0.0` instead of the `ARG` setting 1317 passed by the user:`v2.0.1` This behavior is similar to a shell 1318 script where a locally scoped variable overrides the variables passed as 1319 arguments or inherited from environment, from its point of definition. 1320 1321 Using the example above but a different `ENV` specification you can create more 1322 useful interactions between `ARG` and `ENV` instructions: 1323 1324 ``` 1325 1 FROM ubuntu 1326 2 ARG CONT_IMG_VER 1327 3 ENV CONT_IMG_VER ${CONT_IMG_VER:-v1.0.0} 1328 4 RUN echo $CONT_IMG_VER 1329 ``` 1330 1331 Unlike an `ARG` instruction, `ENV` values are always persisted in the built 1332 image. Consider a docker build without the --build-arg flag: 1333 1334 ``` 1335 $ docker build Dockerfile 1336 ``` 1337 1338 Using this Dockerfile example, `CONT_IMG_VER` is still persisted in the image but 1339 its value would be `v1.0.0` as it is the default set in line 3 by the `ENV` instruction. 1340 1341 The variable expansion technique in this example allows you to pass arguments 1342 from the command line and persist them in the final image by leveraging the 1343 `ENV` instruction. Variable expansion is only supported for [a limited set of 1344 Dockerfile instructions.](#environment-replacement) 1345 1346 Docker has a set of predefined `ARG` variables that you can use without a 1347 corresponding `ARG` instruction in the Dockerfile. 1348 1349 * `HTTP_PROXY` 1350 * `http_proxy` 1351 * `HTTPS_PROXY` 1352 * `https_proxy` 1353 * `FTP_PROXY` 1354 * `ftp_proxy` 1355 * `NO_PROXY` 1356 * `no_proxy` 1357 1358 To use these, simply pass them on the command line using the `--build-arg 1359 <varname>=<value>` flag. 1360 1361 ### Impact on build caching 1362 1363 `ARG` variables are not persisted into the built image as `ENV` variables are. 1364 However, `ARG` variables do impact the build cache in similar ways. If a 1365 Dockerfile defines an `ARG` variable whose value is different from a previous 1366 build, then a "cache miss" occurs upon its first usage, not its definition. In 1367 particular, all `RUN` instructions following an `ARG` instruction use the `ARG` 1368 variable implicitly (as an environment variable), thus can cause a cache miss. 1369 1370 For example, consider these two Dockerfile: 1371 1372 ``` 1373 1 FROM ubuntu 1374 2 ARG CONT_IMG_VER 1375 3 RUN echo $CONT_IMG_VER 1376 ``` 1377 1378 ``` 1379 1 FROM ubuntu 1380 2 ARG CONT_IMG_VER 1381 3 RUN echo hello 1382 ``` 1383 1384 If you specify `--build-arg CONT_IMG_VER=<value>` on the command line, in both 1385 cases, the specification on line 2 does not cause a cache miss; line 3 does 1386 cause a cache miss.`ARG CONT_IMG_VER` causes the RUN line to be identified 1387 as the same as running `CONT_IMG_VER=<value>` echo hello, so if the `<value>` 1388 changes, we get a cache miss. 1389 1390 Consider another example under the same command line: 1391 1392 ``` 1393 1 FROM ubuntu 1394 2 ARG CONT_IMG_VER 1395 3 ENV CONT_IMG_VER $CONT_IMG_VER 1396 4 RUN echo $CONT_IMG_VER 1397 ``` 1398 In this example, the cache miss occurs on line 3. The miss happens because 1399 the variable's value in the `ENV` references the `ARG` variable and that 1400 variable is changed through the command line. In this example, the `ENV` 1401 command causes the image to include the value. 1402 1403 If an `ENV` instruction overrides an `ARG` instruction of the same name, like 1404 this Dockerfile: 1405 1406 ``` 1407 1 FROM ubuntu 1408 2 ARG CONT_IMG_VER 1409 3 ENV CONT_IMG_VER hello 1410 4 RUN echo $CONT_IMG_VER 1411 ``` 1412 1413 Line 3 does not cause a cache miss because the value of `CONT_IMG_VER` is a 1414 constant (`hello`). As a result, the environment variables and values used on 1415 the `RUN` (line 4) doesn't change between builds. 1416 1417 ## ONBUILD 1418 1419 ONBUILD [INSTRUCTION] 1420 1421 The `ONBUILD` instruction adds to the image a *trigger* instruction to 1422 be executed at a later time, when the image is used as the base for 1423 another build. The trigger will be executed in the context of the 1424 downstream build, as if it had been inserted immediately after the 1425 `FROM` instruction in the downstream `Dockerfile`. 1426 1427 Any build instruction can be registered as a trigger. 1428 1429 This is useful if you are building an image which will be used as a base 1430 to build other images, for example an application build environment or a 1431 daemon which may be customized with user-specific configuration. 1432 1433 For example, if your image is a reusable Python application builder, it 1434 will require application source code to be added in a particular 1435 directory, and it might require a build script to be called *after* 1436 that. You can't just call `ADD` and `RUN` now, because you don't yet 1437 have access to the application source code, and it will be different for 1438 each application build. You could simply provide application developers 1439 with a boilerplate `Dockerfile` to copy-paste into their application, but 1440 that is inefficient, error-prone and difficult to update because it 1441 mixes with application-specific code. 1442 1443 The solution is to use `ONBUILD` to register advance instructions to 1444 run later, during the next build stage. 1445 1446 Here's how it works: 1447 1448 1. When it encounters an `ONBUILD` instruction, the builder adds a 1449 trigger to the metadata of the image being built. The instruction 1450 does not otherwise affect the current build. 1451 2. At the end of the build, a list of all triggers is stored in the 1452 image manifest, under the key `OnBuild`. They can be inspected with 1453 the `docker inspect` command. 1454 3. Later the image may be used as a base for a new build, using the 1455 `FROM` instruction. As part of processing the `FROM` instruction, 1456 the downstream builder looks for `ONBUILD` triggers, and executes 1457 them in the same order they were registered. If any of the triggers 1458 fail, the `FROM` instruction is aborted which in turn causes the 1459 build to fail. If all triggers succeed, the `FROM` instruction 1460 completes and the build continues as usual. 1461 4. Triggers are cleared from the final image after being executed. In 1462 other words they are not inherited by "grand-children" builds. 1463 1464 For example you might add something like this: 1465 1466 [...] 1467 ONBUILD ADD . /app/src 1468 ONBUILD RUN /usr/local/bin/python-build --dir /app/src 1469 [...] 1470 1471 > **Warning**: Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. 1472 1473 > **Warning**: The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. 1474 1475 ## STOPSIGNAL 1476 1477 STOPSIGNAL signal 1478 1479 The `STOPSIGNAL` instruction sets the system call signal that will be sent to the container to exit. 1480 This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9, 1481 or a signal name in the format SIGNAME, for instance SIGKILL. 1482 1483 ## HEALTHCHECK 1484 1485 The `HEALTHCHECK` instruction has two forms: 1486 1487 * `HEALTHCHECK [OPTIONS] CMD command` (check container health by running a command inside the container) 1488 * `HEALTHCHECK NONE` (disable any healthcheck inherited from the base image) 1489 1490 The `HEALTHCHECK` instruction tells Docker how to test a container to check that 1491 it is still working. This can detect cases such as a web server that is stuck in 1492 an infinite loop and unable to handle new connections, even though the server 1493 process is still running. 1494 1495 When a container has a healthcheck specified, it has a _health status_ in 1496 addition to its normal status. This status is initially `starting`. Whenever a 1497 health check passes, it becomes `healthy` (whatever state it was previously in). 1498 After a certain number of consecutive failures, it becomes `unhealthy`. 1499 1500 The options that can appear before `CMD` are: 1501 1502 * `--interval=DURATION` (default: `30s`) 1503 * `--timeout=DURATION` (default: `30s`) 1504 * `--retries=N` (default: `3`) 1505 1506 The health check will first run **interval** seconds after the container is 1507 started, and then again **interval** seconds after each previous check completes. 1508 1509 If a single run of the check takes longer than **timeout** seconds then the check 1510 is considered to have failed. 1511 1512 It takes **retries** consecutive failures of the health check for the container 1513 to be considered `unhealthy`. 1514 1515 There can only be one `HEALTHCHECK` instruction in a Dockerfile. If you list 1516 more than one then only the last `HEALTHCHECK` will take effect. 1517 1518 The command after the `CMD` keyword can be either a shell command (e.g. `HEALTHCHECK 1519 CMD /bin/check-running`) or an _exec_ array (as with other Dockerfile commands; 1520 see e.g. `ENTRYPOINT` for details). 1521 1522 The command's exit status indicates the health status of the container. 1523 The possible values are: 1524 1525 - 0: success - the container is healthy and ready for use 1526 - 1: unhealthy - the container is not working correctly 1527 - 2: reserved - do not use this exit code 1528 1529 For example, to check every five minutes or so that a web-server is able to 1530 serve the site's main page within three seconds: 1531 1532 HEALTHCHECK --interval=5m --timeout=3s \ 1533 CMD curl -f http://localhost/ || exit 1 1534 1535 To help debug failing probes, any output text (UTF-8 encoded) that the command writes 1536 on stdout or stderr will be stored in the health status and can be queried with 1537 `docker inspect`. Such output should be kept short (only the first 4096 bytes 1538 are stored currently). 1539 1540 When the health status of a container changes, a `health_status` event is 1541 generated with the new status. 1542 1543 The `HEALTHCHECK` feature was added in Docker 1.12. 1544 1545 1546 ## SHELL 1547 1548 SHELL ["executable", "parameters"] 1549 1550 The `SHELL` instruction allows the default shell used for the *shell* form of 1551 commands to be overridden. The default shell on Linux is `["/bin/sh", "-c"]`, and on 1552 Windows is `["cmd", "/S", "/C"]`. The `SHELL` instruction *must* be written in JSON 1553 form in a Dockerfile. 1554 1555 The `SHELL` instruction is particularly useful on Windows where there are 1556 two commonly used and quite different native shells: `cmd` and `powershell`, as 1557 well as alternate shells available including `sh`. 1558 1559 The `SHELL` instruction can appear multiple times. Each `SHELL` instruction overrides 1560 all previous `SHELL` instructions, and affects all subsequent instructions. For example: 1561 1562 FROM windowsservercore 1563 1564 # Executed as cmd /S /C echo default 1565 RUN echo default 1566 1567 # Executed as cmd /S /C powershell -command Write-Host default 1568 RUN powershell -command Write-Host default 1569 1570 # Executed as powershell -command Write-Host hello 1571 SHELL ["powershell", "-command"] 1572 RUN Write-Host hello 1573 1574 # Executed as cmd /S /C echo hello 1575 SHELL ["cmd", "/S"", "/C"] 1576 RUN echo hello 1577 1578 The following instructions can be affected by the `SHELL` instruction when the 1579 *shell* form of them is used in a Dockerfile: `RUN`, `CMD` and `ENTRYPOINT`. 1580 1581 The following example is a common pattern found on Windows which can be 1582 streamlined by using the `SHELL` instruction: 1583 1584 ... 1585 RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 1586 ... 1587 1588 The command invoked by docker will be: 1589 1590 cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" 1591 1592 This is inefficient for two reasons. First, there is an un-necessary cmd.exe command 1593 processor (aka shell) being invoked. Second, each `RUN` instruction in the *shell* 1594 form requires an extra `powershell -command` prefixing the command. 1595 1596 To make this more efficient, one of two mechanisms can be employed. One is to 1597 use the JSON form of the RUN command such as: 1598 1599 ... 1600 RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""] 1601 ... 1602 1603 While the JSON form is unambiguous and does not use the un-necessary cmd.exe, 1604 it does require more verbosity through double-quoting and escaping. The alternate 1605 mechanism is to use the `SHELL` instruction and the *shell* form, 1606 making a more natural syntax for Windows users, especially when combined with 1607 the `escape` parser directive: 1608 1609 # escape=` 1610 1611 FROM windowsservercore 1612 SHELL ["powershell","-command"] 1613 RUN New-Item -ItemType Directory C:\Example 1614 ADD Execute-MyCmdlet.ps1 c:\example\ 1615 RUN c:\example\Execute-MyCmdlet -sample 'hello world' 1616 1617 Resulting in: 1618 1619 PS E:\docker\build\shell> docker build -t shell . 1620 Sending build context to Docker daemon 3.584 kB 1621 Step 1 : FROM windowsservercore 1622 ---> 5bc36a335344 1623 Step 2 : SHELL powershell -command 1624 ---> Running in 87d7a64c9751 1625 ---> 4327358436c1 1626 Removing intermediate container 87d7a64c9751 1627 Step 3 : RUN New-Item -ItemType Directory C:\Example 1628 ---> Running in 3e6ba16b8df9 1629 1630 1631 Directory: C:\ 1632 1633 1634 Mode LastWriteTime Length Name 1635 ---- ------------- ------ ---- 1636 d----- 6/2/2016 2:59 PM Example 1637 1638 1639 ---> 1f1dfdcec085 1640 Removing intermediate container 3e6ba16b8df9 1641 Step 4 : ADD Execute-MyCmdlet.ps1 c:\example\ 1642 ---> 6770b4c17f29 1643 Removing intermediate container b139e34291dc 1644 Step 5 : RUN c:\example\Execute-MyCmdlet -sample 'hello world' 1645 ---> Running in abdcf50dfd1f 1646 Hello from Execute-MyCmdlet.ps1 - passed hello world 1647 ---> ba0e25255fda 1648 Removing intermediate container abdcf50dfd1f 1649 Successfully built ba0e25255fda 1650 PS E:\docker\build\shell> 1651 1652 The `SHELL` instruction could also be used to modify the way in which 1653 a shell operates. For example, using `SHELL cmd /S /C /V:ON|OFF` on Windows, delayed 1654 environment variable expansion semantics could be modified. 1655 1656 The `SHELL` instruction can also be used on Linux should an alternate shell be 1657 required such `zsh`, `csh`, `tcsh` and others. 1658 1659 The `SHELL` feature was added in Docker 1.12. 1660 1661 ## Dockerfile examples 1662 1663 Below you can see some examples of Dockerfile syntax. If you're interested in 1664 something more realistic, take a look at the list of [Dockerization examples](../examples/index.md). 1665 1666 ``` 1667 # Nginx 1668 # 1669 # VERSION 0.0.1 1670 1671 FROM ubuntu 1672 MAINTAINER Victor Vieux <victor@docker.com> 1673 1674 LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0" 1675 RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server 1676 ``` 1677 1678 ``` 1679 # Firefox over VNC 1680 # 1681 # VERSION 0.3 1682 1683 FROM ubuntu 1684 1685 # Install vnc, xvfb in order to create a 'fake' display and firefox 1686 RUN apt-get update && apt-get install -y x11vnc xvfb firefox 1687 RUN mkdir ~/.vnc 1688 # Setup a password 1689 RUN x11vnc -storepasswd 1234 ~/.vnc/passwd 1690 # Autostart firefox (might not be the best way, but it does the trick) 1691 RUN bash -c 'echo "firefox" >> /.bashrc' 1692 1693 EXPOSE 5900 1694 CMD ["x11vnc", "-forever", "-usepw", "-create"] 1695 ``` 1696 1697 ``` 1698 # Multiple images example 1699 # 1700 # VERSION 0.1 1701 1702 FROM ubuntu 1703 RUN echo foo > bar 1704 # Will output something like ===> 907ad6c2736f 1705 1706 FROM ubuntu 1707 RUN echo moo > oink 1708 # Will output something like ===> 695d7793cbe4 1709 1710 # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with 1711 # /oink. 1712 ```