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