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