github.com/a4a881d4/docker@v1.9.0-rc2/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 ports. 493 You can expose one port number and publish it externally under another number. 494 495 Docker uses exposed and published ports to interconnect containers using links 496 (see [Linking containers together](../userguide/dockerlinks.md)) 497 and to set up port redirection on the host system when [using the -P flag](run.md#expose-incoming-ports). 498 499 ## ENV 500 501 ENV <key> <value> 502 ENV <key>=<value> ... 503 504 The `ENV` instruction sets the environment variable `<key>` to the value 505 `<value>`. This value will be in the environment of all "descendent" `Dockerfile` 506 commands and can be [replaced inline](#environment-replacement) in many as well. 507 508 The `ENV` instruction has two forms. The first form, `ENV <key> <value>`, 509 will set a single variable to a value. The entire string after the first 510 space will be treated as the `<value>` - including characters such as 511 spaces and quotes. 512 513 The second form, `ENV <key>=<value> ...`, allows for multiple variables to 514 be set at one time. Notice that the second form uses the equals sign (=) 515 in the syntax, while the first form does not. Like command line parsing, 516 quotes and backslashes can be used to include spaces within values. 517 518 For example: 519 520 ENV myName="John Doe" myDog=Rex\ The\ Dog \ 521 myCat=fluffy 522 523 and 524 525 ENV myName John Doe 526 ENV myDog Rex The Dog 527 ENV myCat fluffy 528 529 will yield the same net results in the final container, but the first form 530 is preferred because it produces a single cache layer. 531 532 The environment variables set using `ENV` will persist when a container is run 533 from the resulting image. You can view the values using `docker inspect`, and 534 change them using `docker run --env <key>=<value>`. 535 536 > **Note**: 537 > Environment persistence can cause unexpected side effects. For example, 538 > setting `ENV DEBIAN_FRONTEND noninteractive` may confuse apt-get 539 > users on a Debian-based image. To set a value for a single command, use 540 > `RUN <key>=<value> <command>`. 541 542 ## ADD 543 544 ADD has two forms: 545 546 - `ADD <src>... <dest>` 547 - `ADD ["<src>",... "<dest>"]` (this form is required for paths containing 548 whitespace) 549 550 The `ADD` instruction copies new files, directories or remote file URLs from `<src>` 551 and adds them to the filesystem of the container at the path `<dest>`. 552 553 Multiple `<src>` resource may be specified but if they are files or 554 directories then they must be relative to the source directory that is 555 being built (the context of the build). 556 557 Each `<src>` may contain wildcards and matching will be done using Go's 558 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 559 560 ADD hom* /mydir/ # adds all files starting with "hom" 561 ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 562 563 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 564 the source will be copied inside the destination container. 565 566 ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 567 ADD test /absoluteDir # adds "test" to /absoluteDir 568 569 All new files and directories are created with a UID and GID of 0. 570 571 In the case where `<src>` is a remote file URL, the destination will 572 have permissions of 600. If the remote file being retrieved has an HTTP 573 `Last-Modified` header, the timestamp from that header will be used 574 to set the `mtime` on the destination file. However, like any other file 575 processed during an `ADD`, `mtime` will not be included in the determination 576 of whether or not the file has changed and the cache should be updated. 577 578 > **Note**: 579 > If you build by passing a `Dockerfile` through STDIN (`docker 580 > build - < somefile`), there is no build context, so the `Dockerfile` 581 > can only contain a URL based `ADD` instruction. You can also pass a 582 > compressed archive through STDIN: (`docker build - < archive.tar.gz`), 583 > the `Dockerfile` at the root of the archive and the rest of the 584 > archive will get used at the context of the build. 585 586 > **Note**: 587 > If your URL files are protected using authentication, you 588 > will need to use `RUN wget`, `RUN curl` or use another tool from 589 > within the container as the `ADD` instruction does not support 590 > authentication. 591 592 > **Note**: 593 > The first encountered `ADD` instruction will invalidate the cache for all 594 > following instructions from the Dockerfile if the contents of `<src>` have 595 > changed. This includes invalidating the cache for `RUN` instructions. 596 > See the [`Dockerfile` Best Practices 597 guide](../articles/dockerfile_best-practices.md#build-cache) for more information. 598 599 600 `ADD` obeys the following rules: 601 602 - The `<src>` path must be inside the *context* of the build; 603 you cannot `ADD ../something /something`, because the first step of a 604 `docker build` is to send the context directory (and subdirectories) to the 605 docker daemon. 606 607 - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a 608 file is downloaded from the URL and copied to `<dest>`. 609 610 - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the 611 filename is inferred from the URL and the file is downloaded to 612 `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would 613 create the file `/foobar`. The URL must have a nontrivial path so that an 614 appropriate filename can be discovered in this case (`http://example.com` 615 will not work). 616 617 - If `<src>` is a directory, the entire contents of the directory are copied, 618 including filesystem metadata. 619 620 > **Note**: 621 > The directory itself is not copied, just its contents. 622 623 - If `<src>` is a *local* tar archive in a recognized compression format 624 (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources 625 from *remote* URLs are **not** decompressed. When a directory is copied or 626 unpacked, it has the same behavior as `tar -x`: the result is the union of: 627 628 1. Whatever existed at the destination path and 629 2. The contents of the source tree, with conflicts resolved in favor 630 of "2." on a file-by-file basis. 631 632 - If `<src>` is any other kind of file, it is copied individually along with 633 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 634 will be considered a directory and the contents of `<src>` will be written 635 at `<dest>/base(<src>)`. 636 637 - If multiple `<src>` resources are specified, either directly or due to the 638 use of a wildcard, then `<dest>` must be a directory, and it must end with 639 a slash `/`. 640 641 - If `<dest>` does not end with a trailing slash, it will be considered a 642 regular file and the contents of `<src>` will be written at `<dest>`. 643 644 - If `<dest>` doesn't exist, it is created along with all missing directories 645 in its path. 646 647 ## COPY 648 649 COPY has two forms: 650 651 - `COPY <src>... <dest>` 652 - `COPY ["<src>",... "<dest>"]` (this form is required for paths containing 653 whitespace) 654 655 The `COPY` instruction copies new files or directories from `<src>` 656 and adds them to the filesystem of the container at the path `<dest>`. 657 658 Multiple `<src>` resource may be specified but they must be relative 659 to the source directory that is being built (the context of the build). 660 661 Each `<src>` may contain wildcards and matching will be done using Go's 662 [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For example: 663 664 COPY hom* /mydir/ # adds all files starting with "hom" 665 COPY hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt" 666 667 The `<dest>` is an absolute path, or a path relative to `WORKDIR`, into which 668 the source will be copied inside the destination container. 669 670 COPY test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/ 671 COPY test /absoluteDir # adds "test" to /absoluteDir 672 673 All new files and directories are created with a UID and GID of 0. 674 675 > **Note**: 676 > If you build using STDIN (`docker build - < somefile`), there is no 677 > build context, so `COPY` can't be used. 678 679 `COPY` obeys the following rules: 680 681 - The `<src>` path must be inside the *context* of the build; 682 you cannot `COPY ../something /something`, because the first step of a 683 `docker build` is to send the context directory (and subdirectories) to the 684 docker daemon. 685 686 - If `<src>` is a directory, the entire contents of the directory are copied, 687 including filesystem metadata. 688 689 > **Note**: 690 > The directory itself is not copied, just its contents. 691 692 - If `<src>` is any other kind of file, it is copied individually along with 693 its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it 694 will be considered a directory and the contents of `<src>` will be written 695 at `<dest>/base(<src>)`. 696 697 - If multiple `<src>` resources are specified, either directly or due to the 698 use of a wildcard, then `<dest>` must be a directory, and it must end with 699 a slash `/`. 700 701 - If `<dest>` does not end with a trailing slash, it will be considered a 702 regular file and the contents of `<src>` will be written at `<dest>`. 703 704 - If `<dest>` doesn't exist, it is created along with all missing directories 705 in its path. 706 707 ## ENTRYPOINT 708 709 ENTRYPOINT has two forms: 710 711 - `ENTRYPOINT ["executable", "param1", "param2"]` 712 (*exec* form, preferred) 713 - `ENTRYPOINT command param1 param2` 714 (*shell* form) 715 716 An `ENTRYPOINT` allows you to configure a container that will run as an executable. 717 718 For example, the following will start nginx with its default content, listening 719 on port 80: 720 721 docker run -i -t --rm -p 80:80 nginx 722 723 Command line arguments to `docker run <image>` will be appended after all 724 elements in an *exec* form `ENTRYPOINT`, and will override all elements specified 725 using `CMD`. 726 This allows arguments to be passed to the entry point, i.e., `docker run <image> -d` 727 will pass the `-d` argument to the entry point. 728 You can override the `ENTRYPOINT` instruction using the `docker run --entrypoint` 729 flag. 730 731 The *shell* form prevents any `CMD` or `run` command line arguments from being 732 used, but has the disadvantage that your `ENTRYPOINT` will be started as a 733 subcommand of `/bin/sh -c`, which does not pass signals. 734 This means that the executable will not be the container's `PID 1` - and 735 will _not_ receive Unix signals - so your executable will not receive a 736 `SIGTERM` from `docker stop <container>`. 737 738 Only the last `ENTRYPOINT` instruction in the `Dockerfile` will have an effect. 739 740 ### Exec form ENTRYPOINT example 741 742 You can use the *exec* form of `ENTRYPOINT` to set fairly stable default commands 743 and arguments and then use either form of `CMD` to set additional defaults that 744 are more likely to be changed. 745 746 FROM ubuntu 747 ENTRYPOINT ["top", "-b"] 748 CMD ["-c"] 749 750 When you run the container, you can see that `top` is the only process: 751 752 $ docker run -it --rm --name test top -H 753 top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05 754 Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie 755 %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 756 KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers 757 KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem 758 759 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 760 1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top 761 762 To examine the result further, you can use `docker exec`: 763 764 $ docker exec -it test ps aux 765 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 766 root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H 767 root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux 768 769 And you can gracefully request `top` to shut down using `docker stop test`. 770 771 The following `Dockerfile` shows using the `ENTRYPOINT` to run Apache in the 772 foreground (i.e., as `PID 1`): 773 774 ``` 775 FROM debian:stable 776 RUN apt-get update && apt-get install -y --force-yes apache2 777 EXPOSE 80 443 778 VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"] 779 ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] 780 ``` 781 782 If you need to write a starter script for a single executable, you can ensure that 783 the final executable receives the Unix signals by using `exec` and `gosu` 784 commands: 785 786 ```bash 787 #!/bin/bash 788 set -e 789 790 if [ "$1" = 'postgres' ]; then 791 chown -R postgres "$PGDATA" 792 793 if [ -z "$(ls -A "$PGDATA")" ]; then 794 gosu postgres initdb 795 fi 796 797 exec gosu postgres "$@" 798 fi 799 800 exec "$@" 801 ``` 802 803 Lastly, if you need to do some extra cleanup (or communicate with other containers) 804 on shutdown, or are co-ordinating more than one executable, you may need to ensure 805 that the `ENTRYPOINT` script receives the Unix signals, passes them on, and then 806 does some more work: 807 808 ``` 809 #!/bin/sh 810 # Note: I've written this using sh so it works in the busybox container too 811 812 # USE the trap if you need to also do manual cleanup after the service is stopped, 813 # or need to start multiple services in the one container 814 trap "echo TRAPed signal" HUP INT QUIT KILL TERM 815 816 # start service in background here 817 /usr/sbin/apachectl start 818 819 echo "[hit enter key to exit] or run 'docker stop <container>'" 820 read 821 822 # stop service and clean up here 823 echo "stopping apache" 824 /usr/sbin/apachectl stop 825 826 echo "exited $0" 827 ``` 828 829 If you run this image with `docker run -it --rm -p 80:80 --name test apache`, 830 you can then examine the container's processes with `docker exec`, or `docker top`, 831 and then ask the script to stop Apache: 832 833 ```bash 834 $ docker exec -it test ps aux 835 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 836 root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123 cmd cmd2 837 root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start 838 www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 839 www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start 840 root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux 841 $ docker top test 842 PID USER COMMAND 843 10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2 844 10054 root /usr/sbin/apache2 -k start 845 10055 33 /usr/sbin/apache2 -k start 846 10056 33 /usr/sbin/apache2 -k start 847 $ /usr/bin/time docker stop test 848 test 849 real 0m 0.27s 850 user 0m 0.03s 851 sys 0m 0.03s 852 ``` 853 854 > **Note:** you can over ride the `ENTRYPOINT` setting using `--entrypoint`, 855 > but this can only set the binary to *exec* (no `sh -c` will be used). 856 857 > **Note**: 858 > The *exec* form is parsed as a JSON array, which means that 859 > you must use double-quotes (") around words not single-quotes ('). 860 861 > **Note**: 862 > Unlike the *shell* form, the *exec* form does not invoke a command shell. 863 > This means that normal shell processing does not happen. For example, 864 > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. 865 > If you want shell processing then either use the *shell* form or execute 866 > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo", "$HOME" ]`. 867 > Variables that are defined in the `Dockerfile`using `ENV`, will be substituted by 868 > the `Dockerfile` parser. 869 870 ### Shell form ENTRYPOINT example 871 872 You can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`. 873 This form will use shell processing to substitute shell environment variables, 874 and will ignore any `CMD` or `docker run` command line arguments. 875 To ensure that `docker stop` will signal any long running `ENTRYPOINT` executable 876 correctly, you need to remember to start it with `exec`: 877 878 FROM ubuntu 879 ENTRYPOINT exec top -b 880 881 When you run this image, you'll see the single `PID 1` process: 882 883 $ docker run -it --rm --name test top 884 Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached 885 CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq 886 Load average: 0.08 0.03 0.05 2/98 6 887 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 888 1 0 root R 3164 0% 0% top -b 889 890 Which will exit cleanly on `docker stop`: 891 892 $ /usr/bin/time docker stop test 893 test 894 real 0m 0.20s 895 user 0m 0.02s 896 sys 0m 0.04s 897 898 If you forget to add `exec` to the beginning of your `ENTRYPOINT`: 899 900 FROM ubuntu 901 ENTRYPOINT top -b 902 CMD --ignored-param1 903 904 You can then run it (giving it a name for the next step): 905 906 $ docker run -it --name test top --ignored-param2 907 Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached 908 CPU: 9% usr 2% sys 0% nic 88% idle 0% io 0% irq 0% sirq 909 Load average: 0.01 0.02 0.05 2/101 7 910 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 911 1 0 root S 3168 0% 0% /bin/sh -c top -b cmd cmd2 912 7 1 root R 3164 0% 0% top -b 913 914 You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. 915 916 If you then run `docker stop test`, the container will not exit cleanly - the 917 `stop` command will be forced to send a `SIGKILL` after the timeout: 918 919 $ docker exec -it test ps aux 920 PID USER COMMAND 921 1 root /bin/sh -c top -b cmd cmd2 922 7 root top -b 923 8 root ps aux 924 $ /usr/bin/time docker stop test 925 test 926 real 0m 10.19s 927 user 0m 0.04s 928 sys 0m 0.03s 929 930 ## VOLUME 931 932 VOLUME ["/data"] 933 934 The `VOLUME` instruction creates a mount point with the specified name 935 and marks it as holding externally mounted volumes from native host or other 936 containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain 937 string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log 938 /var/db`. For more information/examples and mounting instructions via the 939 Docker client, refer to 940 [*Share Directories via Volumes*](../userguide/dockervolumes.md#mount-a-host-directory-as-a-data-volume) 941 documentation. 942 943 The `docker run` command initializes the newly created volume with any data 944 that exists at the specified location within the base image. For example, 945 consider the following Dockerfile snippet: 946 947 FROM ubuntu 948 RUN mkdir /myvol 949 RUN echo "hello world" > /myvol/greeting 950 VOLUME /myvol 951 952 This Dockerfile results in an image that causes `docker run`, to 953 create a new mount point at `/myvol` and copy the `greeting` file 954 into the newly created volume. 955 956 > **Note**: 957 > If any build steps change the data within the volume after it has been 958 > declared, those changes will be discarded. 959 960 > **Note**: 961 > The list is parsed as a JSON array, which means that 962 > you must use double-quotes (") around words not single-quotes ('). 963 964 ## USER 965 966 USER daemon 967 968 The `USER` instruction sets the user name or UID to use when running the image 969 and for any `RUN`, `CMD` and `ENTRYPOINT` instructions that follow it in the 970 `Dockerfile`. 971 972 ## WORKDIR 973 974 WORKDIR /path/to/workdir 975 976 The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, 977 `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. 978 979 It can be used multiple times in the one `Dockerfile`. If a relative path 980 is provided, it will be relative to the path of the previous `WORKDIR` 981 instruction. For example: 982 983 WORKDIR /a 984 WORKDIR b 985 WORKDIR c 986 RUN pwd 987 988 The output of the final `pwd` command in this `Dockerfile` would be 989 `/a/b/c`. 990 991 The `WORKDIR` instruction can resolve environment variables previously set using 992 `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. 993 For example: 994 995 ENV DIRPATH /path 996 WORKDIR $DIRPATH/$DIRNAME 997 RUN pwd 998 999 The output of the final `pwd` command in this `Dockerfile` would be 1000 `/path/$DIRNAME` 1001 1002 ## ARG 1003 1004 ARG <name>[=<default value>] 1005 1006 The `ARG` instruction defines a variable that users can pass at build-time to 1007 the builder with the `docker build` command using the `--build-arg 1008 <varname>=<value>` flag. If a user specifies a build argument that was not 1009 defined in the Dockerfile, the build outputs an error. 1010 1011 ``` 1012 One or more build-args were not consumed, failing build. 1013 ``` 1014 1015 The Dockerfile author can define a single variable by specifying `ARG` once or many 1016 variables by specifying `ARG` more than once. For example, a valid Dockerfile: 1017 1018 ``` 1019 FROM busybox 1020 ARG user1 1021 ARG buildno 1022 ... 1023 ``` 1024 1025 A Dockerfile author may optionally specify a default value for an `ARG` instruction: 1026 1027 ``` 1028 FROM busybox 1029 ARG user1=someuser 1030 ARG buildno=1 1031 ... 1032 ``` 1033 1034 If an `ARG` value has a default and if there is no value passed at build-time, the 1035 builder uses the default. 1036 1037 An `ARG` variable definition comes into effect from the line on which it is 1038 defined in the `Dockerfile` not from the argument's use on the command-line or 1039 elsewhere. For example, consider this Dockerfile: 1040 1041 ``` 1042 1 FROM busybox 1043 2 USER ${user:-some_user} 1044 3 ARG user 1045 4 USER $user 1046 ... 1047 ``` 1048 A user builds this file by calling: 1049 1050 ``` 1051 $ docker build --build-arg user=what_user Dockerfile 1052 ``` 1053 1054 The `USER` at line 2 evaluates to `some_user` as the `user` variable is defined on the 1055 subsequent line 3. The `USER` at line 4 evaluates to `what_user` as `user` is 1056 defined and the `what_user` value was passed on the command line. Prior to its definition by an 1057 `ARG` instruction, any use of a variable results in an empty string. 1058 1059 > **Note:** It is not recommended to use build-time variables for 1060 > passing secrets like github keys, user credentials etc. 1061 1062 You can use an `ARG` or an `ENV` instruction to specify variables that are 1063 available to the `RUN` instruction. Environment variables defined using the 1064 `ENV` instruction always override an `ARG` instruction of the same name. Consider 1065 this Dockerfile with an `ENV` and `ARG` instruction. 1066 1067 ``` 1068 1 FROM ubuntu 1069 2 ARG CONT_IMG_VER 1070 3 ENV CONT_IMG_VER v1.0.0 1071 4 RUN echo $CONT_IMG_VER 1072 ``` 1073 Then, assume this image is built with this command: 1074 1075 ``` 1076 $ docker build --build-arg CONT_IMG_VER=v2.0.1 Dockerfile 1077 ``` 1078 1079 In this case, the `RUN` instruction uses `v1.0.0` instead of the `ARG` setting 1080 passed by the user:`v2.0.1` This behavior is similar to a shell 1081 script where a locally scoped variable overrides the variables passed as 1082 arguments or inherited from environment, from its point of definition. 1083 1084 Using the example above but a different `ENV` specification you can create more 1085 useful interactions between `ARG` and `ENV` instructions: 1086 1087 ``` 1088 1 FROM ubuntu 1089 2 ARG CONT_IMG_VER 1090 3 ENV CONT_IMG_VER ${CONT_IMG_VER:-v1.0.0} 1091 4 RUN echo $CONT_IMG_VER 1092 ``` 1093 1094 Unlike an `ARG` instruction, `ENV` values are always persisted in the built 1095 image. Consider a docker build without the --build-arg flag: 1096 1097 ``` 1098 $ docker build Dockerfile 1099 ``` 1100 1101 Using this Dockerfile example, `CONT_IMG_VER` is still persisted in the image but 1102 its value would be `v1.0.0` as it is the default set in line 3 by the `ENV` instruction. 1103 1104 The variable expansion technique in this example allows you to pass arguments 1105 from the command line and persist them in the final image by leveraging the 1106 `ENV` instruction. Variable expansion is only supported for [a limited set of 1107 Dockerfile instructions.](#environment-replacement) 1108 1109 Docker has a set of predefined `ARG` variables that you can use without a 1110 corresponding `ARG` instruction in the Dockerfile. 1111 1112 * `HTTP_PROXY` 1113 * `http_proxy` 1114 * `HTTPS_PROXY` 1115 * `https_proxy` 1116 * `FTP_PROXY` 1117 * `ftp_proxy` 1118 * `NO_PROXY` 1119 * `no_proxy` 1120 1121 To use these, simply pass them on the command line using the `--build-arg 1122 <varname>=<value>` flag. 1123 1124 ## ONBUILD 1125 1126 ONBUILD [INSTRUCTION] 1127 1128 The `ONBUILD` instruction adds to the image a *trigger* instruction to 1129 be executed at a later time, when the image is used as the base for 1130 another build. The trigger will be executed in the context of the 1131 downstream build, as if it had been inserted immediately after the 1132 `FROM` instruction in the downstream `Dockerfile`. 1133 1134 Any build instruction can be registered as a trigger. 1135 1136 This is useful if you are building an image which will be used as a base 1137 to build other images, for example an application build environment or a 1138 daemon which may be customized with user-specific configuration. 1139 1140 For example, if your image is a reusable Python application builder, it 1141 will require application source code to be added in a particular 1142 directory, and it might require a build script to be called *after* 1143 that. You can't just call `ADD` and `RUN` now, because you don't yet 1144 have access to the application source code, and it will be different for 1145 each application build. You could simply provide application developers 1146 with a boilerplate `Dockerfile` to copy-paste into their application, but 1147 that is inefficient, error-prone and difficult to update because it 1148 mixes with application-specific code. 1149 1150 The solution is to use `ONBUILD` to register advance instructions to 1151 run later, during the next build stage. 1152 1153 Here's how it works: 1154 1155 1. When it encounters an `ONBUILD` instruction, the builder adds a 1156 trigger to the metadata of the image being built. The instruction 1157 does not otherwise affect the current build. 1158 2. At the end of the build, a list of all triggers is stored in the 1159 image manifest, under the key `OnBuild`. They can be inspected with 1160 the `docker inspect` command. 1161 3. Later the image may be used as a base for a new build, using the 1162 `FROM` instruction. As part of processing the `FROM` instruction, 1163 the downstream builder looks for `ONBUILD` triggers, and executes 1164 them in the same order they were registered. If any of the triggers 1165 fail, the `FROM` instruction is aborted which in turn causes the 1166 build to fail. If all triggers succeed, the `FROM` instruction 1167 completes and the build continues as usual. 1168 4. Triggers are cleared from the final image after being executed. In 1169 other words they are not inherited by "grand-children" builds. 1170 1171 For example you might add something like this: 1172 1173 [...] 1174 ONBUILD ADD . /app/src 1175 ONBUILD RUN /usr/local/bin/python-build --dir /app/src 1176 [...] 1177 1178 > **Warning**: Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. 1179 1180 > **Warning**: The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. 1181 1182 ## STOPSIGNAL 1183 1184 STOPSIGNAL signal 1185 1186 The `STOPSIGNAL` instruction sets the system call signal that will be sent to the container to exit. 1187 This signal can be a valid unsigned number that matches a position in the kernel's syscall table, for instance 9, 1188 or a signal name in the format SIGNAME, for instance SIGKILL. 1189 1190 ## Dockerfile examples 1191 1192 Below you can see some examples of Dockerfile syntax. If you're interested in 1193 something more realistic, take a look at the list of [Dockerization examples](../examples/). 1194 1195 ``` 1196 # Nginx 1197 # 1198 # VERSION 0.0.1 1199 1200 FROM ubuntu 1201 MAINTAINER Victor Vieux <victor@docker.com> 1202 1203 LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0" 1204 RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server 1205 ``` 1206 1207 ``` 1208 # Firefox over VNC 1209 # 1210 # VERSION 0.3 1211 1212 FROM ubuntu 1213 1214 # Install vnc, xvfb in order to create a 'fake' display and firefox 1215 RUN apt-get update && apt-get install -y x11vnc xvfb firefox 1216 RUN mkdir ~/.vnc 1217 # Setup a password 1218 RUN x11vnc -storepasswd 1234 ~/.vnc/passwd 1219 # Autostart firefox (might not be the best way, but it does the trick) 1220 RUN bash -c 'echo "firefox" >> /.bashrc' 1221 1222 EXPOSE 5900 1223 CMD ["x11vnc", "-forever", "-usepw", "-create"] 1224 ``` 1225 1226 ``` 1227 # Multiple images example 1228 # 1229 # VERSION 0.1 1230 1231 FROM ubuntu 1232 RUN echo foo > bar 1233 # Will output something like ===> 907ad6c2736f 1234 1235 FROM ubuntu 1236 RUN echo moo > oink 1237 # Will output something like ===> 695d7793cbe4 1238 1239 # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with 1240 # /oink. 1241 ```