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