Dockerfile Reference Docker Docs
Dockerfile Reference Docker Docs
com/reference/dockerfile/#from
Dockerfile reference
Docker can build images automatically by reading the instructions from a Docker�le. A
Docker�le 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
Docker�le.
Overview
The Docker�le supports the following instructions:
Give feedback
ADD Add local or remote �les and directories.
1 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Format
Here is the format of the Docker�le:
Give feedback
# Comment
INSTRUCTION arguments
. This may be after parser directives, comments, and globally scoped ARGs. The
FROM instruction speci�es the parent 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 Docker�le.
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:
2 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
# Comment
RUN echo 'we are running some # of cool things'
Comment lines are removed before the Docker�le instructions are executed. The comment
in the following example is removed before the shell executes the echo command.
Give feedback
Comments don't support line continuation characters.
# this is a comment-line
RUN echo hello
RUN echo world
# this is a comment-line
RUN echo hello
RUN echo world
3 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Parser directives
Parser directives are optional, and a�ect the way in which subsequent lines in a Docker�le
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.
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 Docker�le.
Give feedback
Parser directives aren't case-sensitive, but they're lowercase by convention. It's also
conventional to include a blank line following any parser directives. Line continuation
characters aren't supported in parser directives.
# direc \
tive=value
# directive=value1
# directive=value2
FROM ImageName
4 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
FROM ImageName
# directive=value
Treated as a comment because it appears after a comment that isn't a parser directive:
# About my dockerfile
# directive=value
FROM ImageName
Give feedback
# unknowndirective=value
# syntax=value
Non 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=value
• syntax
• escape
syntax
5 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Use the syntax parser directive to declare the Docker�le syntax version to use for the build.
If unspeci�ed, BuildKit uses a bundled version of the Docker�le frontend. Declaring a syntax
version lets you automatically use the latest Docker�le version without having to upgrade
BuildKit or Docker Engine, or even use a custom Docker�le 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 Docker�le syntax before the build.
# syntax=docker/dockerfile:1
For more information about how the parser directive works, see Custom Docker�le syntax
.
escape
Give feedback
# escape=\
Or
# escape=`
The escape directive sets the character used to escape characters in a Docker�le. If not
speci�ed, 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 Docker�le instruction to span multiple lines. Note that regardless of whether
the escape parser directive is included in a Docker�le, escaping is not performed in a RUN
command, except at the end of a line.
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,
6 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
instead of a target of the escape from the �rst \ . 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 Docker�le is that second and third lines are considered a
single instruction:
FROM microsoft/nanoserver
COPY testfile.txt c:\\
RUN dir c:\
Results in:
Give feedback
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 Docker�le succeeds as expected with
the use of natural platform semantics for �le paths on Windows:
# escape=`
FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
Results in:
7 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Directory of c:\
Give feedback
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>
Environment replacement
Environment variables (declared with the ENV statement) can also be used in certain
instructions as variables to be interpreted by the Docker�le. Escapes are also handled for
including variable-like syntax into a statement literally.
8 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The ${variable_name} syntax also supports a few of the standard bash modi�ers as
speci�ed below:
• ${variable:-word} indicates that if variable is set then the result will be that value.
• ${variable:+word} indicates that if variable is set then word will be the result,
Give feedback
• ${variable##pattern} removes the longest match of pattern from variable ,
9 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
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.
Give feedback
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 Docker�le:
• ADD
• COPY
• ENV
• EXPOSE
• FROM
• LABEL
• STOPSIGNAL
10 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
• USER
• VOLUME
• WORKDIR
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 e�ect in subsequent instructions.
Consider the following example:
ENV abc=hello
Give feedback
ENV abc=bye def=$abc
ENV ghi=$abc
.dockerignore �le
You can use .dockerignore �le to exclude �les and directories from the build context. For
more information, see .dockerignore �le .
11 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The exec form makes it possible to avoid shell string munging, and to invoke commands
using a speci�c command shell, or any other executable. It uses a JSON array syntax, where
each element in the array is a command, �ag, or argument.
The shell form is more relaxed, and emphasizes ease of use, �exibility, 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 (').
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
Give feedback
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:
12 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
RUN ["c:\windows\system32\tasklist.exe"]
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:
Give feedback
RUN source $HOME/.bashrc && \
echo $HOME
You can also use heredocs with the shell form to break up a command:
RUN <<EOF
source $HOME/.bashrc && \
echo $HOME
EOF
13 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
You can change the default shell using the SHELL command. For example:
FROM
FROM [--platform=<platform>] <image> [AS <name>]
Or
Give feedback
Or
The FROM instruction initializes a new build stage and sets the base image for
subsequent instructions. As such, a valid Docker�le must start with a FROM instruction. The
image can be any valid image.
• ARG is the only instruction that may precede FROM in the Docker�le. See Understand
• FROM can appear multiple times within a single Docker�le 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 new FROM instruction. Each FROM instruction
clears any state created by previous instructions.
• Optionally a name can be given to a new build stage by adding AS name to the FROM
instruction. The name can be used in subsequent FROM and COPY --from=<name>
instructions to refer to the image built in this stage.
14 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
• The tag or digest values are optional. If you omit either of them, the builder
assumes a latest tag by default. The builder returns an error if it can't �nd the tag
value.
The optional --platform �ag 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 �ag, 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.
Give feedback
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 �rst 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
The RUN instruction will execute any commands to create a new layer on top of the current
15 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
image. The added layer is used in the next step in the Docker�le.
The shell form is most commonly used, and lets you more easily break up longer
instructions into multiple lines, either using newline escapes, or with heredocs:
RUN <<EOF
apt-get update
apt-get install -y curl
Give feedback
EOF
The cache for RUN instructions can be invalidated by ADD and COPY instructions.
RUN --mount
Added in docker/dockerfile:1.2
16 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
RUN --mount allows you to create �lesystem mounts that the build can access. This can be
used to:
Syntax: --mount=[type=<TYPE>][,option=<value>[,option=<value>]...]
Mount types
Give feedback
cache Mount a temporary directory to cache directories for compilers and package
managers.
secret Allow the build container to access secure �les such as private keys without baking
them into the image.
ssh Allow the build container to access SSH keys via SSH agents, with support for
passphrases.
RUN --mount=type=bind
This mount type allows binding �les or directories to the build container. A bind mount is
read-only by default.
source Source path in the from . Defaults to the root of the from .
from Build stage or image name for the root of the source. Defaults to the build context.
17 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
RUN --mount=type=cache
This mount type allows the build container to cache directories for compilers and package
managers.
ro , Read-only if set.
readonly
Give feedback
sharing One of shared , private , or locked . Defaults to shared . A shared cache mount
can be used concurrently by multiple writers. private creates a new mount if there are
multiple writers. locked pauses the second writer until the �rst one releases the
mount.
from Build stage to use as a base of the cache mount. Defaults to empty directory.
source Subpath in the from to mount. Defaults to the root of the from .
mode File mode for new cache directory in octal. Default 0755 .
Contents of the cache directories persists between builder invocations without invalidating
the instruction cache. Cache mounts should only be used for better performance. Your build
should work with any contents of the cache directory as another build may overwrite the
�les or GC may clean it if more storage space is needed.
18 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
# syntax=docker/dockerfile:1
FROM golang
RUN --mount=type=cache,target=/root/.cache/go-build \
go build ...
# syntax=docker/dockerfile:1
FROM ubuntu
RUN rm -f /etc/apt/apt.conf.d/docker-clean; echo 'Binary::apt::APT::Keep-Downloaded-P
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
apt update && apt-get --no-install-recommends install -y gcc
Apt needs exclusive access to its data, so the caches use the option sharing=locked ,
which will make sure multiple parallel builds using the same cache mount will wait for each
Give feedback
other and not access the same cache �les at the same time. You could also use
sharing=private if you prefer to have each build create another cache directory in this
case.
RUN --mount=type=tmpfs
This mount type allows mounting tmpfs in the build container.
RUN --mount=type=secret
This mount type allows the build container to access secure �les such as private keys
without baking them into the image.
19 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
required If set to true , the instruction errors out when the secret is unavailable. Defaults to
false .
Example: access to S3
# syntax=docker/dockerfile:1
FROM python:3
Give feedback
RUN pip install awscli
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials \
aws s3 cp s3://... ...
RUN --mount=type=ssh
This mount type allows the build container to access SSH keys via SSH agents, with support
for passphrases.
required If set to true , the instruction errors out when the key is unavailable. Defaults to false .
20 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
# syntax=docker/dockerfile:1
FROM alpine
RUN apk add --no-cache openssh-client
RUN mkdir -p -m 0700 ~/.ssh && ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
RUN --mount=type=ssh \
ssh -q -T [email protected] 2>&1 | tee /hello
# "Welcome to GitLab, @GITLAB_USERNAME_ASSOCIATED_WITH_SSHKEY" should be printed here
# with the type of build progress is defined as `plain`.
Give feedback
$ eval $(ssh-agent)
$ ssh-add ~/.ssh/id_rsa
(Input your passphrase here)
$ docker buildx build --ssh default=$SSH_AUTH_SOCK .
You can also specify a path to *.pem �le on the host directly instead of $SSH_AUTH_SOCK .
However, pem �les with passphrases are not supported.
RUN --network
Added in docker/dockerfile:1.1
RUN --network allows control over which networking environment the command is run in.
Syntax: --network=<TYPE>
21 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Network types
RUN --network=default
Equivalent to not supplying a �ag at all, the command is run in the default network for the
build.
RUN --network=none
Give feedback
The command is run with no network access ( lo is still available, but is isolated to this
process)
# syntax=docker/dockerfile:1
FROM python:3.6
ADD mypackage.tgz wheels/
RUN --network=none pip install --find-links wheels mypackage
pip will only be able to install the packages provided in the tar�le, which can be controlled
RUN --network=host
The command is run in the host's network environment (similar to
docker build --network=host , but on a per-instruction basis)
22 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
RUN --security
RUN --security=insecure
With --security=insecure , builder runs the command without sandbox in insecure mode,
Give feedback
which allows to run �ows requiring elevated privileges (e.g. containerd). This is equivalent to
running docker run --privileged .
# syntax=docker/dockerfile:1-labs
FROM ubuntu
RUN --security=insecure cat /proc/self/status | grep CapEff
23 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
RUN --security=sandbox
Default sandbox mode can be activated via --security=sandbox , but that is no-op.
CMD
The CMD instruction sets the command to be executed when running a container from an
image.
There can only be one CMD instruction in a Docker�le. If you list more than one CMD , only
Give feedback
the last one takes e�ect.
The 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.
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
speci�es arguments to docker run then they will override the default speci�ed in CMD , but
still use the default ENTRYPOINT .
If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD
and ENTRYPOINT instructions should be speci�ed in the exec form.
Don't confuse RUN with CMD . RUN actually runs a command and commits the
result; CMD doesn't execute anything at build time, but speci�es the intended
command for the image.
24 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
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:
An image can have more than one label. You can specify multiple labels on a single line.
Give feedback
Prior to Docker 1.10, this decreased the size of the �nal 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"
Be sure to use double quotes and not single quotes. Particularly when you are using
string interpolation (e.g. LABEL example="foo-$ENV_VAR" ), single quotes will take
the string as is without unpacking the variable's value.
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 di�erent value, the most-recently-applied value
25 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
To view an image's labels, use the docker image inspect command. You can use the
--format option to show just the 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"
}
Give feedback
MAINTAINER (deprecated)
MAINTAINER <name>
The MAINTAINER instruction sets the Author �eld of the generated images. The LABEL
instruction is a much more �exible 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 �eld you could use:
LABEL org.opencontainers.image.authors="[email protected]"
This will then be visible from docker inspect with the other labels.
EXPOSE
EXPOSE <port> [<port>/<protocol>...]
26 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The EXPOSE instruction informs Docker that the container listens on the speci�ed network
ports at runtime. You can specify whether the port listens on TCP or UDP, and the default is
TCP if you don't specify a protocol.
The EXPOSE instruction doesn't 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 publish the port when running
the container, use the -p �ag on docker run to publish and map one or more ports, or
the -P �ag to publish all exposed ports and map them to high-order ports.
EXPOSE 80/udp
Give feedback
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
TCP and UDP doesn't use the same port.
Regardless of the EXPOSE settings, you can override them at runtime by using the -p �ag.
For example
To set up port redirection on the host system, see using the -P �ag . The docker network
command supports creating networks for communication among containers without the
need to expose or publish speci�c 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 .
27 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
ENV
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 value will be interpreted for other environment variables,
so quote characters will be removed if they are not escaped. Like command line parsing,
quotes and backslashes can be used to include spaces within values.
Example:
Give feedback
The ENV instruction allows for multiple <key>=<value> ... variables to be set at one
time, and the example below will yield the same net results in the �nal 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> .
A stage inherits any environment variables that were set using ENV by its parent stage or
any ancestor. Refer here for more on multi-staged builds.
Environment variable persistence can cause unexpected side e�ects. For example, setting
ENV DEBIAN_FRONTEND=noninteractive changes the behavior of apt-get , and may
If an environment variable is only needed during build, and not in the �nal image, consider
setting a value for a single command instead:
28 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y ...
The ENV instruction also allows an alternative syntax ENV <key> <value> ,
omitting the = . For example:
Give feedback
This syntax does not allow for multiple environment-variables to be set in a single
ENV instruction, and can be confusing. For example, the following sets a single
The alternative syntax is supported for backward compatibility, but discouraged for
the reasons outlined above, and may be removed in a future release.
ADD
ADD has two forms:
29 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The --chown and --chmod features are only supported on Docker�les used to build
Linux containers, and doesn't 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
The ADD instruction copies new �les, directories or remote �le URLs from <src> and adds
Give feedback
them to the �lesystem of the image at the path <dest> .
Multiple <src> resources may be speci�ed but if they are �les 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 �lepath.Match
rules. For example:
In the example below, ? 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.
30 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The example below uses a relative path, and adds "test.txt" to <WORKDIR>/relativeDir/ :
Whereas this example uses an absolute path, and adds "test.txt" to /absoluteDir/
When adding �les 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 �le named arr[0].txt , use the following;
All new �les and directories are created with a UID and GID of 0, unless the optional
Give feedback
--chown �ag speci�es a given username, groupname, or UID/GID combination to request
speci�c ownership of the content added. The format of the --chown �ag 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 �lesystem
/etc/passwd and /etc/group �les will be used to perform the translation from name to
integer UID or GID respectively. The following examples show valid de�nitions for the
--chown �ag:
If the container root �lesystem doesn't contain either /etc/passwd or /etc/group �les
and either user or group names are used in the --chown �ag, the build will fail on the ADD
operation. Using numeric IDs requires no lookup and doesn't depend on container root
�lesystem content.
31 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
In the case where <src> is a remote �le URL, the destination will have permissions of 600.
If the remote �le being retrieved has an HTTP Last-Modified header, the timestamp from
that header will be used to set the mtime on the destination �le. However, like any other �le
processed during an ADD , mtime isn't included in the determination of whether or not the
�le has changed and the cache should be updated.
If you build by passing a Docker�le through STDIN ( docker build - < somefile ),
there is no build context, so the Docker�le can only contain a URL based ADD
instruction. You can also pass a compressed archive through STDIN: (
docker build - < archive.tar.gz ), the Docker�le at the root of the archive and
the rest of the archive will be used as the context of the build.
If your URL �les are protected using authentication, you need to use RUN wget , RUN curl
Give feedback
or use another tool from within the container as the ADD instruction doesn't support
authentication.
The �rst encountered ADD instruction will invalidate the cache for all following
instructions from the Docker�le if the contents of <src> have changed. This
includes invalidating the cache for RUN instructions. See the Docker�le Best
Practices guide – Leverage build cache for more information.
• The <src> path must be inside the build context; you can't use
ADD ../something /something , because the builder can only access �les from the
context, and ../something speci�es a parent �le or directory of the build context root.
• If <src> is a URL and <dest> does end with a trailing slash, then the �lename is
inferred from the URL and the �le is downloaded to <dest>/<filename> . For instance,
ADD http://example.com/foobar / would create the �le /foobar . The URL must
32 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
have a nontrivial path so that an appropriate �lename can be discovered in this case (
http://example.com doesn't work).
• If <src> is a directory, the entire contents of the directory are copied, including
�lesystem metadata.
2. The contents of the source tree, with con�icts resolved in favor of "2." on a �le-by-
�le basis.
Give feedback
Whether a �le is identi�ed as a recognized compression format or not is done
solely based on the contents of the �le, not the name of the �le. For example, if
an empty �le happens to end with .tar.gz this isn't recognized as a
compressed �le and doesn't generate any kind of decompression error
message, rather the �le will simply be copied to the destination.
• If <src> is any other kind of �le, it's 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 speci�ed, either directly or due to the use of a wildcard,
then <dest> must be a directory, and it must end with a slash / .
• If <src> is a �le, and <dest> doesn't end with a trailing slash, the contents of <src>
will be written as �lename <dest> .
• If <dest> doesn't exist, it's created, along with all missing directories in its path.
33 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
ADD --checksum=sha256:24454f830cdb571e2c4ad15481119c43b3cafd48dd869a9b2945d1036d1dc68
Give feedback
# syntax=docker/dockerfile:1
FROM alpine
ADD --keep-git-dir=true https://github.com/moby/buildkit.git#v0.10.1 /buildkit
The --keep-git-dir=true �ag adds the .git directory. This �ag defaults to false.
# syntax=docker/dockerfile:1
FROM alpine
ADD [email protected]:foo/bar.git /bar
This Docker�le can be built with docker build --ssh or buildctl build --ssh , e.g.,
34 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
ADD --link
See COPY --link .
COPY
COPY has two forms:
Give feedback
The --chown and --chmod features are only supported on Docker�les used to build
Linux containers, and doesn't 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
The COPY instruction copies new �les or directories from <src> and adds them to the
�lesystem of the container at the path <dest> .
Multiple <src> resources may be speci�ed but the paths of �les and directories will be
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 �lepath.Match
rules. For example:
35 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
In the example below, ? 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.
The example below uses a relative path, and adds "test.txt" to <WORKDIR>/relativeDir/ :
Whereas this example uses an absolute path, and adds "test.txt" to /absoluteDir/
Give feedback
COPY test.txt /absoluteDir/
When copying �les 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 copy a �le named arr[0].txt , use the following;
All new �les and directories are created with a UID and GID of 0, unless the optional
--chown �ag speci�es a given username, groupname, or UID/GID combination to request
speci�c ownership of the copied content. The format of the --chown �ag 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 �lesystem
/etc/passwd and /etc/group �les will be used to perform the translation from name to
integer UID or GID respectively. The following examples show valid de�nitions for the
--chown �ag:
36 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
If the container root �lesystem doesn't contain either /etc/passwd or /etc/group �les
and either user or group names are used in the --chown �ag, the build will fail on the COPY
operation. Using numeric IDs requires no lookup and does not depend on container root
�lesystem content.
If you build using STDIN ( docker build - < somefile ), there is no build context,
so COPY can't be used.
Give feedback
Optionally COPY accepts a �ag --from=<name> that can be used to set the source location
to a previous build stage (created with FROM .. AS <name> ) that will be used instead of a
build context sent by the user. In case a build stage with a speci�ed name can't be found an
image with the same name is attempted to be used instead.
• The <src> path must be inside the build context; you can't use
COPY ../something /something , because the builder can only access �les from the
context, and ../something speci�es a parent �le or directory of the build context root.
• If <src> is a directory, the entire contents of the directory are copied, including
�lesystem metadata.
• If <src> is any other kind of �le, it's copied individually along with its metadata. In this
case, if <dest> ends with a trailing slash / , it will be considered a directory and the
37 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
• If multiple <src> resources are speci�ed, either directly or due to the use of a wildcard,
then <dest> must be a directory, and it must end with a slash / .
• If <src> is a �le, and <dest> doesn't end with a trailing slash, the contents of <src>
will be written as �lename <dest> .
• If <dest> doesn't exist, it's created, along with all missing directories in its path.
The �rst encountered COPY instruction will invalidate the cache for all following
instructions from the Docker�le if the contents of <src> have changed. This
includes invalidating the cache for RUN instructions. See the Docker�le Best
Practices guide – Leverage build cache for more information.
Give feedback
COPY --link
Added in docker/dockerfile:1.4
Enabling this �ag in COPY or ADD commands allows you to copy �les with enhanced
semantics where your �les remain independent on their own layer and don't get invalidated
when commands on previous layers are changed.
When --link is used your source �les are copied into an empty destination directory. That
directory is turned into a layer that is linked on top of your previous state.
# syntax=docker/dockerfile:1
FROM alpine
COPY --link /foo /bar
38 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
FROM alpine
and
FROM scratch
COPY /foo /bar
same stage changed, causing the need to rebuild the intermediate stages again. With
Give feedback
--link the layer the previous build generated is reused and merged on top of the new
layers. This also means you can easily rebase your images when the base images receive
updates, without having to execute the whole build again. In backends that support it,
BuildKit can do this rebase action without the need to push or pull any layers between the
client and the registry. BuildKit will detect this case and only create new image manifest that
contains the new layers and old layers in correct order.
The same behavior where BuildKit can avoid pulling down the base image can also happen
when using --link and no other commands that would require access to the �les in the
base image. In that case BuildKit will only build the layers for the COPY commands and
push them to the registry directly on top of the layers of the base image.
39 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
If you don't rely on the behavior of following symlinks in the destination path, using --link
is always recommended. The performance of --link is equivalent or better than the
default behavior and, it creates much better conditions for cache reuse.
COPY --parents
The --parents �ag preserves parent directories for src entries. This �ag defaults to
Give feedback
false .
# syntax=docker/dockerfile-upstream:master-labs
FROM scratch
# /no_parents/a.txt
# /parents/x/a.txt
# /parents/y/a.txt
Note that, without the --parents �ag speci�ed, any �lename collision will fail the Linux
cp operation with an explicit error message (
cp: will not overwrite just-created './x/a.txt' with './y/a.txt' ), where the
While it is possible to preserve the directory structure for COPY instructions consisting of
40 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
only one src entry, usually it is more bene�cial to keep the layer count in the resulting
image as low as possible. Therefore, with the --parents �ag, the Buildkit is capable of
packing multiple COPY instructions together, keeping the directory structure intact.
ENTRYPOINT
An ENTRYPOINT allows you to con�gure a container that will run as an executable.
Give feedback
ENTRYPOINT command param1 param2
For more information about the di�erent forms, see Shell and exec form.
The following command starts a container from the nginx with its default content, listening
on port 80:
Command line arguments to docker run <image> will be appended after all elements in
an exec form ENTRYPOINT , and will override all elements speci�ed using CMD .
This allows arguments to be passed to the entry point, i.e., docker run <image> -d will
pass the -d argument to the entry point. You can override the ENTRYPOINT instruction
using the docker run --entrypoint �ag.
The shell form of ENTRYPOINT prevents any CMD command line arguments from being
used. It also starts your ENTRYPOINT as a subcommand of /bin/sh -c , which does not
pass signals. This means that the executable will not be the container's PID 1 , and will not
41 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
receive Unix signals. In this case, your executable doesn't receive a SIGTERM from
docker stop <container> .
Only the last ENTRYPOINT instruction in the Docker�le will have an e�ect.
FROM ubuntu
ENTRYPOINT ["top", "-b"]
CMD ["-c"]
When you run the container, you can see that top is the only process:
Give feedback
$ docker run -it --rm --name test top -H
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H
root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux
42 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
And you can gracefully request top to shut down using docker stop test .
The following Docker�le shows using the ENTRYPOINT to run Apache in the foreground (i.e.,
as PID 1 ):
FROM debian:stable
RUN apt-get update && apt-get install -y --force-yes apache2
EXPOSE 80 443
VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"]
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
If you need to write a starter script for a single executable, you can ensure that the �nal
executable receives the Unix signals by using exec and gosu commands:
#!/usr/bin/env bash
set -e
Give feedback
if [ "$1" = 'postgres' ]; then
chown -R postgres "$PGDATA"
exec "$@"
Lastly, if you need to do some extra cleanup (or communicate with other containers) on
shutdown, or are co-ordinating more than one executable, you may need to ensure that the
ENTRYPOINT script receives the Unix signals, passes them on, and then does some more
work:
#!/bin/sh
# Note: I've written this using sh so it works in the busybox container too
43 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
# USE the trap if you need to also do manual cleanup after the service is stopped,
# or need to start multiple services in the one container
trap "echo TRAPed signal" HUP INT QUIT TERM
Give feedback
If you run this image with docker run -it --rm -p 80:80 --name test apache , you can
then examine the container's processes with docker exec , or docker top , and then ask
the script to stop Apache:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123
root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k
www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k
www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k
root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux
44 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
test
real 0m 0.27s
user 0m 0.03s
sys 0m 0.03s
You can override the ENTRYPOINT setting using --entrypoint , but this can only
set the binary to exec (no sh -c will be used).
Give feedback
form will use shell processing to substitute shell environment variables, and will ignore any
CMD or docker run command line arguments. To ensure that docker stop will signal
any long running ENTRYPOINT executable correctly, you need to remember to start it with
exec :
FROM ubuntu
ENTRYPOINT exec top -b
When you run this image, you'll see the single PID 1 process:
45 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
test
real 0m 0.20s
user 0m 0.02s
sys 0m 0.04s
FROM ubuntu
ENTRYPOINT top -b
CMD -- --ignored-param1
You can then run it (giving it a name for the next step):
Give feedback
top - 13:58:24 up 17 min, 0 users, load average: 0.00, 0.00, 0.00
Tasks: 2 total, 1 running, 1 sleeping, 0 stopped, 0 zombie
%Cpu(s): 16.7 us, 33.3 sy, 0.0 ni, 50.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 1990.8 total, 1354.6 free, 231.4 used, 404.7 buff/cache
MiB Swap: 1024.0 total, 1024.0 free, 0.0 used. 1639.8 avail Mem
You can see from the output of top that the speci�ed ENTRYPOINT is not PID 1 .
If you then run docker stop test , the container will not exit cleanly - the stop command
will be forced to send a SIGKILL after the timeout:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.4 0.0 2612 604 pts/0 Ss+ 13:58 0:00 /bin/sh -c top -b --
46 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
test
real 0m 10.19s
user 0m 0.04s
sys 0m 0.03s
Give feedback
2. ENTRYPOINT should be de�ned when using the container as an executable.
4. CMD will be overridden when running the container with alternative arguments.
The table below shows what command is executed for di�erent ENTRYPOINT / CMD
combinations:
47 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
If CMD is de�ned from the base image, setting ENTRYPOINT will reset CMD to an
empty value. In this scenario, CMD must be de�ned in the current image to have a
value.
VOLUME
VOLUME ["/data"]
The VOLUME instruction creates a mount point with the speci�ed name and marks it as
holding externally mounted volumes from native host or other containers. The value can be a
JSON array, VOLUME ["/var/log/"] , or a plain string with multiple arguments, such as
VOLUME /var/log or VOLUME /var/log /var/db . For more information/examples and
Give feedback
mounting instructions via the Docker client, refer to Share Directories via Volumes
documentation.
The docker run command initializes the newly created volume with any data that exists at
the speci�ed location within the base image. For example, consider the following Docker�le
snippet:
FROM ubuntu
RUN mkdir /myvol
RUN echo "hello world" > /myvol/greeting
VOLUME /myvol
This Docker�le results in an image that causes docker run to create a new mount point at
/myvol and copy the greeting �le into the newly created volume.
48 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
• : The list is parsed as a JSON array. You must enclose words with
double quotes ( " ) rather than single quotes ( ' ).
Give feedback
USER
USER <user>[:<group>]
or
USER UID[:GID]
The USER instruction sets the user name (or UID) and optionally the user group (or GID) to
use as the default user and group for the remainder of the current stage. The speci�ed user
is used for RUN instructions and at runtime, runs the relevant ENTRYPOINT and CMD
commands.
Note that when specifying a group for the user, the user will have only the
speci�ed group membership. Any other con�gured group memberships will be
ignored.
49 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
When the user doesn't have a primary group then the image (or the next instructions)
will be run with the root group.
On Windows, the user must be created �rst if it's not a built-in account. This can be
done with the net user command called as part of a Docker�le.
FROM microsoft/windowsservercore
# Create Windows user in the container
RUN net user /add patrick
# Set it for subsequent commands
USER patrick
WORKDIR
Give feedback
WORKDIR /path/to/workdir
The WORKDIR instruction sets the working directory for any RUN , CMD , ENTRYPOINT , COPY
and ADD instructions that follow it in the Docker�le. If the WORKDIR doesn't exist, it will be
created even if it's not used in any subsequent Docker�le instruction.
The WORKDIR instruction can be used multiple times in a Docker�le. If a relative path is
provided, it will be relative to the path of the previous WORKDIR instruction. For example:
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd
The output of the �nal pwd command in this Docker�le would be /a/b/c .
The WORKDIR instruction can resolve environment variables previously set using ENV . You
can only use environment variables explicitly set in the Docker�le. For example:
50 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd
The output of the �nal pwd command in this Docker�le would be /path/$DIRNAME
If not speci�ed, the default working directory is / . In practice, if you aren't building a
Docker�le from scratch ( FROM scratch ), the WORKDIR may likely be set by the base image
you're using.
Therefore, to avoid unintended operations in unknown directories, it's best practice to set
your WORKDIR explicitly.
ARG
Give feedback
ARG <name>[=<default value>]
The ARG instruction de�nes a variable that users can pass at build-time to the builder with
the docker build command using the --build-arg <varname>=<value> �ag.
It isn't recommended to use build arguments for passing secrets such as user
credentials, API tokens, etc. Build arguments are visible in the docker history
command and in max mode provenance attestations, which are attached to the
image by default if you use the Buildx GitHub Actions and your GitHub repository is
public.
Refer to the RUN --mount=type=secret section to learn about secure ways to use
secrets when building images.
If you specify a build argument that wasn't de�ned in the Docker�le, the build outputs a
warning.
51 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
A Docker�le may include one or more ARG instructions. For example, the following is a valid
Docker�le:
FROM busybox
ARG user1
ARG buildno
# ...
Default values
An ARG instruction can optionally include a default value:
FROM busybox
Give feedback
ARG user1=someuser
ARG buildno=1
# ...
If an ARG instruction has a default value and if there is no value passed at build-time, the
builder uses the default.
Scope
An ARG variable de�nition comes into e�ect from the line on which it is de�ned in the
Docker�le not from the argument's use on the command-line or elsewhere. For example,
consider this Docker�le:
FROM busybox
USER ${username:-some_user}
ARG username
USER $username
# ...
52 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The USER at line 2 evaluates to some_user as the username variable is de�ned on the
subsequent line 3. The USER at line 4 evaluates to what_user , as the username argument
is de�ned and the what_user value was passed on the command line. Prior to its de�nition
by an ARG instruction, any use of a variable results in an empty string.
An ARG instruction goes out of scope at the end of the build stage where it was de�ned. To
use an argument in multiple stages, each stage must include the ARG instruction.
FROM busybox
ARG SETTINGS
RUN ./run/setup $SETTINGS
Give feedback
FROM busybox
ARG SETTINGS
RUN ./run/other $SETTINGS
instruction.
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=v1.0.0
RUN echo $CONT_IMG_VER
53 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
In this case, the RUN instruction uses v1.0.0 instead of the ARG setting passed by the
user: v2.0.1 This behavior is similar to a shell script where a locally scoped variable
overrides the variables passed as arguments or inherited from environment, from its point of
de�nition.
Using the example above but a di�erent ENV speci�cation you can create more useful
interactions between ARG and ENV instructions:
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=${CONT_IMG_VER:-v1.0.0}
RUN echo $CONT_IMG_VER
Unlike an ARG instruction, ENV values are always persisted in the built image. Consider a
Give feedback
docker build without the --build-arg �ag:
$ docker build .
Using this Docker�le example, CONT_IMG_VER is still persisted in the image but its value
would be v1.0.0 as it is the default set in line 3 by the ENV instruction.
The variable expansion technique in this example allows you to pass arguments from the
command line and persist them in the �nal image by leveraging the ENV instruction.
Variable expansion is only supported for a limited set of Docker�le instructions.
Predefined ARGs
Docker has a set of prede�ned ARG variables that you can use without a corresponding
ARG instruction in the Docker�le.
• HTTP_PROXY
• http_proxy
54 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
• HTTPS_PROXY
• https_proxy
• FTP_PROXY
• ftp_proxy
• NO_PROXY
• no_proxy
• ALL_PROXY
• all_proxy
To use these, pass them on the command line using the --build-arg �ag, for example:
Give feedback
By default, these pre-de�ned variables are excluded from the output of docker history .
Excluding them reduces the risk of accidentally leaking sensitive authentication information
in an HTTP_PROXY variable.
FROM ubuntu
RUN echo "Hello World"
In this case, the value of the HTTP_PROXY variable is not available in the docker history
and is not cached. If you were to change location, and your proxy server changed to
http://user:[email protected] , a subsequent build does not result in a
cache miss.
If you need to override this behaviour then you may do so by adding an ARG statement in
the Docker�le as follows:
FROM ubuntu
55 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
ARG HTTP_PROXY
RUN echo "Hello World"
When building this Docker�le, the HTTP_PROXY is preserved in the docker history , and
changing its value invalidates the build cache.
BuildKit supports a prede�ned set of ARG variables with information on the platform of the
node performing the build (build platform) and on the platform of the resulting image (target
platform). The target platform can be speci�ed with the --platform �ag on
docker build .
Give feedback
• TARGETPLATFORM - platform of the build result. Eg linux/amd64 , linux/arm/v7 ,
windows/amd64 .
These arguments are de�ned in the global scope so are not automatically available inside
build stages or for your RUN commands. To expose one of these arguments inside the build
stage rede�ne it without value.
For example:
56 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
FROM alpine
ARG TARGETPLATFORM
RUN echo "I'm building for $TARGETPLATFORM"
Give feedback
BUILDKIT_SYNTAX String Set frontend image
SOURCE_DATE_EPOCH Int Set the Unix timestamp for created image and layers.
More info from reproducible builds . Supported since
Docker�le 1.5, BuildKit 0.11
# syntax=docker/dockerfile:1
FROM alpine
WORKDIR /src
RUN --mount=target=. \
make REVISION=$(git rev-parse HEAD) build
57 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
variables do impact the build cache in similar ways. If a Docker�le de�nes an ARG variable
whose value is di�erent from a previous build, then a "cache miss" occurs upon its �rst
usage, not its de�nition. In particular, all RUN instructions following an ARG instruction use
the ARG variable implicitly (as an environment variable), thus can cause a cache miss. All
prede�ned ARG variables are exempt from caching unless there is a matching ARG
statement in the Docker�le.
FROM ubuntu
ARG CONT_IMG_VER
RUN echo $CONT_IMG_VER
Give feedback
FROM ubuntu
ARG CONT_IMG_VER
RUN echo hello
CONT_IMG_VER=<value> echo hello , so if the <value> changes, you get a cache miss.
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=$CONT_IMG_VER
RUN echo $CONT_IMG_VER
In this example, the cache miss occurs on line 3. The miss happens because the variable's
value in the ENV references the ARG variable and that variable is changed through the
command line. In this example, the ENV command causes the image to include the value.
58 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
If an ENV instruction overrides an ARG instruction of the same name, like this Docker�le:
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=hello
RUN echo $CONT_IMG_VER
Line 3 doesn't cause a cache miss because the value of CONT_IMG_VER is a constant (
hello ). As a result, the environment variables and values used on the RUN (line 4) doesn't
ONBUILD
ONBUILD INSTRUCTION
Give feedback
The ONBUILD instruction adds to the image a trigger instruction to be executed at a later
time, when the image is used as the base for another build. The trigger will be executed in
the context of the downstream build, as if it had been inserted immediately after the FROM
instruction in the downstream Docker�le.
This is useful if you are building an image which will be used as a base to build other
images, for example an application build environment or a daemon which may be
customized with user-speci�c con�guration.
For example, if your image is a reusable Python application builder, it will require application
source code to be added in a particular directory, and it might require a build script to be
called after that. You can't just call ADD and RUN now, because you don't yet have access
to the application source code, and it will be di�erent for each application build. You could
simply provide application developers with a boilerplate Docker�le to copy-paste into their
application, but that's ine�cient, error-prone and di�cult to update because it mixes with
application-speci�c code.
The solution is to use ONBUILD to register advance instructions to run later, during the next
59 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
build stage.
1. When it encounters an ONBUILD instruction, the builder adds a trigger to the metadata
of the image being built. The instruction doesn't otherwise a�ect the current build.
2. At the end of the build, a list of all triggers is stored in the image manifest, under the key
OnBuild . They can be inspected with the docker inspect command.
3. Later the image may be used as a base for a new build, using the FROM instruction. As
part of processing the FROM instruction, the downstream builder looks for ONBUILD
triggers, and executes them in the same order they were registered. If any of the
triggers fail, the FROM instruction is aborted which in turn causes the build to fail. If all
triggers succeed, the FROM instruction completes and the build continues as usual.
4. Triggers are cleared from the �nal image after being executed. In other words they
aren't inherited by "grand-children" builds.
Give feedback
For example you might add something like this:
STOPSIGNAL
60 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
STOPSIGNAL signal
The STOPSIGNAL instruction sets the system call signal that will be sent to the container to
exit. This signal can be a signal name in the format SIG<NAME> , for instance SIGKILL , or
an unsigned number that matches a position in the kernel's syscall table, for instance 9 .
The default is SIGTERM if not de�ned.
The image's default stopsignal can be overridden per container, using the --stop-signal
�ag on docker run and docker create .
HEALTHCHECK
The HEALTHCHECK instruction has two forms:
Give feedback
• HEALTHCHECK NONE (disable any healthcheck inherited from the base image)
The HEALTHCHECK instruction tells Docker how to test a container to check that it's still
working. This can detect cases such as a web server stuck in an in�nite loop and unable to
handle new connections, even though the server process is still running.
When a container has a healthcheck speci�ed, it has a health status in addition to its normal
status. This status is initially starting . Whenever a health check passes, it becomes
healthy (whatever state it was previously in). After a certain number of consecutive
• --start-period=DURATION (default: 0s )
• --start-interval=DURATION (default: 5s )
• --retries=N (default: 3 )
61 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The health check will �rst run seconds after the container is started, and then again
seconds after each previous check completes.
If a single run of the check takes longer than seconds then the check is considered
to have failed.
It takes consecutive failures of the health check for the container to be considered
unhealthy .
provides initialization time for containers that need time to bootstrap. Probe
failure during that period will not be counted towards the maximum number of retries.
However, if a health check succeeds during the start period, the container is considered
started and all consecutive failures will be counted towards the maximum number of retries.
is the time between health checks during the start period. This option requires
Docker Engine version 25.0 or later.
Give feedback
There can only be one HEALTHCHECK instruction in a Docker�le. If you list more than one
then only the last HEALTHCHECK will take e�ect.
The command after the CMD keyword can be either a shell command (e.g.
HEALTHCHECK CMD /bin/check-running ) or an exec array (as with other Docker�le
The command's exit status indicates the health status of the container. The possible values
are:
For example, to check every �ve minutes or so that a web-server is able to serve the site's
main page within three seconds:
62 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
To help debug failing probes, any output text (UTF-8 encoded) that the command writes on
stdout or stderr will be stored in the health status and can be queried with docker inspect
. Such output should be kept short (only the �rst 4096 bytes are stored currently).
When the health status of a container changes, a health_status event is generated with
the new status.
SHELL
SHELL ["executable", "parameters"]
The SHELL instruction allows the default shell used for the shell form of commands to be
overridden. The default shell on Linux is ["/bin/sh", "-c"] , and on Windows is
["cmd", "/S", "/C"] . The SHELL instruction must be written in JSON form in a
Docker�le.
Give feedback
The SHELL instruction is particularly useful on Windows where there are two commonly
used and quite di�erent native shells: cmd and powershell , as well as alternate shells
available including sh .
The SHELL instruction can appear multiple times. Each SHELL instruction overrides all
previous SHELL instructions, and a�ects all subsequent instructions. For example:
FROM microsoft/windowsservercore
63 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The following instructions can be a�ected by the SHELL instruction when the shell form of
them is used in a Docker�le: RUN , CMD and ENTRYPOINT .
The following example is a common pattern found on Windows which can be streamlined by
using the SHELL instruction:
Give feedback
This is ine�cient for two reasons. First, there is an unnecessary cmd.exe command
processor (aka shell) being invoked. Second, each RUN instruction in the shell form requires
an extra powershell -command pre�xing the command.
To make this more e�cient, one of two mechanisms can be employed. One is to use the
JSON form of the RUN command such as:
While the JSON form is unambiguous and does not use the unnecessary cmd.exe , it does
require more verbosity through double-quoting and escaping. The alternate mechanism is to
use the SHELL instruction and the shell form, making a more natural syntax for Windows
users, especially when combined with the escape parser directive:
# escape=`
FROM microsoft/nanoserver
SHELL ["powershell","-command"]
RUN New-Item -ItemType Directory C:\Example
ADD Execute-MyCmdlet.ps1 c:\example\
64 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Resulting in:
Give feedback
Directory: C:\
---> 3f2fbf1395d9
Removing intermediate container d0eef8386e97
Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\
---> a955b2621c31
Removing intermediate container b825593d39fc
Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world'
---> Running in be6d8e63fe75
hello world
---> 8e559e9bf424
Removing intermediate container be6d8e63fe75
Successfully built 8e559e9bf424
PS E:\myproject>
65 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
The SHELL instruction could also be used to modify the way in which a shell operates. For
example, using SHELL cmd /S /C /V:ON|OFF on Windows, delayed environment variable
expansion semantics could be modi�ed.
The SHELL instruction can also be used on Linux should an alternate shell be required such
as zsh , csh , tcsh and others.
Here-Documents
Added in docker/dockerfile:1.4
Give feedback
the next lines until the line only containing a here-doc delimiter as part of the same
command.
# syntax=docker/dockerfile:1
FROM debian
RUN <<EOT bash
set -ex
apt-get update
apt-get install -y vim
EOT
If the command only contains a here-document, its contents is evaluated with the default
shell.
# syntax=docker/dockerfile:1
FROM debian
RUN <<EOT
66 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
mkdir -p foo/bar
EOT
# syntax=docker/dockerfile:1
FROM python:3.6
RUN <<EOT
#!/usr/bin/env python
print("hello world")
EOT
# syntax=docker/dockerfile:1
FROM alpine
Give feedback
RUN <<FILE1 cat > file1 && <<FILE2 cat > file2
I am
first
FILE1
I am
second
FILE2
# syntax=docker/dockerfile:1
FROM alpine
COPY <<EOF greeting.txt
hello world
EOF
67 of 68 2/26/24, 12:50
Dockerfile reference | Docker Docs https://docs.docker.com/reference/dockerfile/#from
Regular here-doc variable expansion and tab stripping rules apply. The following example
shows a small Docker�le that creates a hello.sh script �le using a COPY instruction with
a here-document.
# syntax=docker/dockerfile:1
FROM alpine
ARG FOO=bar
COPY <<-EOT /script.sh
echo "hello ${FOO}"
EOT
ENTRYPOINT ash /script.sh
In this case, �le script prints "hello bar", because the variable is expanded when the COPY
instruction gets executed.
Give feedback
$ docker run heredoc
hello bar
68 of 68 2/26/24, 12:50