github.com/tompao/docker@v1.9.1/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 = "mn_reference" 8 +++ 9 <![end-metadata]--> 10 11 # Dockerfile reference 12 13 Docker can build images automatically by reading the instructions from a 14 `Dockerfile`. A `Dockerfile` is a text document that contains all the commands a 15 user could call on the command line to assemble an image. Using `docker build` 16 users can create an automated build that executes several command-line 17 instructions in succession. 18 19 This page describes the commands you can use in a `Dockerfile`. When you are 20 done reading this page, refer to the [`Dockerfile` Best 21 Practices](../articles/dockerfile_best-practices.md) for a tip-oriented guide. 22 23 ## Usage 24 25 The [`docker build`](commandline/build.md) command builds an image from 26 a `Dockerfile` and a *context*. The build's context is the files at a specified 27 location `PATH` or `URL`. The `PATH` is a directory on your local filesystem. 28 The `URL` is a the location of a Git repository. 29 30 A context is processed recursively. So, a `PATH` includes any subdirectories and 31 the `URL` includes the repository and its submodules. A simple build command 32 that uses the current directory as context: 33 34 $ docker build . 35 Sending build context to Docker daemon 6.51 MB 36 ... 37 38 The build is run by the Docker daemon, not by the CLI. The first thing a build 39 process does is send the entire context (recursively) to the daemon. In most 40 cases, it's best to start with an empty directory as context and keep your 41 Dockerfile in that directory. Add only the files needed for building the 42 Dockerfile. 43 44 >**Warning**: Do not use your root directory, `/`, as the `PATH` as it causes 45 >the build to transfer the entire contents of your hard drive to the Docker 46 >daemon. 47 48 To use a file in the build context, the `Dockerfile` refers to the file specified 49 in an instruction, for example, a `COPY` instruction. To increase the build's 50 performance, exclude files and directories by adding a `.dockerignore` file to 51 the context directory. For information about how to [create a `.dockerignore` 52 file](#dockerignore-file) see the documentation on this page. 53 54 Traditionally, the `Dockerfile` is called `Dockerfile` and located in the root 55 of the context. You use the `-f` flag with `docker build` to point to a Dockerfile 56 anywhere in your file system. 57 58 $ docker build -f /path/to/a/Dockerfile . 59 60 You can specify a repository and tag at which to save the new image if 61 the build succeeds: 62 63 $ docker build -t shykes/myapp . 64 65 The Docker daemon runs the instructions in the `Dockerfile` one-by-one, 66 committing the result of each instruction 67 to a new image if necessary, before finally outputting the ID of your 68 new image. The Docker daemon will automatically clean up the context you 69 sent. 70 71 Note that each instruction is run independently, and causes a new image 72 to be created - so `RUN cd /tmp` will not have any effect on the next 73 instructions. 74 75 Whenever possible, Docker will re-use the intermediate images (cache), 76 to accelerate the `docker build` process significantly. This is indicated by 77 the `Using cache` message in the console output. 78 (For more information, see the [Build cache section](../articles/dockerfile_best-practices.md#build-cache)) in the 79 `Dockerfile` best practices guide: 80 81 $ docker build -t svendowideit/ambassador . 82 Sending build context to Docker daemon 15.36 kB 83 Step 0 : FROM alpine:3.2 84 ---> 31f630c65071 85 Step 1 : MAINTAINER SvenDowideit@home.org.au 86 ---> Using cache 87 ---> 2a1c91448f5f 88 Step 2 : RUN apk update && apk add socat && rm -r /var/cache/ 89 ---> Using cache 90 ---> 21ed6e7fbb73 91 Step 3 : CMD env | grep _TCP= | sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat -t 100000000 TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \& wait/' | sh 92 ---> Using cache 93 ---> 7ea8aef582cc 94 Successfully built 7ea8aef582cc 95 96 When you're done with your build, you're ready to look into [*Pushing a 97 repository to its registry*](../userguide/dockerrepos.md#contributing-to-docker-hub). 98 99 ## Format 100 101 Here is the format of the `Dockerfile`: 102 103 # Comment 104 INSTRUCTION arguments 105 106 The instruction is not case-sensitive, however convention is for them to 107 be UPPERCASE in order to distinguish them from arguments more easily. 108 109 Docker runs the instructions in a `Dockerfile` in order. **The 110 first instruction must be \`FROM\`** in order to specify the [*Base 111 Image*](glossary.md#base-image) from which you are building. 112 113 Docker will treat lines that *begin* with `#` as a 114 comment. A `#` marker anywhere else in the line will 115 be treated as an argument. This allows statements like: 116 117 # Comment 118 RUN echo 'we are running some # of cool things' 119 120 Here is the set of instructions you can use in a `Dockerfile` for building 121 images. 122 123 ### Environment replacement 124 125 Environment variables (declared with [the `ENV` statement](#env)) can also be 126 used in certain instructions as variables to be interpreted by the 127 `Dockerfile`. Escapes are also handled for including variable-like syntax 128 into a statement literally. 129 130 Environment variables are notated in the `Dockerfile` either with 131 `$variable_name` or `${variable_name}`. They are treated equivalently and the 132 brace syntax is typically used to address issues with variable names with no 133 whitespace, like `${foo}_bar`. 134 135 The `${variable_name}` syntax also supports a few of the standard `bash` 136 modifiers as specified below: 137 138 * `${variable:-word}` indicates that if `variable` is set then the result 139 will be that value. If `variable` is not set then `word` will be the result. 140 * `${variable:+word}` indicates that if `variable` is set then `word` will be 141 the result, otherwise the result is the empty string. 142 143 In all cases, `word` can be any string, including additional environment 144 variables. 145 146 Escaping is possible by adding a `\` before the variable: `\$foo` or `\${foo}`, 147 for example, will translate to `$foo` and `${foo}` literals respectively. 148 149 Example (parsed representation is displayed after the `#`): 150 151 FROM busybox 152 ENV foo /bar 153 WORKDIR ${foo} # WORKDIR /bar 154 ADD . $foo # ADD . /bar 155 COPY \$foo /quux # COPY $foo /quux 156 157 Environment variables are supported by the following list of instructions in 158 the `Dockerfile`: 159 160 * `ADD` 161 * `COPY` 162 * `ENV` 163 * `EXPOSE` 164 * `LABEL` 165 * `USER` 166 * `WORKDIR` 167 * `VOLUME` 168 * `STOPSIGNAL` 169 170 as well as: 171 172 * `ONBUILD` (when combined with one of the supported instructions above) 173 174 > **Note**: 175 > prior to 1.4, `ONBUILD` instructions did **NOT** support environment 176 > variable, even when combined with any of the instructions listed above. 177 178 Environment variable substitution will use the same value for each variable 179 throughout the entire command. In other words, in this example: 180 181 ENV abc=hello 182 ENV abc=bye def=$abc 183 ENV ghi=$abc 184 185 will result in `def` having a value of `hello`, not `bye`. However, 186 `ghi` will have a value of `bye` because it is not part of the same command 187 that set `abc` to `bye`. 188 189 ### .dockerignore file 190 191 Before the docker CLI sends the context to the docker daemon, it looks 192 for a file named `.dockerignore` in the root directory of the context. 193 If this file exists, the CLI modifies the context to exclude files and 194 directories that match patterns in it. This helps to avoid 195 unnecessarily sending large or sensitive files and directories to the 196 daemon and potentially adding them to images using `ADD` or `COPY`. 197 198 The CLI interprets the `.dockerignore` file as a newline-separated 199 list of patterns similar to the file globs of Unix shells. For the 200 purposes of matching, the root of the context is considered to be both 201 the working and the root directory. For example, the patterns 202 `/foo/bar` and `foo/bar` both exclude a file or directory named `bar` 203 in the `foo` subdirectory of `PATH` or in the root of the git 204 repository located at `URL`. Neither excludes anything else. 205 206 Here is an example `.dockerignore` file: 207 208 ``` 209 */temp* 210 */*/temp* 211 temp? 212 ``` 213 214 This file causes the following build behavior: 215 216 | Rule | Behavior | 217 |----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 218 | `*/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`. | 219 | `*/*/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. | 220 | `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. 221 222 223 Matching is done using Go's 224 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. A 225 preprocessing step removes leading and trailing whitespace and 226 eliminates `.` and `..` elements using Go's 227 [filepath.Clean](http://golang.org/pkg/path/filepath/#Clean). Lines 228 that are blank after preprocessing are ignored. 229 230 Lines starting with `!` (exclamation mark) can be used to make exceptions 231 to exclusions. The following is an example `.dockerignore` file that 232 uses this mechanism: 233 234 ``` 235 *.md 236 !README.md 237 ``` 238 239 All markdown files *except* `README.md` are excluded from the context. 240 241 The placement of `!` exception rules influences the behavior: the last 242 line of the `.dockerignore` that matches a particular file determines 243 whether it is included or excluded. Consider the following example: 244 245 ``` 246 *.md 247 !README*.md 248 README-secret.md 249 ``` 250 251 No markdown files are included in the context except README files other than 252 `README-secret.md`. 253 254 Now consider this example: 255 256 ``` 257 *.md 258 README-secret.md 259 !README*.md 260 ``` 261 262 All of the README files are included. The middle line has no effect because 263 `!README*.md` matches `README-secret.md` and comes last. 264 265 You can even use the `.dockerignore` file to exclude the `Dockerfile` 266 and `.dockerignore` files. These files are still sent to the daemon 267 because it needs them to do its job. But the `ADD` and `COPY` commands 268 do not copy them to the the image. 269 270 Finally, you may want to specify which files to include in the 271 context, rather than which to exclude. To achieve this, specify `*` as 272 the first pattern, followed by one or more `!` exception patterns. 273 274 **Note**: For historical reasons, the pattern `.` is ignored. 275 276 ## FROM 277 278 FROM <image> 279 280 Or 281 282 FROM <image>:<tag> 283 284 Or 285 286 FROM <image>@<digest> 287 288 The `FROM` instruction sets the [*Base Image*](glossary.md#base-image) 289 for subsequent instructions. As such, a valid `Dockerfile` must have `FROM` as 290 its first instruction. The image can be any valid image – it is especially easy 291 to start by **pulling an image** from the [*Public Repositories*](../userguide/dockerrepos.md). 292 293 - `FROM` must be the first non-comment instruction in the `Dockerfile`. 294 295 - `FROM` can appear multiple times within a single `Dockerfile` in order to create 296 multiple images. Simply make a note of the last image ID output by the commit 297 before each new `FROM` command. 298 299 - The `tag` or `digest` values are optional. If you omit either of them, the builder 300 assumes a `latest` by default. The builder returns an error if it cannot match 301 the `tag` value. 302 303 ## MAINTAINER 304 305 MAINTAINER <name> 306 307 The `MAINTAINER` instruction allows you to set the *Author* field of the 308 generated images. 309 310 ## RUN 311 312 RUN has 2 forms: 313 314 - `RUN <command>` (*shell* form, the command is run in a shell - `/bin/sh -c`) 315 - `RUN ["executable", "param1", "param2"]` (*exec* form) 316 317 The `RUN` instruction will execute any commands in a new layer on top of the 318 current image and commit the results. The resulting committed image will be 319 used for the next step in the `Dockerfile`. 320 321 Layering `RUN` instructions and generating commits conforms to the core 322 concepts of Docker where commits are cheap and containers can be created from 323 any point in an image's history, much like source control. 324 325 The *exec* form makes it possible to avoid shell string munging, and to `RUN` 326 commands using a base image that does not contain `/bin/sh`. 327 328 In the *shell* form you can use a `\` (backslash) to continue a single 329 RUN instruction onto the next line. For example, consider these two lines: 330 ``` 331 RUN /bin/bash -c 'source $HOME/.bashrc ;\ 332 echo $HOME' 333 ``` 334 Together they are equivalent to this single line: 335 ``` 336 RUN /bin/bash -c 'source $HOME/.bashrc ; echo $HOME' 337 ``` 338 339 > **Note**: 340 > To use a different shell, other than '/bin/sh', use the *exec* form 341 > passing in the desired shell. For example, 342 > `RUN ["/bin/bash", "-c", "echo hello"]` 343 344 > **Note**: 345 > The *exec* form is parsed as a JSON array, which means that 346 > you must use double-quotes (") around words not single-quotes ('). 347 348 > **Note**: 349 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 350 > This means that normal shell processing does not happen. For example, 351 > `RUN [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 352 > If you want shell processing then either use the *shell* form or execute 353 > a shell directly, for example: `RUN [ "sh", "-c", "echo", "$HOME" ]`. 354 355 The cache for `RUN` instructions isn't invalidated automatically during 356 the next build. The cache for an instruction like 357 `RUN apt-get dist-upgrade -y` will be reused during the next build. The 358 cache for `RUN` instructions can be invalidated by using the `--no-cache` 359 flag, for example `docker build --no-cache`. 360 361 See the [`Dockerfile` Best Practices 362 guide](../articles/dockerfile_best-practices.md#build-cache) for more information. 363 364 The cache for `RUN` instructions can be invalidated by `ADD` instructions. See 365 [below](#add) for details. 366 367 ### Known issues (RUN) 368 369 - [Issue 783](https://github.com/docker/docker/issues/783) is about file 370 permissions problems that can occur when using the AUFS file system. You 371 might notice it during an attempt to `rm` a file, for example. 372 373 For systems that have recent aufs version (i.e., `dirperm1` mount option can 374 be set), docker will attempt to fix the issue automatically by mounting 375 the layers with `dirperm1` option. More details on `dirperm1` option can be 376 found at [`aufs` man page](http://aufs.sourceforge.net/aufs3/man.html) 377 378 If your system doesn't have support for `dirperm1`, the issue describes a workaround. 379 380 ## CMD 381 382 The `CMD` instruction has three forms: 383 384 - `CMD ["executable","param1","param2"]` (*exec* form, this is the preferred form) 385 - `CMD ["param1","param2"]` (as *default parameters to ENTRYPOINT*) 386 - `CMD command param1 param2` (*shell* form) 387 388 There can only be one `CMD` instruction in a `Dockerfile`. If you list more than one `CMD` 389 then only the last `CMD` will take effect. 390 391 **The main purpose of a `CMD` is to provide defaults for an executing 392 container.** These defaults can include an executable, or they can omit 393 the executable, in which case you must specify an `ENTRYPOINT` 394 instruction as well. 395 396 > **Note**: 397 > If `CMD` is used to provide default arguments for the `ENTRYPOINT` 398 > instruction, both the `CMD` and `ENTRYPOINT` instructions should be specified 399 > with the JSON array format. 400 401 > **Note**: 402 > The *exec* form is parsed as a JSON array, which means that 403 > you must use double-quotes (") around words not single-quotes ('). 404 405 > **Note**: 406 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 407 > This means that normal shell processing does not happen. For example, 408 > `CMD [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 409 > If you want shell processing then either use the *shell* form or execute 410 > a shell directly, for example: `CMD [ "sh", "-c", "echo", "$HOME" ]`. 411 412 When used in the shell or exec formats, the `CMD` instruction sets the command 413 to be executed when running the image. 414 415 If you use the *shell* form of the `CMD`, then the `<command>` will execute in 416 `/bin/sh -c`: 417 418 FROM ubuntu 419 CMD echo "This is a test." | wc - 420 421 If you want to **run your** `<command>` **without a shell** then you must 422 express the command as a JSON array and give the full path to the executable. 423 **This array form is the preferred format of `CMD`.** Any additional parameters 424 must be individually expressed as strings in the array: 425 426 FROM ubuntu 427 CMD ["/usr/bin/wc","--help"] 428 429 If you would like your container to run the same executable every time, then 430 you should consider using `ENTRYPOINT` in combination with `CMD`. See 431 [*ENTRYPOINT*](#entrypoint). 432 433 If the user specifies arguments to `docker run` then they will override the 434 default specified in `CMD`. 435 436 > **Note**: 437 > don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits 438 > the result; `CMD` does not execute anything at build time, but specifies 439 > the intended command for the image. 440 441 ## LABEL 442 443 LABEL <key>=<value> <key>=<value> <key>=<value> ... 444 445 The `LABEL` instruction adds metadata to an image. A `LABEL` is a 446 key-value pair. To include spaces within a `LABEL` value, use quotes and 447 backslashes as you would in command-line parsing. A few usage examples: 448 449 LABEL "com.example.vendor"="ACME Incorporated" 450 LABEL com.example.label-with-value="foo" 451 LABEL version="1.0" 452 LABEL description="This text illustrates \ 453 that label-values can span multiple lines." 454 455 An image can have more than one label. To specify multiple labels, 456 Docker recommends combining labels into a single `LABEL` instruction where 457 possible. Each `LABEL` instruction produces a new layer which can result in an 458 inefficient image if you use many labels. This example results in a single image 459 layer. 460 461 LABEL multi.label1="value1" multi.label2="value2" other="value3" 462 463 The above can also be written as: 464 465 LABEL multi.label1="value1" \ 466 multi.label2="value2" \ 467 other="value3" 468 469 Labels are additive including `LABEL`s in `FROM` images. If Docker 470 encounters a label/key that already exists, the new value overrides any previous 471 labels with identical keys. 472 473 To view an image's labels, use the `docker inspect` command. 474 475 "Labels": { 476 "com.example.vendor": "ACME Incorporated" 477 "com.example.label-with-value": "foo", 478 "version": "1.0", 479 "description": "This text illustrates that label-values can span multiple lines.", 480 "multi.label1": "value1", 481 "multi.label2": "value2", 482 "other": "value3" 483 }, 484 485 ## EXPOSE 486 487 EXPOSE <port> [<port>...] 488 489 The `EXPOSE` instruction informs Docker that the container listens on the 490 specified network ports at runtime. `EXPOSE` does not make the ports of the 491 container accessible to the host. To do that, you must use either the `-p` flag 492 to publish a range of ports or the `-P` flag to publish all of the exposed 493 ports. You can expose one port number and publish it externally under another 494 number. 495 496 To set up port redirection on the host system, see [using the -P 497 flag](run.md#expose-incoming-ports). The Docker network feature supports 498 creating networks without the need to expose ports within the network, for 499 detailed information see the [overview of this 500 feature](../userguide/networking/index.md)). 501 502 ## ENV 503 504 ENV <key> <value> 505 ENV <key>=<value> ... 506 507 The `ENV` instruction sets the environment variable `<key>` to the value 508 `<value>`. This value will be in the environment of all "descendent" 509 `Dockerfile` commands and can be [replaced inline](#environment-replacement) in 510 many as well. 511 512 The `ENV` instruction has two forms. The first form, `ENV <key> <value>`, 513 will set a single variable to a value. The entire string after the first 514 space will be treated as the `<value>` - including characters such as 515 spaces and quotes. 516 517 The second form, `ENV <key>=<value> ...`, allows for multiple variables to 518 be set at one time. Notice that the second form uses the equals sign (=) 519 in the syntax, while the first form does not. Like command line parsing, 520 quotes and backslashes can be used to include spaces within values. 521 522 For example: 523 524 ENV myName="John Doe" myDog=Rex\ The\ Dog \ 525 myCat=fluffy 526 527 and 528 529 ENV myName John Doe 530 ENV myDog Rex The Dog 531 ENV myCat fluffy 532 533 will yield the same net results in the final container, but the first form 534 is preferred because it produces a single cache layer. 535 536 The environment variables set using `ENV` will persist when a container is run 537 from the resulting image. You can view the values using `docker inspect`, and 538 change them using `docker run --env <key>=<value>`. 539 540 > **Note**: 541 > Environment persistence can cause unexpected side effects. For example, 542 > setting `ENV DEBIAN_FRONTEND noninteractive` may confuse apt-get 543 > users on a Debian-based image. To set a value for a single command, use 544 > `RUN <key>=<value> <command>`. 545 546 ## ADD 547 548 ADD has two forms: 549 550 - `ADD <src>... <dest>` 551 - `ADD ["<src>",... "<dest>"]` (this form is required for paths containing 552 whitespace) 553 554 The `ADD` instruction copies new files, directories or remote file URLs from `<src>` 555 and adds them to the filesystem of the container at the path `<dest>`. 556 557 Multiple `<src>` resource may be specified but if they are files or 558 directories then they must be relative to the source directory that is 559 being built (the context of the build). 560 561 Each `<src>` may contain wildcards and matching will be done using Go's 562 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 563 564 ADD hom* /mydir/ # adds all files starting with "hom" 565 ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 566 567 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 568 the source will be copied inside the destination container. 569 570 ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 571 ADD test /absoluteDir # adds "test" to /absoluteDir 572 573 All new files and directories are created with a UID and GID of 0. 574 575 In the case where `<src>` is a remote file URL, the destination will 576 have permissions of 600. If the remote file being retrieved has an HTTP 577 `Last-Modified` header, the timestamp from that header will be used 578 to set the `mtime` on the destination file. However, like any other file 579 processed during an `ADD`, `mtime` will not be included in the determination 580 of whether or not the file has changed and the cache should be updated. 581 582 > **Note**: 583 > If you build by passing a `Dockerfile` through STDIN (`docker 584 > build - < somefile`), there is no build context, so the `Dockerfile` 585 > can only contain a URL based `ADD` instruction. You can also pass a 586 > compressed archive through STDIN: (`docker build - < archive.tar.gz`), 587 > the `Dockerfile` at the root of the archive and the rest of the 588 > archive will get used at the context of the build. 589 590 > **Note**: 591 > If your URL files are protected using authentication, you 592 > will need to use `RUN wget`, `RUN curl` or use another tool from 593 > within the container as the `ADD` instruction does not support 594 > authentication. 595 596 > **Note**: 597 > The first encountered `ADD` instruction will invalidate the cache for all 598 > following instructions from the Dockerfile if the contents of `<src>` have 599 > changed. This includes invalidating the cache for `RUN` instructions. 600 > See the [`Dockerfile` Best Practices 601 guide](../articles/dockerfile_best-practices.md#build-cache) for more information. 602 603 604 `ADD` obeys the following rules: 605 606 - The `<src>` path must be inside the *context* of the build; 607 you cannot `ADD ../something /something`, because the first step of a 608 `docker build` is to send the context directory (and subdirectories) to the 609 docker daemon. 610 611 - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a 612 file is downloaded from the URL and copied to `<dest>`. 613 614 - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the 615 filename is inferred from the URL and the file is downloaded to 616 `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would 617 create the file `/foobar`. The URL must have a nontrivial path so that an 618 appropriate filename can be discovered in this case (`http://example.com` 619 will not work). 620 621 - If `<src>` is a directory, the entire contents of the directory are copied, 622 including filesystem metadata. 623 624 > **Note**: 625 > The directory itself is not copied, just its contents. 626 627 - If `<src>` is a *local* tar archive in a recognized compression format 628 (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources 629 from *remote* URLs are **not** decompressed. When a directory is copied or 630 unpacked, it has the same behavior as `tar -x`: the result is the union of: 631 632 1. Whatever existed at the destination path and 633 2. The contents of the source tree, with conflicts resolved in favor 634 of "2." on a file-by-file basis. 635 636 - If `<src>` is any other kind of file, it is copied individually along with 637 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 638 will be considered a directory and the contents of `<src>` will be written 639 at `<dest>/base(<src>)`. 640 641 - If multiple `<src>` resources are specified, either directly or due to the 642 use of a wildcard, then `<dest>` must be a directory, and it must end with 643 a slash `/`. 644 645 - If `<dest>` does not end with a trailing slash, it will be considered a 646 regular file and the contents of `<src>` will be written at `<dest>`. 647 648 - If `<dest>` doesn't exist, it is created along with all missing directories 649 in its path. 650 651 ## COPY 652 653 COPY has two forms: 654 655 - `COPY <src>... <dest>` 656 - `COPY ["<src>",... "<dest>"]` (this form is required for paths containing 657 whitespace) 658 659 The `COPY` instruction copies new files or directories from `<src>` 660 and adds them to the filesystem of the container at the path `<dest>`. 661 662 Multiple `<src>` resource may be specified but they must be relative 663 to the source directory that is being built (the context of the build). 664 665 Each `<src>` may contain wildcards and matching will be done using Go's 666 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 667 668 COPY hom* /mydir/ # adds all files starting with "hom" 669 COPY hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 670 671 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 672 the source will be copied inside the destination container. 673 674 COPY test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 675 COPY test /absoluteDir # adds "test" to /absoluteDir 676 677 All new files and directories are created with a UID and GID of 0. 678 679 > **Note**: 680 > If you build using STDIN (`docker build - < somefile`), there is no 681 > build context, so `COPY` can't be used. 682 683 `COPY` obeys the following rules: 684 685 - The `<src>` path must be inside the *context* of the build; 686 you cannot `COPY ../something /something`, because the first step of a 687 `docker build` is to send the context directory (and subdirectories) to the 688 docker daemon. 689 690 - If `<src>` is a directory, the entire contents of the directory are copied, 691 including filesystem metadata. 692 693 > **Note**: 694 > The directory itself is not copied, just its contents. 695 696 - If `<src>` is any other kind of file, it is copied individually along with 697 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 698 will be considered a directory and the contents of `<src>` will be written 699 at `<dest>/base(<src>)`. 700 701 - If multiple `<src>` resources are specified, either directly or due to the 702 use of a wildcard, then `<dest>` must be a directory, and it must end with 703 a slash `/`. 704 705 - If `<dest>` does not end with a trailing slash, it will be considered a 706 regular file and the contents of `<src>` will be written at `<dest>`. 707 708 - If `<dest>` doesn't exist, it is created along with all missing directories 709 in its path. 710 711 ## ENTRYPOINT 712 713 ENTRYPOINT has two forms: 714 715 - `ENTRYPOINT ["executable", "param1", "param2"]` 716 (*exec* form, preferred) 717 - `ENTRYPOINT command param1 param2` 718 (*shell* form) 719 720 An `ENTRYPOINT` allows you to configure a container that will run as an executable. 721 722 For example, the following will start nginx with its default content, listening 723 on port 80: 724 725 docker run -i -t --rm -p 80:80 nginx 726 727 Command line arguments to `docker run <image>` will be appended after all 728 elements in an *exec* form `ENTRYPOINT`, and will override all elements specified 729 using `CMD`. 730 This allows arguments to be passed to the entry point, i.e., `docker run <image> -d` 731 will pass the `-d` argument to the entry point. 732 You can override the `ENTRYPOINT` instruction using the `docker run --entrypoint` 733 flag. 734 735 The *shell* form prevents any `CMD` or `run` command line arguments from being 736 used, but has the disadvantage that your `ENTRYPOINT` will be started as a 737 subcommand of `/bin/sh -c`, which does not pass signals. 738 This means that the executable will not be the container's `PID 1` - and 739 will _not_ receive Unix signals - so your executable will not receive a 740 `SIGTERM` from `docker stop <container>`. 741 742 Only the last `ENTRYPOINT` instruction in the `Dockerfile` will have an effect. 743 744 ### Exec form ENTRYPOINT example 745 746 You can use the *exec* form of `ENTRYPOINT` to set fairly stable default commands 747 and arguments and then use either form of `CMD` to set additional defaults that 748 are more likely to be changed. 749 750 FROM ubuntu 751 ENTRYPOINT ["top", "-b"] 752 CMD ["-c"] 753 754 When you run the container, you can see that `top` is the only process: 755 756 $ docker run -it --rm --name test top -H 757 top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05 758 Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie 759 %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 760 KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers 761 KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem 762 763 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 764 1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top 765 766 To examine the result further, you can use `docker exec`: 767 768 $ docker exec -it test ps aux 769 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 770 root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H 771 root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux 772 773 And you can gracefully request `top` to shut down using `docker stop test`. 774 775 The following `Dockerfile` shows using the `ENTRYPOINT` to run Apache in the 776 foreground (i.e., as `PID 1`): 777 778 ``` 779 FROM debian:stable 780 RUN apt-get update && apt-get install -y --force-yes apache2 781 EXPOSE 80 443 782 VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"] 783 ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] 784 ``` 785 786 If you need to write a starter script for a single executable, you can ensure that 787 the final executable receives the Unix signals by using `exec` and `gosu` 788 commands: 789 790 ```bash 791 #!/bin/bash 792 set -e 793 794 if [ "$1" = 'postgres' ]; then 795 chown -R postgres "$PGDATA" 796 797 if [ -z "$(ls -A "$PGDATA")" ]; then 798 gosu postgres initdb 799 fi 800 801 exec gosu postgres "$@" 802 fi 803 804 exec "$@" 805 ``` 806 807 Lastly, if you need to do some extra cleanup (or communicate with other containers) 808 on shutdown, or are co-ordinating more than one executable, you may need to ensure 809 that the `ENTRYPOINT` script receives the Unix signals, passes them on, and then 810 does some more work: 811 812 ``` 813 #!/bin/sh 814 # Note: I've written this using sh so it works in the busybox container too 815 816 # USE the trap if you need to also do manual cleanup after the service is stopped, 817 # or need to start multiple services in the one container 818 trap "echo TRAPed signal" HUP INT QUIT KILL TERM 819 820 # start service in background here 821 /usr/sbin/apachectl start 822 823 echo "[hit enter key to exit] or run 'docker stop <container>'" 824 read 825 826 # stop service and clean up here 827 echo "stopping apache" 828 /usr/sbin/apachectl stop 829 830 echo "exited $0" 831 ``` 832 833 If you run this image with `docker run -it --rm -p 80:80 --name test apache`, 834 you can then examine the container's processes with `docker exec`, or `docker top`, 835 and then ask the script to stop Apache: 836 837 ```bash 838 $ docker exec -it test ps aux 839 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 840 root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123 cmd cmd2 841 root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start 842 www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 843 www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 844 root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux 845 $ docker top test 846 PID USER COMMAND 847 10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2 848 10054 root /usr/sbin/apache2 -k start 849 10055 33 /usr/sbin/apache2 -k start 850 10056 33 /usr/sbin/apache2 -k start 851 $ /usr/bin/time docker stop test 852 test 853 real 0m 0.27s 854 user 0m 0.03s 855 sys 0m 0.03s 856 ``` 857 858 > **Note:** you can over ride the `ENTRYPOINT` setting using `--entrypoint`, 859 > but this can only set the binary to *exec* (no `sh -c` will be used). 860 861 > **Note**: 862 > The *exec* form is parsed as a JSON array, which means that 863 > you must use double-quotes (") around words not single-quotes ('). 864 865 > **Note**: 866 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 867 > This means that normal shell processing does not happen. For example, 868 > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 869 > If you want shell processing then either use the *shell* form or execute 870 > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo", "$HOME" ]`. 871 > Variables that are defined in the `Dockerfile`using `ENV`, will be substituted by 872 > the `Dockerfile` parser. 873 874 ### Shell form ENTRYPOINT example 875 876 You can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`. 877 This form will use shell processing to substitute shell environment variables, 878 and will ignore any `CMD` or `docker run` command line arguments. 879 To ensure that `docker stop` will signal any long running `ENTRYPOINT` executable 880 correctly, you need to remember to start it with `exec`: 881 882 FROM ubuntu 883 ENTRYPOINT exec top -b 884 885 When you run this image, you'll see the single `PID 1` process: 886 887 $ docker run -it --rm --name test top 888 Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached 889 CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq 890 Load average: 0.08 0.03 0.05 2/98 6 891 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 892 1 0 root R 3164 0% 0% top -b 893 894 Which will exit cleanly on `docker stop`: 895 896 $ /usr/bin/time docker stop test 897 test 898 real 0m 0.20s 899 user 0m 0.02s 900 sys 0m 0.04s 901 902 If you forget to add `exec` to the beginning of your `ENTRYPOINT`: 903 904 FROM ubuntu 905 ENTRYPOINT top -b 906 CMD --ignored-param1 907 908 You can then run it (giving it a name for the next step): 909 910 $ docker run -it --name test top --ignored-param2 911 Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached 912 CPU: 9% usr 2% sys 0% nic 88% idle 0% io 0% irq 0% sirq 913 Load average: 0.01 0.02 0.05 2/101 7 914 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 915 1 0 root S 3168 0% 0% /bin/sh -c top -b cmd cmd2 916 7 1 root R 3164 0% 0% top -b 917 918 You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. 919 920 If you then run `docker stop test`, the container will not exit cleanly - the 921 `stop` command will be forced to send a `SIGKILL` after the timeout: 922 923 $ docker exec -it test ps aux 924 PID USER COMMAND 925 1 root /bin/sh -c top -b cmd cmd2 926 7 root top -b 927 8 root ps aux 928 $ /usr/bin/time docker stop test 929 test 930 real 0m 10.19s 931 user 0m 0.04s 932 sys 0m 0.03s 933 934 ## VOLUME 935 936 VOLUME ["/data"] 937 938 The `VOLUME` instruction creates a mount point with the specified name 939 and marks it as holding externally mounted volumes from native host or other 940 containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain 941 string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log 942 /var/db`. For more information/examples and mounting instructions via the 943 Docker client, refer to 944 [*Share Directories via Volumes*](../userguide/dockervolumes.md#mount-a-host-directory-as-a-data-volume) 945 documentation. 946 947 The `docker run` command initializes the newly created volume with any data 948 that exists at the specified location within the base image. For example, 949 consider the following Dockerfile snippet: 950 951 FROM ubuntu 952 RUN mkdir /myvol 953 RUN echo "hello world" > /myvol/greeting 954 VOLUME /myvol 955 956 This Dockerfile results in an image that causes `docker run`, to 957 create a new mount point at `/myvol` and copy the `greeting` file 958 into the newly created volume. 959 960 > **Note**: 961 > If any build steps change the data within the volume after it has been 962 > declared, those changes will be discarded. 963 964 > **Note**: 965 > The list is parsed as a JSON array, which means that 966 > you must use double-quotes (") around words not single-quotes ('). 967 968 ## USER 969 970 USER daemon 971 972 The `USER` instruction sets the user name or UID to use when running the image 973 and for any `RUN`, `CMD` and `ENTRYPOINT` instructions that follow it in the 974 `Dockerfile`. 975 976 ## WORKDIR 977 978 WORKDIR /path/to/workdir 979 980 The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, 981 `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. 982 983 It can be used multiple times in the one `Dockerfile`. If a relative path 984 is provided, it will be relative to the path of the previous `WORKDIR` 985 instruction. For example: 986 987 WORKDIR /a 988 WORKDIR b 989 WORKDIR c 990 RUN pwd 991 992 The output of the final `pwd` command in this `Dockerfile` would be 993 `/a/b/c`. 994 995 The `WORKDIR` instruction can resolve environment variables previously set using 996 `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. 997 For example: 998 999 ENV DIRPATH /path 1000 WORKDIR $DIRPATH/$DIRNAME 1001 RUN pwd 1002 1003 The output of the final `pwd` command in this `Dockerfile` would be 1004 `/path/$DIRNAME` 1005 1006 ## ARG 1007 1008 ARG <name>[=<default value>] 1009 1010 The `ARG` instruction defines a variable that users can pass at build-time to 1011 the builder with the `docker build` command using the `--build-arg 1012 <varname>=<value>` flag. If a user specifies a build argument that was not 1013 defined in the Dockerfile, the build outputs an error. 1014 1015 ``` 1016 One or more build-args were not consumed, failing build. 1017 ``` 1018 1019 The Dockerfile author can define a single variable by specifying `ARG` once or many 1020 variables by specifying `ARG` more than once. For example, a valid Dockerfile: 1021 1022 ``` 1023 FROM busybox 1024 ARG user1 1025 ARG buildno 1026 ... 1027 ``` 1028 1029 A Dockerfile author may optionally specify a default value for an `ARG` instruction: 1030 1031 ``` 1032 FROM busybox 1033 ARG user1=someuser 1034 ARG buildno=1 1035 ... 1036 ``` 1037 1038 If an `ARG` value has a default and if there is no value passed at build-time, the 1039 builder uses the default. 1040 1041 An `ARG` variable definition comes into effect from the line on which it is 1042 defined in the `Dockerfile` not from the argument's use on the command-line or 1043 elsewhere. For example, consider this Dockerfile: 1044 1045 ``` 1046 1 FROM busybox 1047 2 USER ${user:-some_user} 1048 3 ARG user 1049 4 USER $user 1050 ... 1051 ``` 1052 A user builds this file by calling: 1053 1054 ``` 1055 $ docker build --build-arg user=what_user Dockerfile 1056 ``` 1057 1058 The `USER` at line 2 evaluates to `some_user` as the `user` variable is defined on the 1059 subsequent line 3. The `USER` at line 4 evaluates to `what_user` as `user` is 1060 defined and the `what_user` value was passed on the command line. Prior to its definition by an 1061 `ARG` instruction, any use of a variable results in an empty string. 1062 1063 > **Note:** It is not recommended to use build-time variables for 1064 > passing secrets like github keys, user credentials etc. 1065 1066 You can use an `ARG` or an `ENV` instruction to specify variables that are 1067 available to the `RUN` instruction. Environment variables defined using the 1068 `ENV` instruction always override an `ARG` instruction of the same name. Consider 1069 this Dockerfile with an `ENV` and `ARG` instruction. 1070 1071 ``` 1072 1 FROM ubuntu 1073 2 ARG CONT_IMG_VER 1074 3 ENV CONT_IMG_VER v1.0.0 1075 4 RUN echo $CONT_IMG_VER 1076 ``` 1077 Then, assume this image is built with this command: 1078 1079 ``` 1080 $ docker build --build-arg CONT_IMG_VER=v2.0.1 Dockerfile 1081 ``` 1082 1083 In this case, the `RUN` instruction uses `v1.0.0` instead of the `ARG` setting 1084 passed by the user:`v2.0.1` This behavior is similar to a shell 1085 script where a locally scoped variable overrides the variables passed as 1086 arguments or inherited from environment, from its point of definition. 1087 1088 Using the example above but a different `ENV` specification you can create more 1089 useful interactions between `ARG` and `ENV` instructions: 1090 1091 ``` 1092 1 FROM ubuntu 1093 2 ARG CONT_IMG_VER 1094 3 ENV CONT_IMG_VER ${CONT_IMG_VER:-v1.0.0} 1095 4 RUN echo $CONT_IMG_VER 1096 ``` 1097 1098 Unlike an `ARG` instruction, `ENV` values are always persisted in the built 1099 image. Consider a docker build without the --build-arg flag: 1100 1101 ``` 1102 $ docker build Dockerfile 1103 ``` 1104 1105 Using this Dockerfile example, `CONT_IMG_VER` is still persisted in the image but 1106 its value would be `v1.0.0` as it is the default set in line 3 by the `ENV` instruction. 1107 1108 The variable expansion technique in this example allows you to pass arguments 1109 from the command line and persist them in the final image by leveraging the 1110 `ENV` instruction. Variable expansion is only supported for [a limited set of 1111 Dockerfile instructions.](#environment-replacement) 1112 1113 Docker has a set of predefined `ARG` variables that you can use without a 1114 corresponding `ARG` instruction in the Dockerfile. 1115 1116 * `HTTP_PROXY` 1117 * `http_proxy` 1118 * `HTTPS_PROXY` 1119 * `https_proxy` 1120 * `FTP_PROXY` 1121 * `ftp_proxy` 1122 * `NO_PROXY` 1123 * `no_proxy` 1124 1125 To use these, simply pass them on the command line using the `--build-arg 1126 <varname>=<value>` flag. 1127 1128 ## ONBUILD 1129 1130 ONBUILD [INSTRUCTION] 1131 1132 The `ONBUILD` instruction adds to the image a *trigger* instruction to 1133 be executed at a later time, when the image is used as the base for 1134 another build. The trigger will be executed in the context of the 1135 downstream build, as if it had been inserted immediately after the 1136 `FROM` instruction in the downstream `Dockerfile`. 1137 1138 Any build instruction can be registered as a trigger. 1139 1140 This is useful if you are building an image which will be used as a base 1141 to build other images, for example an application build environment or a 1142 daemon which may be customized with user-specific configuration. 1143 1144 For example, if your image is a reusable Python application builder, it 1145 will require application source code to be added in a particular 1146 directory, and it might require a build script to be called *after* 1147 that. You can't just call `ADD` and `RUN` now, because you don't yet 1148 have access to the application source code, and it will be different for 1149 each application build. You could simply provide application developers 1150 with a boilerplate `Dockerfile` to copy-paste into their application, but 1151 that is inefficient, error-prone and difficult to update because it 1152 mixes with application-specific code. 1153 1154 The solution is to use `ONBUILD` to register advance instructions to 1155 run later, during the next build stage. 1156 1157 Here's how it works: 1158 1159 1. When it encounters an `ONBUILD` instruction, the builder adds a 1160 trigger to the metadata of the image being built. The instruction 1161 does not otherwise affect the current build. 1162 2. At the end of the build, a list of all triggers is stored in the 1163 image manifest, under the key `OnBuild`. They can be inspected with 1164 the `docker inspect` command. 1165 3. Later the image may be used as a base for a new build, using the 1166 `FROM` instruction. As part of processing the `FROM` instruction, 1167 the downstream builder looks for `ONBUILD` triggers, and executes 1168 them in the same order they were registered. If any of the triggers 1169 fail, the `FROM` instruction is aborted which in turn causes the 1170 build to fail. If all triggers succeed, the `FROM` instruction 1171 completes and the build continues as usual. 1172 4. Triggers are cleared from the final image after being executed. In 1173 other words they are not inherited by "grand-children" builds. 1174 1175 For example you might add something like this: 1176 1177 [...] 1178 ONBUILD ADD . /app/src 1179 ONBUILD RUN /usr/local/bin/python-build --dir /app/src 1180 [...] 1181 1182 > **Warning**: Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. 1183 1184 > **Warning**: The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. 1185 1186 ## STOPSIGNAL 1187 1188 STOPSIGNAL signal 1189 1190 The `STOPSIGNAL` instruction sets the system call signal that will be sent to the container to exit. 1191 This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9, 1192 or a signal name in the format SIGNAME, for instance SIGKILL. 1193 1194 ## Dockerfile examples 1195 1196 Below you can see some examples of Dockerfile syntax. If you're interested in 1197 something more realistic, take a look at the list of [Dockerization examples](../examples/). 1198 1199 ``` 1200 # Nginx 1201 # 1202 # VERSION 0.0.1 1203 1204 FROM ubuntu 1205 MAINTAINER Victor Vieux <victor@docker.com> 1206 1207 LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0" 1208 RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server 1209 ``` 1210 1211 ``` 1212 # Firefox over VNC 1213 # 1214 # VERSION 0.3 1215 1216 FROM ubuntu 1217 1218 # Install vnc, xvfb in order to create a 'fake' display and firefox 1219 RUN apt-get update && apt-get install -y x11vnc xvfb firefox 1220 RUN mkdir ~/.vnc 1221 # Setup a password 1222 RUN x11vnc -storepasswd 1234 ~/.vnc/passwd 1223 # Autostart firefox (might not be the best way, but it does the trick) 1224 RUN bash -c 'echo "firefox" >> /.bashrc' 1225 1226 EXPOSE 5900 1227 CMD ["x11vnc", "-forever", "-usepw", "-create"] 1228 ``` 1229 1230 ``` 1231 # Multiple images example 1232 # 1233 # VERSION 0.1 1234 1235 FROM ubuntu 1236 RUN echo foo > bar 1237 # Will output something like ===> 907ad6c2736f 1238 1239 FROM ubuntu 1240 RUN echo moo > oink 1241 # Will output something like ===> 695d7793cbe4 1242 1243 # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with 1244 # /oink. 1245 ```