Dockerfile reference
Docker can build images automatically by reading the instructions from a Dockerfile
.
A Dockerfile
is a text document that contains all the commands a user could call on the command line to assemble an image.
Using docker build
users can create an automated build that executes several command-line instructions in succession.
This page describes the commands you can use in a Dockerfile
. When you are done reading this page, refer to the Dockerfile
Best Practices for a tip-oriented guide.
Usage
The docker build
command builds an image from a Dockerfile
and a context.
The build’s context is the set of files at a specified location PATH
or URL
.
The PATH
is a directory on your local filesystem.
The URL
is a Git repository location.
A context is processed recursively.
So, a PATH
includes any subdirectories and the URL
includes the repository and its submodules.
This example shows a build command that uses the current directory as context:
$ docker build .
Sending build context to Docker daemon 6.51 MB
...
The build is run by the Docker daemon, not by the CLI.
The first thing a build process does is send the entire context (recursively) to the daemon.
In most cases, it’s best to start with an empty directory as context and keep your Dockerfile in that directory. Add only the files needed for building the Dockerfile.
Warning: Do not use your root directory,
/
, as thePATH
as it causes the build to transfer the entire contents of your hard drive to the Docker daemon.
To use a file in the build context, the Dockerfile
refers to the file specified in an instruction, for example, a COPY
instruction.
To increase the build’s performance, exclude files and directories by adding a .dockerignore
file to the context directory.
For information about how to create a .dockerignore
file see the documentation on this page.
Traditionally, the Dockerfile
is called Dockerfile
and located in the root of the context.
You use the -f
flag with docker build
to point to a Dockerfile anywhere in your file system.
$ docker build -f /path/to/a/Dockerfile .
You can specify a repository and tag at which to save the new image if the build succeeds:
$ docker build -t shykes/myapp .
To tag the image into multiple repositories after the build, add multiple -t
parameters when you run the build
command:
$ docker build -t shykes/myapp:1.0.2 -t shykes/myapp:latest .
Before the Docker daemon runs the instructions in the Dockerfile
, it performs a preliminary validation of the Dockerfile
and returns an error if the syntax is incorrect:
$ docker build -t test/myapp .
Sending build context to Docker daemon 2.048 kB
Error response from daemon: Unknown instruction: RUNCMD
The Docker daemon runs the instructions in the Dockerfile
one-by-one, committing the result of each instruction to a new image if necessary, before finally outputting the ID of your new image. The Docker daemon will automatically clean up the context you sent.
Note that each instruction is run independently, and causes a new image to be created - so RUN cd /tmp
will not have any effect on the next instructions.
Whenever possible, Docker will re-use the intermediate images (cache), to accelerate the docker build
process significantly. This is indicated by the Using cache
message in the console output. (For more information, see the Build cache section in the Dockerfile
best practices guide):
$ docker build -t svendowideit/ambassador .
Sending build context to Docker daemon 15.36 kB
Step 1/4 : FROM alpine:3.2
---> 31f630c65071
Step 2/4 : MAINTAINER SvenDowideit@home.org.au
---> Using cache
---> 2a1c91448f5f
Step 3/4 : RUN apk update && apk add socat && rm -r /var/cache/
---> Using cache
---> 21ed6e7fbb73
Step 4/4 : CMD env | grep _TCP= | (sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat -t 100000000 TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/' && echo wait) | sh
---> Using cache
---> 7ea8aef582cc
Successfully built 7ea8aef582cc
Build cache is only used from images that have a local parent chain.
This means that these images were created by previous builds or the whole chain of images was loaded with docker load
.
If you wish to use build cache of a specific image you can specify it with --cache-from
option. Images specified with --cache-from
do not need to have a parent chain and may be pulled from other registries.
When you’re done with your build, you’re ready to look into Pushing a repository to its registry.
Format
Here is the format of the Dockerfile
:
# Comment
INSTRUCTION arguments
The instruction is not case-sensitive. However, convention is for them to be UPPERCASE to distinguish them from arguments more easily.
Docker runs instructions in a Dockerfile
in order.
A Dockerfile
must start with a `FROM` instruction. The FROM
instruction specifies the Base Image from which you are building. FROM
may only be preceded by one or more ARG
instructions, which declare arguments that are used in FROM
lines in the Dockerfile
.
Docker treats lines that begin with #
as a comment, unless the line is a valid parser directive. A #
marker anywhere else in a line is treated as an argument. This allows statements like:
# Comment
RUN echo 'we are running some # of cool things'
Line continuation characters are not supported in comments.
Parser directives
Parser directives are optional, and affect the way in which subsequent lines in a Dockerfile
are handled.
Parser directives do not add layers to the build, and will not be shown as a build step.
Parser directives are written as a special type of comment in the form # directive=value
.
A single directive may only be used once.
Once a comment, empty line or builder instruction has been processed, Docker no longer looks for parser directives. Instead it treats anything formatted as a parser directive as a comment and does not attempt to validate if it might be a parser directive.
Therefore, all parser directives must be at the very top of a Dockerfile
.
Parser directives are not case-sensitive. However, convention is for them to be lowercase.
Convention is also to include a blank line following any parser directives.
Line continuation characters are not supported in parser directives.
Due to these rules, the following examples are all invalid:Invalid due to line continuation:
# direc \
tive=value
Invalid due to appearing twice:
# directive=value1
# directive=value2 FROM ImageName
Treated as a comment due to appearing after a builder instruction:
FROM ImageName
# directive=value
Treated as a comment due to appearing after a comment which is not a parser directive:
# About my dockerfile
# directive=value
FROM ImageName
The unknown directive is treated as a comment due to not being recognized.
In addition, the known directive is treated as a comment due to appearing after a comment which is not a parser directive.
#directive=value
# directive =value
# directive= value
# directive = value
# dIrEcTiVe=value
The following parser directive is supported:
escape
escape
# escape=\ (backslash)
Or
# escape=` (backtick)
The escape
directive sets the character used to escape characters in a Dockerfile
.
If not specified, the default escape character is \
.
The escape character is used both to escape characters in a line, and to escape a newline.
This allows a Dockerfile
instruction to span multiple lines.
Note that regardless of whether the escape
parser directive is included in a Dockerfile
, escaping is not performed in a RUN
command, except at the end of a line.
Setting the escape character to `
is especially useful on Windows
, where \
is the directory path separator. `
is consistent with Windows PowerShell.
Consider the following example which would fail in a non-obvious way on Windows
.
The second \
at the end of the second line would be interpreted as an escape for the newline, instead of a target of the escape from the first \
.
Similarly, the \
at the end of the third line would, assuming it was actually handled as an instruction, cause it be treated as a line continuation.
The result of this dockerfile is that second and third lines are considered a single instruction:
FROM microsoft/nanoserver
COPY testfile.txt c:\\
RUN dir c:\
Results in:
PS C:\John> docker build -t cmd .
Sending build context to Docker daemon 3.072 kB
Step 1/2 : FROM microsoft/nanoserver
---> 22738ff49c6d
Step 2/2 : COPY testfile.txt c:\RUN dir c:
GetFileAttributesEx c:RUN: The system cannot find the file specified.
PS C:\John>
One solution to the above would be to use /
as the target of both the COPY
instruction, and dir
.
However, this syntax is, at best, confusing as it is not natural for paths on Windows
, and at worst, error prone as not all commands on Windows
support /
as the path separator.
By adding the escape
parser directive, the following Dockerfile
succeeds as expected with the use of natural platform semantics for file paths on Windows
:
# escape=` FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
Results in:
PS C:\John> docker build -t succeeds --no-cache=true .
Sending build context to Docker daemon 3.072 kB
Step 1/3 : FROM microsoft/nanoserver
---> 22738ff49c6d
Step 2/3 : COPY testfile.txt c:\
---> 96655de338de
Removing intermediate container 4db9acbb1682
Step 3/3 : RUN dir c:\
---> Running in a2c157f842f5
Volume in drive C has no label.
Volume Serial Number is 7E6D-E0F7 Directory of c:\ 10/05/2016 05:04 PM 1,894 License.txt
10/05/2016 02:22 PM <DIR> Program Files
10/05/2016 02:14 PM <DIR> Program Files (x86)
10/28/2016 11:18 AM 62 testfile.txt
10/28/2016 11:20 AM <DIR> Users
10/28/2016 11:20 AM <DIR> Windows
2 File(s) 1,956 bytes
4 Dir(s) 21,259,096,064 bytes free
---> 01c7f3bef04f
Removing intermediate container a2c157f842f5
Successfully built 01c7f3bef04f
PS C:\John>
Environment replacement
Environment variables (declared with the ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile
.
Escapes are also handled for including variable-like syntax into a statement literally.
Environment variables are notated in the Dockerfile
either with $variable_name
or ${variable_name}
.
They are treated equivalently and the brace syntax is typically used to address issues with variable names with no whitespace, like ${foo}_bar
.
The ${variable_name}
syntax also supports a few of the standard bash
modifiers as specified below:
-
${variable:-word}
indicates that ifvariable
is set then the result will be that value. Ifvariable
is not set thenword
will be the result. -
${variable:+word}
indicates that ifvariable
is set thenword
will be the result, otherwise the result is the empty string.
In all cases, word
can be any string, including additional environment variables.
Escaping is possible by adding a \
before the variable: \$foo
or \${foo}
, for example, will translate to $foo
and ${foo}
literals respectively.
Example (parsed representation is displayed after the #
):
FROM busybox
ENV foo /bar
WORKDIR ${foo} # WORKDIR /bar
ADD . $foo # ADD . /bar
COPY \$foo /quux # COPY $foo /quux
Environment variables are supported by the following list of instructions in the Dockerfile
:
ADD
COPY
ENV
EXPOSE
FROM
LABEL
STOPSIGNAL
USER
VOLUME
WORKDIR
as well as:
-
ONBUILD
(when combined with one of the supported instructions above)
Note: prior to 1.4,
ONBUILD
instructions did NOT support environment variable, even when combined with any of the instructions listed above.
Environment variable substitution will use the same value for each variable throughout the entire instruction. In other words, in this example:
ENV abc=hello
ENV abc=bye def=$abc
ENV ghi=$abc
will result in def
having a value of hello
, not bye
. However, ghi
will have a value of bye
because it is not part of the same instruction that set abc
to bye
.
.dockerignore file
Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore
in the root directory of the context.
If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it.
This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD
or COPY
.
The CLI interprets the .dockerignore
file as a newline-separated list of patterns similar to the file globs of Unix shells.
For the purposes of matching, the root of the context is considered to be both the working and the root directory.
For example, the patterns /foo/bar
and foo/bar
both exclude a file or directory named bar
in the foo
subdirectory of PATH
or in the root of the git repository located at URL
. Neither excludes anything else.
If a line in .dockerignore
file starts with #
in column 1, then this line is considered as a comment and is ignored before interpreted by the CLI.
Here is an example .dockerignore
file:
# comment
*/temp*
*/*/temp*
temp?
This file causes the following build behavior:
Rule | Behavior |
---|---|
# comment |
Ignored. |
*/temp* |
Exclude files and directories whose names start with temp in any immediate subdirectory of the root. For example, the plain file /somedir/temporary.txt is excluded, as is the directory /somedir/temp . |
*/*/temp* |
Exclude files and directories starting with temp from any subdirectory that is two levels below the root. For example, /somedir/subdir/temporary.txt is excluded. |
temp? |
Exclude files and directories in the root directory whose names are a one-character extension of temp . For example, /tempa and /tempb are excluded. |
Matching is done using Go’s filepath.Match rules.
A preprocessing step removes leading and trailing whitespace and eliminates .
and ..
elements using Go’s filepath.Clean.
Lines that are blank after preprocessing are ignored.
Beyond Go’s filepath.Match rules, Docker also supports a special wildcard string **
that matches any number of directories (including zero).
For example, **/*.go
will exclude all files that end with .go
that are found in all directories, including the root of the build context.
Lines starting with !
(exclamation mark) can be used to make exceptions to exclusions.
The following is an example .dockerignore
file that uses this mechanism:
*.md
!README.md
All markdown files except README.md
are excluded from the context.
The placement of !
exception rules influences the behavior: the last line of the .dockerignore
that matches a particular file determines whether it is included or excluded. Consider the following example:
*.md
!README*.md
README-secret.md
No markdown files are included in the context except README files other than README-secret.md
.
Now consider this example:
*.md
README-secret.md
!README*.md
All of the README files are included. The middle line has no effect because !README*.md
matches README-secret.md
and comes last.
You can even use the .dockerignore
file to exclude the Dockerfile
and .dockerignore
files.
These files are still sent to the daemon because it needs them to do its job. But the ADD
and COPY
instructions do not copy them to the image.
Finally, you may want to specify which files to include in the context, rather than which to exclude. To achieve this, specify *
as the first pattern, followed by one or more !
exception patterns.
Note: For historical reasons, the pattern .
is ignored.
FROM
FROM <image> [AS <name>]
Or
FROM <image>[:<tag>] [AS <name>]
Or
FROM <image>[@<digest>] [AS <name>]
The FROM
instruction initializes a new build stage and sets the Base Image for subsequent instructions.
As such, a valid Dockerfile
must start with a FROM
instruction. The image can be any valid image – it is especially easy to start by pulling an image from the Public Repositories.
ARG
is the only instruction that may precedeFROM
in theDockerfile
. See Understand how ARG and FROM interact.FROM
can appear multiple times within a singleDockerfile
to create multiple images or use one build stage as a dependency for another. Simply make a note of the last image ID output by the commit before each newFROM
instruction. EachFROM
instruction clears any state created by previous instructions.Optionally a name can be given to a new build stage by adding
AS name
to theFROM
instruction. The name can be used in subsequentFROM
andCOPY --from=<name|index>
instructions to refer to the image built in this stage.The
tag
ordigest
values are optional. If you omit either of them, the builder assumes alatest
tag by default. The builder returns an error if it cannot find thetag
value.
Understand how ARG and FROM interact
FROM
instructions support variables that are declared by any ARG
instructions that occur before the first FROM
.
ARG CODE_VERSION=latest
FROM base:${CODE_VERSION}
CMD /code/run-app FROM extras:${CODE_VERSION}
CMD /code/run-extras
An ARG
declared before a FROM
is outside of a build stage, so it can’t be used in any instruction after a FROM
.
To use the default value of an ARG
declared before the first FROM
use an ARG
instruction without a value inside of a build stage:
ARG VERSION=latest
FROM busybox:$VERSION
ARG VERSION
RUN echo $VERSION > image_version
RUN
RUN has 2 forms:
-
RUN <command>
(shell form, the command is run in a shell, which by default is/bin/sh -c
on Linux orcmd /S /C
on Windows) -
RUN ["executable", "param1", "param2"]
(exec form)
The RUN
instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile
.
Layering RUN
instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in an image’s history, much like source control.
The exec form makes it possible to avoid shell string munging, and to RUN
commands using a base image that does not contain the specified shell executable.
The default shell for the shell form can be changed using the SHELL
command.
In the shell form you can use a \
(backslash) to continue a single RUN instruction onto the next line. For example, consider these two lines:
RUN /bin/bash -c 'source $HOME/.bashrc; \
echo $HOME'
Together they are equivalent to this single line:
RUN /bin/bash -c 'source $HOME/.bashrc; echo $HOME'
Note: To use a different shell, other than ‘/bin/sh’, use the exec form passing in the desired shell. For example,
RUN ["/bin/bash", "-c", "echo hello"]
Note: The exec form is parsed as a JSON array, which means that you must use double-quotes (“) around words not single-quotes (‘).
Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen.
For example,
RUN [ "echo", "$HOME" ]
will not do variable substitution on$HOME
.If you want shell processing then either use the shell form or execute a shell directly,
for example:
RUN [ "sh", "-c", "echo $HOME" ]
. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.Note: In the JSON form, it is necessary to escape backslashes. This is particularly relevant on Windows where the backslash is the path separator.
The following line would otherwise be treated as shell form due to not being valid JSON, and fail in an unexpected way:
RUN ["c:\windows\system32\tasklist.exe"]
The correct syntax for this example is:RUN ["c:\\windows\\system32\\tasklist.exe"]
The cache for RUN
instructions isn’t invalidated automatically during the next build. The cache for an instruction like RUN apt-get dist-upgrade -y
will be reused during the next build. The cache for RUN
instructions can be invalidated by using the --no-cache
flag, for example docker build --no-cache
.
See the Dockerfile
Best Practices guide for more information.
The cache for RUN
instructions can be invalidated by ADD
instructions. See below for details.
Known issues (RUN)
-
Issue 783 is about file permissions problems that can occur when using the AUFS file system. You might notice it during an attempt to
rm
a file, for example.For systems that have recent aufs version (i.e.,
dirperm1
mount option can be set), docker will attempt to fix the issue automatically by mounting the layers withdirperm1
option. More details ondirperm1
option can be found ataufs
man pageIf your system doesn’t have support for
dirperm1
, the issue describes a workaround.
CMD
The CMD
instruction has three forms:
-
CMD ["executable","param1","param2"]
(exec form, this is the preferred form) -
CMD ["param1","param2"]
(as default parameters to ENTRYPOINT) -
CMD command param1 param2
(shell form)
There can only be one CMD
instruction in a Dockerfile
. If you list more than one CMD
then only the last CMD
will take effect.
The main purpose of a CMD
is to provide defaults for an executing container. These defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT
instruction as well.
Note: If
CMD
is used to provide default arguments for theENTRYPOINT
instruction, both theCMD
andENTRYPOINT
instructions should be specified with the JSON array format.
Note: The exec form is parsed as a JSON array, which means that you must use double-quotes (“) around words not single-quotes (‘).
Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen.
For example,
CMD [ "echo", "$HOME" ]
will not do variable substitution on$HOME
.If you want shell processing then either use the shell form or execute a shell directly, for example:
CMD [ "sh", "-c", "echo $HOME" ]
.When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.
When used in the shell or exec formats, the CMD
instruction sets the command to be executed when running the image.
If you use the shell form of the CMD
, then the <command>
will execute in /bin/sh -c
:
FROM ubuntu
CMD echo "This is a test." | wc -
If you want to run your <command>
without a shell then you must express the command as a JSON array and give the full path to the executable. This array form is the preferred format of CMD
. Any additional parameters must be individually expressed as strings in the array:
FROM ubuntu
CMD ["/usr/bin/wc","--help"]
If you would like your container to run the same executable every time, then you should consider using ENTRYPOINT
in combination with CMD
. See ENTRYPOINT.
If the user specifies arguments to docker run
then they will override the default specified in CMD
.
Note: Don’t confuse
RUN
withCMD
.RUN
actually runs a command and commits the result;CMD
does not execute anything at build time, but specifies the intended command for the image.
LABEL
LABEL <key>=<value> <key>=<value> <key>=<value> ...
The LABEL
instruction adds metadata to an image.
A LABEL
is a key-value pair.
To include spaces within a LABEL
value, use quotes and backslashes as you would in command-line parsing.
A few usage examples:
LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL version="1.0"
LABEL description="This text illustrates \
that label-values can span multiple lines."
An image can have more than one label.
You can specify multiple labels on a single line.
Prior to Docker 1.10, this decreased the size of the final image, but this is no longer the case.
You may still choose to specify multiple labels in a single instruction, in one of the following two ways:
LABEL multi.label1="value1" multi.label2="value2" other="value3"
LABEL multi.label1="value1" \
multi.label2="value2" \
other="value3"
Labels included in base or parent images (images in the FROM
line) are inherited by your image.
If a label already exists but with a different value, the most-recently-applied value overrides any previously-set value.
To view an image’s labels, use the docker inspect
command.
"Labels": {
"com.example.vendor": "ACME Incorporated"
"com.example.label-with-value": "foo",
"version": "1.0",
"description": "This text illustrates that label-values can span multiple lines.",
"multi.label1": "value1",
"multi.label2": "value2",
"other": "value3"
},
MAINTAINER (deprecated)
MAINTAINER <name>
The MAINTAINER
instruction sets the Author field of the generated images.
The LABEL
instruction is a much more flexible version of this and you should use it instead, as it enables setting any metadata you require, and can be viewed easily,
for example with docker inspect
. To set a label corresponding to the MAINTAINER
field you could use:
LABEL maintainer="SvenDowideit@home.org.au"
This will then be visible from docker inspect
with the other labels.
EXPOSE
EXPOSE <port> [<port>/<protocol>...]
The EXPOSE
instruction informs Docker that the container listens on the specified network ports at runtime.
You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.
The EXPOSE
instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.
To actually publish the port when running the container, use the -p
flag on docker run
to publish and map one or more ports, or the -P
flag to publish all exposed ports and map them to high-order ports.
By default, EXPOSE
assumes TCP. You can also specify UDP:
EXPOSE 80/udp
To expose on both TCP and UDP, include two lines:
EXPOSE 80/tcp
EXPOSE 80/udp
In this case, if you use -P
with docker run
, the port will be exposed once for TCP and once for UDP.
Remember that -P
uses an ephemeral high-ordered host port on the host, so the port will not be the same for TCP and UDP.
Regardless of the EXPOSE
settings, you can override them at runtime by using the -p
flag. For example
docker run -p 80:80/tcp -p 80:80/udp ...
To set up port redirection on the host system, see using the -P flag.
The docker network
command supports creating networks for communication among containers without the need to expose or publish specific ports, because the containers connected to the network can communicate with each other over any port. For detailed information, see the overview of this feature).
ENV
ENV <key> <value>
ENV <key>=<value> ...
The ENV
instruction sets the environment variable <key>
to the value <value>
. This value will be in the environment for all subsequent instructions in the build stage and can be replaced inline in many as well.
The ENV
instruction has two forms.
The first form, ENV <key> <value>
, will set a single variable to a value.
The entire string after the first space will be treated as the <value>
- including whitespace characters.
The value will be interpreted for other environment variables, so quote characters will be removed if they are not escaped.
The second form, ENV <key>=<value> ...
, allows for multiple variables to be set at one time. Notice that the second form uses the equals sign (=) in the syntax, while the first form does not. Like command line parsing, quotes and backslashes can be used to include spaces within values.
For example:
ENV myName="John Doe" myDog=Rex\ The\ Dog \
myCat=fluffy
and
ENV myName John Doe
ENV myDog Rex The Dog
ENV myCat fluffy
will yield the same net results in the final image.
The environment variables set using ENV
will persist when a container is run from the resulting image.
You can view the values using docker inspect
, and change them using docker run --env <key>=<value>
.
Note: Environment persistence can cause unexpected side effects. For example, setting
ENV DEBIAN_FRONTEND noninteractive
may confuse apt-get users on a Debian-based image.To set a value for a single command, use
RUN <key>=<value> <command>
.
ADD
ADD has two forms:
ADD [--chown=<user>:<group>] <src>... <dest>
-
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]
(this form is required for paths containing whitespace)
Note: The
--chown
feature is only supported on Dockerfiles used to build Linux containers, and will not work on Windows containers.Since user and group ownership concepts do not translate between Linux and Windows, the use of
/etc/passwd
and/etc/group
for translating user and group names to IDs restricts this feature to only be viable for Linux OS-based containers.
The ADD
instruction copies new files, directories or remote file URLs from <src>
and adds them to the filesystem of the image at the path <dest>
.
Multiple <src>
resources may be specified but if they are files or directories, their paths are interpreted as relative to the source of the context of the build.
Each <src>
may contain wildcards and matching will be done using Go’s filepath.Match rules.
For example:
ADD hom* /mydir/ # adds all files starting with "hom"
ADD hom?.txt /mydir/ # ? is replaced with any single character, e.g., "home.txt"
The <dest>
is an absolute path, or a path relative to WORKDIR
, into which the source will be copied inside the destination container.
ADD test relativeDir/ # adds "test" to `WORKDIR`/relativeDir/
ADD test /absoluteDir/ # adds "test" to /absoluteDir/
When adding files or directories that contain special characters (such as [
and ]
), you need to escape those paths following the Golang rules to prevent them from being treated as a matching pattern.
For example, to add a file named arr[0].txt
, use the following;
ADD arr[[]0].txt /mydir/ # copy a file named "arr[0].txt" to /mydir/
All new files and directories are created with a UID and GID of 0, unless the optional --chown
flag specifies a given username, groupname, or UID/GID combination to request specific ownership of the content added.
The format of the --chown
flag allows for either username and groupname strings or direct integer UID and GID in any combination.
Providing a username without groupname or a UID without GID will use the same numeric UID as the GID.
If a username or groupname is provided, the container’s root filesystem /etc/passwd
and /etc/group
files will be used to perform the translation from name to integer UID or GID respectively.
The following examples show valid definitions for the --chown
flag:
ADD --chown=55:mygroup files* /somedir/
ADD --chown=bin files* /somedir/
ADD --chown=1 files* /somedir/
ADD --chown=10:11 files* /somedir/
If the container root filesystem does not contain either /etc/passwd
or /etc/group
files and either user or group names are used in the --chown
flag, the build will fail on the ADD
operation.
Using numeric IDs requires no lookup and will not depend on container root filesystem content.
In the case where <src>
is a remote file URL, the destination will have permissions of 600.
If the remote file being retrieved has an HTTP Last-Modified
header, the timestamp from that header will be used to set the mtime
on the destination file. However, like any other file processed during an ADD
, mtime
will not be included in the determination of whether or not the file has changed and the cache should be updated.
Note: If you build by passing a
Dockerfile
through STDIN (docker build - < somefile
), there is no build context, so theDockerfile
can only contain a URL basedADD
instruction.You can also pass a compressed archive through STDIN: (
docker build - < archive.tar.gz
), theDockerfile
at the root of the archive and the rest of the archive will be used as the context of the build.
Note: If your URL files are protected using authentication, you will need to use
RUN wget
,RUN curl
or use another tool from within the container as theADD
instruction does not support authentication.
Note: The first encountered
ADD
instruction will invalidate the cache for all following instructions from the Dockerfile if the contents of<src>
have changed.This includes invalidating the cache for
RUN
instructions. See theDockerfile
Best Practices guide for more information.
ADD
obeys the following rules:
The
<src>
path must be inside the context of the build; you cannotADD ../something /something
, because the first step of adocker build
is to send the context directory (and subdirectories) to the docker daemon.If
<src>
is a URL and<dest>
does not end with a trailing slash, then a file is downloaded from the URL and copied to<dest>
.If
<src>
is a URL and<dest>
does end with a trailing slash, then the filename is inferred from the URL and the file is downloaded to<dest>/<filename>
. For instance,ADD http://example.com/foobar /
would create the file/foobar
. The URL must have a nontrivial path so that an appropriate filename can be discovered in this case (http://example.com
will not work).If
<src>
is a directory, the entire contents of the directory are copied, including filesystem metadata.
Note: The directory itself is not copied, just its contents.
-
If
<src>
is a local tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from remote URLs are not decompressed. When a directory is copied or unpacked, it has the same behavior astar -x
, the result is the union of:- Whatever existed at the destination path and
- The contents of the source tree, with conflicts resolved in favor of “2.” on a file-by-file basis.
Note: Whether a file is identified as a recognized compression format or not is done solely based on the contents of the file, not the name of the file.
For example, if an empty file happens to end with
.tar.gz
this will not be recognized as a compressed file and will not generate any kind of decompression error message, rather the file will simply be copied to the destination. If
<src>
is any other kind of file, it is copied individually along with its metadata. In this case, if<dest>
ends with a trailing slash/
, it will be considered a directory and the contents of<src>
will be written at<dest>/base(<src>)
.If multiple
<src>
resources are specified, either directly or due to the use of a wildcard, then<dest>
must be a directory, and it must end with a slash/
.If
<dest>
does not end with a trailing slash, it will be considered a regular file and the contents of<src>
will be written at<dest>
.If
<dest>
doesn’t exist, it is created along with all missing directories in its path.