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