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