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