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. This page describes the commands you can use in a Dockerfile.
Overview
The Dockerfile supports the following instructions:
| Instruction | Description |
|---|---|
ADD | Add local or remote files and directories. |
ARG | Use build-time variables. |
CMD | Specify default commands. |
COPY | Copy files and directories. |
ENTRYPOINT | Specify default executable. |
ENV | Set environment variables. |
EXPOSE | Describe which ports your application is listening on. |
FROM | Create a new build stage from a base image. |
HEALTHCHECK | Check a container's health on startup. |
LABEL | Add metadata to an image. |
MAINTAINER | Specify the author of an image. |
ONBUILD | Specify instructions for when the image is used in a build. |
RUN | Execute build commands. |
SHELL | Set the default shell of an image. |
STOPSIGNAL | Specify the system call signal for exiting a container. |
USER | Set user and group ID. |
VOLUME | Create volume mounts. |
WORKDIR | Change working directory. |
Format
Here is the format of the Dockerfile:
# Comment
INSTRUCTION argumentsThe 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
begin with a FROM instruction. This may be after parser
directives
, comments
, and globally scoped
ARGs
. 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.
BuildKit 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'Comment lines are removed before the Dockerfile instructions are executed.
The comment in the following example is removed before the shell executes
the echo command.
RUN echo hello \
# comment
worldThe following examples is equivalent.
RUN echo hello \
worldComments don't support line continuation characters.
NoteNote on whitespace
For backward compatibility, leading whitespace before comments (
#) and instructions (such asRUN) are ignored, but discouraged. Leading whitespace is not preserved in these cases, and the following examples are therefore equivalent:# this is a comment-line RUN echo hello RUN echo world# this is a comment-line RUN echo hello RUN echo worldWhitespace in instruction arguments, however, isn't ignored. The following example prints
hello worldwith leading whitespace as specified:RUN echo "\ hello\ world"
Parser directives
Parser directives are optional, and affect the way in which subsequent lines
in a Dockerfile are handled. Parser directives don't add layers to the build,
and don't show up as build steps. Parser directives are written as a
special type of comment in the form # directive=value. A single directive
may only be used once.
The following parser directives are supported:
Once a comment, empty line or builder instruction has been processed, BuildKit no longer looks for parser directives. Instead it treats anything formatted as a parser directive as a comment and doesn't attempt to validate if it might be a parser directive. Therefore, all parser directives must be at the top of a Dockerfile.
Parser directive keys, such as syntax or check, aren't case-sensitive, but
they're lowercase by convention. Values for a directive are case-sensitive and
must be written in the appropriate case for the directive. For example,
#check=skip=jsonargsrecommended is invalid because the check name must use
Pascal case, not lowercase. It's also conventional to include a blank line
following any parser directives. Line continuation characters aren't supported
in parser directives.
Due to these rules, the following examples are all invalid:
Invalid due to line continuation:
# direc \
tive=valueInvalid due to appearing twice:
# directive=value1
# directive=value2
FROM ImageNameTreated as a comment because it appears after a builder instruction:
FROM ImageName
# directive=valueTreated as a comment because it appears after a comment that isn't a parser directive:
# About my dockerfile
# directive=value
FROM ImageNameThe following unknowndirective is treated as a comment because it isn't
recognized. The known syntax directive is treated as a comment because it
appears after a comment that isn't a parser directive.
# unknowndirective=value
# syntax=valueNon line-breaking whitespace is permitted in a parser directive. Hence, the following lines are all treated identically:
#directive=value
# directive =value
# directive= value
# directive = value
# dIrEcTiVe=valuesyntax
Use the syntax parser directive to declare the Dockerfile syntax version to
use for the build. If unspecified, BuildKit uses a bundled version of the
Dockerfile frontend. Declaring a syntax version lets you automatically use the
latest Dockerfile version without having to upgrade BuildKit or Docker Engine,
or even use a custom Dockerfile implementation.
Most users will want to set this parser directive to docker/dockerfile:1,
which causes BuildKit to pull the latest stable version of the Dockerfile
syntax before the build.
# syntax=docker/dockerfile:1For more information about how the parser directive works, see Custom Dockerfile syntax .
escape
# escape=\Or
# escape=`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 E:\myproject> 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 E:\myproject>
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 E:\myproject> 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 E:\myproject>
check
# check=skip=<checks|all>
# check=error=<boolean>The check directive is used to configure how build checks
are evaluated. By default, all checks are run, and failures are treated as
warnings.
You can disable specific checks using #check=skip=<check-name>. To specify
multiple checks to skip, separate them with a comma:
# check=skip=JSONArgsRecommended,StageNameCasingTo disable all checks, use #check=skip=all.
By default, builds with failing build checks exit with a zero status code
despite warnings. To make the build fail on warnings, set #check=error=true.
# check=error=trueNoteWhen using the
checkdirective, witherror=trueoption, it is recommended to pin the Dockerfile syntax to a specific version. Otherwise, your build may start to fail when new checks are added in the future versions.
To combine both the skip and error options, use a semi-colon to separate
them:
# check=skip=JSONArgsRecommended;error=trueTo see all available checks, see the build checks reference
.
Note that the checks available depend on the Dockerfile syntax version. To make
sure you're getting the most up-to-date checks, use the syntax
directive to specify the Dockerfile syntax version to the latest stable
version.
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 ifvariableis set and non-empty then the result will be that value. Ifvariableis unset or empty thenwordwill be the result.${variable-word}indicates that ifvariableis set (even if empty) then the result will be that value. Ifvariableis unset thenwordwill be the result.${variable:+word}indicates that ifvariableis set and non-empty thenwordwill be the result, otherwise the result is the empty string.${variable+word}indicates that ifvariableis set (even if empty) thenwordwill be the result, otherwise the result is the empty string.
The following variable replacements are supported in a pre-release version of
Dockerfile syntax, when using the # syntax=docker/dockerfile-upstream:master syntax
directive in your Dockerfile:
${variable#pattern}removes the shortest match ofpatternfromvariable, seeking from the start of the string.str=foobarbaz echo ${str#f*b} # arbaz${variable##pattern}removes the longest match ofpatternfromvariable, seeking from the start of the string.str=foobarbaz echo ${str##f*b} # az${variable%pattern}removes the shortest match ofpatternfromvariable, seeking backwards from the end of the string.string=foobarbaz echo ${string%b*} # foobar${variable%%pattern}removes the longest match ofpatternfromvariable, seeking backwards from the end of the string.string=foobarbaz echo ${string%%b*} # foo${variable/pattern/replacement}replace the first occurrence ofpatterninvariablewithreplacementstring=foobarbaz echo ${string/ba/fo} # fooforbaz${variable//pattern/replacement}replaces all occurrences ofpatterninvariablewithreplacementstring=foobarbaz echo ${string//ba/fo} # fooforfoz
In all cases, word can be any string, including additional environment
variables.
pattern is a glob pattern where ? matches any single character
and * any number of characters (including zero). To match literal ? and *,
use a backslash escape: \? and \*.
You can escape whole variable names 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 /quuxEnvironment variables are supported by the following list of instructions in the Dockerfile:
ADDCOPYENVEXPOSEFROMLABELSTOPSIGNALUSERVOLUMEWORKDIRONBUILD(when combined with one of the supported instructions above)
You can also use environment variables with RUN, CMD, and ENTRYPOINT
instructions, but in those cases the variable substitution is handled by the
command shell, not the builder. Note that instructions using the exec form
don't invoke a command shell automatically. See Variable
substitution
.
Environment variable substitution use the same value for each variable throughout the entire instruction. Changing the value of a variable only takes effect in subsequent instructions. Consider the following example:
ENV abc=hello
ENV abc=bye def=$abc
ENV ghi=$abc- The value of
defbecomeshello - The value of
ghibecomesbye
.dockerignore file
You can use .dockerignore file to exclude files and directories from the
build context. For more information, see
.dockerignore file
.
Shell and exec form
The RUN, CMD, and ENTRYPOINT instructions all have two possible forms:
INSTRUCTION ["executable","param1","param2"](exec form)INSTRUCTION command param1 param2(shell form)
The exec form makes it possible to avoid shell string munging, and to invoke commands using a specific command shell, or any other executable. It uses a JSON array syntax, where each element in the array is a command, flag, or argument.
The shell form is more relaxed, and emphasizes ease of use, flexibility, and readability. The shell form automatically uses a command shell, whereas the exec form does not.
Exec form
The exec form is parsed as a JSON array, which means that you must use double-quotes (") around words, not single-quotes (').
ENTRYPOINT ["/bin/bash", "-c", "echo hello"]The exec form is best used to specify an ENTRYPOINT instruction, combined
with CMD for setting default arguments that can be overridden at runtime. For
more information, see ENTRYPOINT
.
Variable substitution
Using the exec form doesn't automatically invoke a command shell. This means
that normal shell processing, such as variable substitution, doesn't happen.
For example, RUN [ "echo", "$HOME" ] won't handle variable substitution for
$HOME.
If you want shell processing then either use the shell form or execute a shell
directly with the exec form, 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's the shell that's doing the environment variable substitution,
not the builder.
Backslashes
In exec form, you must 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"]Shell form
Unlike the exec form, instructions using the shell form always use a command shell. The shell form doesn't use the JSON array format, instead it's a regular string. The shell form string lets you escape newlines using the escape character (backslash by default) to continue a single instruction onto the next line. This makes it easier to use with longer commands, because it lets you split them up into multiple lines. For example, consider these two lines:
RUN source $HOME/.bashrc && \
echo $HOMEThey're equivalent to the following line:
RUN source $HOME/.bashrc && echo $HOMEYou can also use heredocs with the shell form to break up supported commands.
RUN <<EOF
source $HOME/.bashrc
echo $HOME
EOFFor more information about heredocs, see Here-documents .
Use a different shell
You can change the default shell using the SHELL command. For example:
SHELL ["/bin/bash", "-c"]
RUN echo helloFor more information, see SHELL .
FROM
FROM [--platform=<platform>] <image> [AS <name>]Or
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]Or
FROM [--platform=<platform>] <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.
ARGis the only instruction that may precedeFROMin the Dockerfile. See Understand how ARG and FROM interact .FROMcan appear multiple times within a single Dockerfile 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 newFROMinstruction. EachFROMinstruction clears any state created by previous instructions.Optionally a name can be given to a new build stage by adding
AS nameto theFROMinstruction. The name can be used in subsequentFROM <name>,COPY --from=<name>, andRUN --mount=type=bind,from=<name>instructions to refer to the image built in this stage.Using a previous build stage as the base for a subsequent stage is a common pattern for sharing a common base environment:
FROM ubuntu AS base RUN apt-get update && apt-get install -y shared-tooling FROM base AS dev RUN apt-get install -y dev-tooling FROM base AS prod COPY --from=build /app /appThe
tagordigestvalues are optional. If you omit either of them, the builder assumes alatesttag by default. The builder returns an error if it can't find thetagvalue.
The optional --platform flag can be used to specify the platform of the image
in case FROM references a multi-platform image. For example, linux/amd64,
linux/arm64, or windows/amd64. By default, the target platform of the build
request is used. Global build arguments can be used in the value of this flag,
for example automatic platform ARGs
allow you to force a stage to native build platform (--platform=$BUILDPLATFORM),
and use it to cross-compile to the target platform inside the stage.
FROM --reset
NoteNot yet available in stable syntax, use
docker/dockerfile:1-labsversion.
FROM --reset=<field>[,<field>...] <image> [AS <name>]The --reset flag clears configuration inherited from the base image, so
that changes in the base image don't affect these parts of your build. The
base image can be an image or another build stage. The flag can be repeated,
and its values aren't expanded with build arguments. The following fields can
be reset:
| Field | Effect |
|---|---|
cmd | Removes the default command |
entrypoint | Removes the entrypoint |
env | Removes environment variables like ENV --unset
, the default PATH is set again on Linux |
expose | Removes exposed ports |
healthcheck | Removes the health check |
label | Removes labels |
onbuild | Skips the ONBUILD
triggers of the base image |
shell | Restores the default shell |
stopsignal | Removes the stop signal |
user | Restores the default user |
volume | Removes volumes |
workdir | Restores the default working directory (/) |
all | Resets all of the above, and any fields added in future versions |
# syntax=docker/dockerfile:1-labs
FROM --reset=onbuild,volume,label postgres
LABEL org.opencontainers.image.title="my-postgres"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-extrasAn 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_versionRUN
The RUN instruction will execute any commands to create a new layer on top of
the current image. The added layer is used in the next step in the Dockerfile.
RUN has two forms:
# Shell form:
RUN [OPTIONS] <command> ...
# Exec form:
RUN [OPTIONS] [ "<command>", ... ]For more information about the differences between these two forms, see shell or exec forms .
The shell form is most commonly used, and lets you break up longer instructions into multiple lines, either using newline escapes , or with heredocs :
RUN <<EOF
apt-get update
apt-get install -y curl
EOFThe available [OPTIONS] for the RUN instruction are:
| Option | Minimum Dockerfile version |
|---|---|
--device | 1.27 |
--mount | 1.2 |
--network | 1.3 |
--security | 1.20 |
Cache invalidation for RUN instructions
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
and COPY
instructions.
RUN --device
NoteThis option needs BuildKit 0.20.0 or later.
RUN --device=name,[required]RUN --device allows build to request CDI devices
to be available to the build step.
WarningThe use of
--deviceis protected by thedeviceentitlement, which needs to be enabled when starting the buildkitd daemon with--allow-insecure-entitlement deviceflag or in buildkitd config , and for a build request with--allow deviceflag .
The device name is provided by the CDI specification registered in BuildKit.
In the following example, multiple devices are registered in the CDI
specification for the vendor1.com/device vendor.
cdiVersion: "0.6.0"
kind: "vendor1.com/device"
devices:
- name: foo
containerEdits: