Docker从入门到精通——Dockerfile reference
Dockerfile 参考
预计阅读时间:87 分钟,此页面是 Docker 官方概述,https://docs.docker.com/engine/reference/builder/
Docker 可以通过读取来自 Dockerfile
. Dockerfile
是一个文本文档,其中包含用户可以在命令行上调用以组装 image 的所有命令。使用 docker build
用户可以创建一个连续执行多个命令行指令的自动构建。
本页描述了您可以在 Dockerfile
. 阅读完本页后,请参阅 Dockerfile
最佳实践 以获取面向提示的指南。
一、用法
docker build 命令从 Dockerfile
和 context 构建 image。构建的上下文是指定位置的文件集 PATH
或 URL
。这 PATH
是本地文件系统上的目录。这 URL
是一个 Git 存储库位置。
构建上下文是递归处理的。因此,PATH
包括任何子目录,并且 URL
包括存储库及其子模块。此示例显示了一个使用当前目录 (.
) 作为构建上下文的构建命令:
$ docker build .
Sending build context to Docker daemon 6.51 MB
构建由 Docker 守护程序运行,而不是由 CLI 运行。构建过程所做的第一件事是将整个上下文(递归)发送到守护进程。在大多数情况下,最好从一个空目录作为上下文开始,并将 Dockerfile 保存在该目录中。仅添加构建 Dockerfile 所需的文件。
警告
不要将根目录
/
用作PATH
构建上下文,因为它会导致构建将硬盘驱动器的全部内容传输到 Docker 守护程序。
要在构建上下文中使用文件,Dockerfile
指的是在指令中指定的文件,例如 COPY
指令。
要提高构建的性能,请通过将.dockerignore
文件添加到上下文目录来排除文件和目录。有关如何 创建.dockerignore
文件 的信息,请参阅此页面上的文档。
传统上,Dockerfile
被调用 Dockerfile
并位于上下文的根中。您可以使用 -f
标志 with docker build
来指向文件系统中任何位置的 Dockerfile。
docker build -f /path/to/a/Dockerfile .
如果构建成功,您可以指定保存新图像的存储库和标记:
docker build -t shykes /myapp .
要在构建后将映像标记到多个存储库中,请在运行命令 -t
时添加多个参数:build
docker build -t shykes/myapp:1.0.2 -t shykes/myapp:latest .
在 Docker 守护进程运行 中的指令之前Dockerfile
,它会对 进行初步验证,Dockerfile
如果语法不正确则返回错误:
docker build -t test/myapp .
[+] Building 0.3s (2/2) FINISHED
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 60B 0.0s
=> [internal] load .dockerignore 0.1s
=> => transferring context: 2B 0.0s
error: failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to create LLB definition:
dockerfile parse error line 2: unknown instruction: RUNCMD
Docker 守护进程 Dockerfile
一个接一个地运行指令,必要时将每条指令的结果提交到新镜像,最后输出新镜像的 ID。Docker 守护进程将自动清理您发送的上下文。
请注意,每条指令都是独立运行的,并会创建一个新图像 - 因此 RUN cd /tmp
不会对下一条指令产生任何影响。
只要有可能,Docker 就会使用构建缓存来docker build
显着加速该过程。这由CACHED
控制台输出中的消息指示。(有关更多信息,请参阅Dockerfile
最佳实践指南):
docker build -t svendowideit/ambassador .
[+] Building 0.7s (6/6) FINISHED
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 286B 0.0s
=> [internal] load .dockerignore 0.1s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/alpine:3.2 0.4s
=> CACHED [1/2] FROM docker.io/library/alpine:3.2@sha256:e9a2035f9d0d7ce 0.0s
=> CACHED [2/2] RUN apk add --no-cache socat 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:1affb80ca37018ac12067fa2af38cc5bcc2a8f09963de 0.0s
=> => naming to docker.io/svendowideit/ambassador 0.0s
默认情况下,构建缓存基于您正在构建的机器上先前构建的结果。该--cache-from
选项还允许您使用通过映像注册表分发的构建缓存,请参阅命令参考中的 指定外部缓存源 部分docker build
。
完成构建后,您就可以开始使用扫描您的镜像docker scan
,并将您的镜像推送到 Docker Hub。
二、BuildKit
从版本 18.09 开始,Docker 支持一个新的后端来执行由 moby/buildkit 项目提供的构建。与旧实现相比,BuildKit 后端提供了许多好处。例如,BuildKit 可以:
-
- 检测并跳过执行未使用的构建阶段
- 并行构建独立的构建阶段
- 在构建之间仅增量传输构建上下文中更改的文件
- 在构建上下文中检测并跳过传输未使用的文件
- 使用具有许多新功能的外部 Dockerfile 实现
- 避免 API 的其余部分(中间图像和容器)产生副作用
- 优先考虑构建缓存以进行自动修剪
要使用 BuildKit 后端,您需要 DOCKER_BUILDKIT=1
在调用之前在 CLI 上设置环境变量docker build
。
要了解可用于基于 BuildKit 的构建的 Dockerfile 语法,请参阅 BuildKit 存储库中的文档。
三、格式
这是 的格式 Dockerfile
:
# Comment
INSTRUCTION arguments
该指令不区分大小写。但是,约定是大写的,以便更容易地将它们与参数区分开来。
Docker 按顺序运行指令 Dockerfile
。必须以指令 Dockerfile
开头 FROM
。这可能在解析器指令、注释和全局范围 的ARG之后。该FROM
指令指定您正在构建的父图像。FROM
前面只能有一个或多个ARG
指令,这些指令声明FROM
在Dockerfile
.
Docker 将开头的行#
视为注释,除非该行是有效的解析器指令。行中任何其他位置的#
标记都被视为参数。这允许以下语句:
# Comment RUN echo 'we are running some # of cool things'
注释行在执行 Dockerfile 指令之前被删除,这意味着下面示例中的注释不是由执行echo
命令的 shell 处理的,下面两个示例是等价的:
RUN echo hello \
# comment
world
RUN echo hello \
world
注释中不支持换行符。
空格注意事项
为了向后兼容,注释 ( #
) 和指令(例如RUN
) 之前的前导空格会被忽略,但不鼓励。在这些情况下不保留前导空格,因此以下示例是等效的:
# this is a comment-line
RUN echo hello
RUN echo world
# this is a comment-line
RUN echo hello
RUN echo world
但是请注意,指令参数中的空格(例如后面的命令RUN
)会被保留,因此以下示例会打印带有指定前导空格的 `hello world`:
RUN echo "\
hello\
world"
解析器指令
解析器指令是可选的,并且会影响处理 a 中后续行的Dockerfile
方式。解析器指令不会将层添加到构建中,并且不会显示为构建步骤。解析器指令以# directive=value
. 一个指令只能使用一次。
一旦处理了注释、空行或构建器指令,Docker 就不再寻找解析器指令。相反,它将任何格式化为解析器指令的内容视为注释,并且不会尝试验证它是否可能是解析器指令。因此,所有解析器指令都必须位于Dockerfile
.
解析器指令不区分大小写。但是,约定是小写的。约定也是在任何解析器指令之后包含一个空行。解析器指令不支持换行符。
由于这些规则,以下示例均无效:
由于行继续而无效:
# direc \
tive=value
由于出现两次而无效:
# directive=value1
# directive=value2
FROM ImageName
由于出现在构建器指令之后,因此被视为注释:
FROM ImageName
# directive=value
由于出现在不是解析器指令的注释之后,因此被视为注释:
# About my dockerfile
# directive=value
FROM ImageName
由于未被识别,未知指令被视为注释。此外,由于出现在不是解析器指令的注释之后,已知指令被视为注释。
# unknowndirective=value
# knowndirective=value
解析器指令中允许使用非换行空格。因此,以下行都被同等对待:
#directive=value
# directive =value
# directive= value
# directive = value
# dIrEcTiVe=value
The following parser directives are supported:
syntax
escape
syntax
# syntax=[remote image reference]
For example:
# syntax=docker/dockerfile:1
# syntax=docker.io/docker/dockerfile:1
# syntax=example.com/user/repo:tag@sha256:abcdef...
This feature is only available when using the BuildKit backend, and is ignored when using the classic builder backend.
The syntax directive defines the location of the Dockerfile syntax that is used to build the Dockerfile. The BuildKit backend allows to seamlessly use external implementations that are distributed as Docker images and execute inside a container sandbox environment.
Custom Dockerfile implementations allows you to:
- Automatically get bugfixes without updating the Docker daemon
- Make sure all users are using the same implementation to build your Dockerfile
- Use the latest features without updating the Docker daemon
- Try out new features or third-party features before they are integrated in the Docker daemon
- Use alternative build definitions, or create your own
Official releases
Docker distributes official versions of the images that can be used for building Dockerfiles under docker/dockerfile
repository on Docker Hub. There are two channels where new images are released: stable
and labs
.
Stable channel follows semantic versioning. For example:
docker/dockerfile:1
- kept updated with the latest1.x.x
minor and patch releasedocker/dockerfile:1.2
- kept updated with the latest1.2.x
patch release, and stops receiving updates once version1.3.0
is released.docker/dockerfile:1.2.1
- immutable: never updated
We recommend using docker/dockerfile:1
, which always points to the latest stable release of the version 1 syntax, and receives both “minor” and “patch” updates for the version 1 release cycle. BuildKit automatically checks for updates of the syntax when performing a build, making sure you are using the most current version.
If a specific version is used, such as 1.2
or 1.2.1
, the Dockerfile needs to be updated manually to continue receiving bugfixes and new features. Old versions of the Dockerfile remain compatible with the new versions of the builder.
labs channel
The “labs” channel provides early access to Dockerfile features that are not yet available in the stable channel. Labs channel images are released in conjunction with the stable releases, and follow the same versioning with the -labs
suffix, for example:
docker/dockerfile:labs
- latest release on labs channeldocker/dockerfile:1-labs
- same asdockerfile:1
in the stable channel, with labs features enableddocker/dockerfile:1.2-labs
- same asdockerfile:1.2
in the stable channel, with labs features enableddocker/dockerfile:1.2.1-labs
- immutable: never updated. Same asdockerfile:1.2.1
in the stable channel, with labs features enabled
Choose a channel that best fits your needs; if you want to benefit from new features, use the labs channel. Images in the labs channel provide a superset of the features in the stable channel; note that stable
features in the labs channel images follow semantic versioning, but “labs” features do not, and newer releases may not be backwards compatible, so it is recommended to use an immutable full version variant.
For documentation on “labs” features, master builds, and nightly feature releases, refer to the description in the BuildKit source repository on GitHub. For a full list of available images, visit the image repository on Docker Hub, and the docker/dockerfile-upstream image repository for development builds.
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 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>
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
ONBUILD
(when combined with one of the supported instructions 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 [--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 – 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>
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.
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.
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'
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 (‘).
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
and COPY
instructions.
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.
If CMD
is used to provide default arguments for the ENTRYPOINT
instruction, both the CMD
and ENTRYPOINT
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 (‘).
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
Do not confuse RUN
with CMD
. 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 image inspect
command. You can use the --format
option to show just the labels;
$ docker image inspect --format='' myimage
{
"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 org.opencontainers.image.authors="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> ...
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:
ENV MY_NAME="John Doe"
ENV MY_DOG=Rex\ The\ Dog
ENV MY_CAT=fluffy
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 final image:
ENV MY_NAME="John Doe" MY_DOG=Rex\ The\ Dog \
MY_CAT=fluffy
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>
.
Environment variable persistence can cause unexpected side effects. For example, setting ENV DEBIAN_FRONTEND=noninteractive
changes the behavior of apt-get
, and may confuse users of your image.
If an environment variable is only needed during build, and not in the final image, consider setting a value for a single command instead:
RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y ...
Or using ARG
, which is not persisted in the final image:
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y ...
Alternative syntax
The ENV
instruction also allows an alternative syntax ENV <key> <value>
, omitting the =
. For example:
ENV MY_VAR my-value
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 environment variable (ONE
) with value "TWO= THREE=world"
:
ENV ONE TWO= THREE=world
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:
ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>",... "<dest>"]
The latter 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:
To add all files starting with “hom”:
ADD hom* /mydir/
In the example below, ?
is replaced with any single character, e.g., “home.txt”.
ADD hom?.txt /mydir/
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/
:
ADD test.txt relativeDir/
Whereas this example uses an absolute path, and adds “test.txt” to /absoluteDir/
ADD test.txt /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/
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 the Dockerfile
can only contain a URL based ADD
instruction. You can also pass a compressed archive through STDIN: (docker build - < archive.tar.gz
), the Dockerfile
at the root of the archive and the rest of the archive will be used as the context of the build.
If your URL files are protected using authentication, you need to use RUN wget
, RUN curl
or use another tool from within the container as the ADD
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 the Dockerfile
Best Practices guide – Leverage build cache 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.
COPY
COPY has two forms:
COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]
This latter 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 COPY
instruction copies new files or directories from <src>
and adds them to the filesystem of the container at the path <dest>
.
Multiple <src>
resources may be specified but the paths of files 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 filepath.Match rules. For example:
To add all files starting with “hom”:
COPY hom* /mydir/
In the example below, ?
is replaced with any single character, e.g., “home.txt”.
COPY hom?.txt /mydir/
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/
:
COPY test.txt relativeDir/
Whereas this example uses an absolute path, and adds “test.txt” to /absoluteDir/
COPY test.txt /absoluteDir/
When copying 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 copy a file named arr[0].txt
, use the following;
COPY arr[[]0].txt /mydir/
所有新文件和目录都使用 0 的 UID 和 GID 创建,除非可选--chown
标志指定给定的用户名、组名或 UID/GID 组合以请求复制内容的特定所有权。标志的格式--chown
允许用户名和组名字符串或直接整数 UID 和 GID 的任意组合。提供不带组名的用户名或不带 GID 的 UID 将使用与 GID 相同的数字 UID。如果提供了用户名或组名,则容器的根文件系统 /etc/passwd
和/etc/group
文件将分别用于执行从名称到整数 UID 或 GID 的转换。以下示例显示了--chown
标志的有效定义:
COPY --chown=55:mygroup files* /somedir/
COPY --chown=bin files* /somedir/
COPY --chown=1 files* /somedir/
COPY --chown=10:11 files* /somedir/
如果容器根文件系统不包含文件,并且标志中使用了用户名或组名/etc/passwd
, 则构建将在操作中失败。使用数字 ID 不需要查找并且不依赖于容器根文件系统内容。/etc/group
--chown
COPY
笔记
如果使用 STDIN ( docker build - < somefile
) 构建,则没有构建上下文,因此COPY
无法使用。
可选择COPY
接受一个标志,该标志--from=<name>
可用于将源位置设置为先前的构建阶段(使用创建FROM .. AS <name>
),而不是用户发送的构建上下文。如果找不到具有指定名称的构建阶段,则尝试使用具有相同名称的图像。
COPY
遵守以下规则:
-
<src>
路径必须在构建的上下文中;你不能COPY ../something /something
,因为 a 的第一步docker build
是将上下文目录(和子目录)发送到 docker 守护进程。 -
如果
<src>
是目录,则复制目录的全部内容,包括文件系统元数据。
笔记
目录本身没有被复制,只是它的内容。
-
如果
<src>
是任何其他类型的文件,则将其与其元数据一起单独复制。在这种情况下,如果<dest>
以斜杠结尾/
,它将被视为一个目录,其内容<src>
将写入<dest>/base(<src>)
. -
<src>
如果直接或由于使用通配符而指定了多个资源,则<dest>
必须是目录,并且必须以斜杠结尾/
。 -
如果
<dest>
不以斜杠结尾,则将其视为常规文件,其内容<src>
将写入<dest>
. -
如果
<dest>
不存在,它会连同其路径中所有缺失的目录一起创建。
笔记
如果 Dockerfile 的内容已更改,则第一个遇到的COPY
指令将使 Dockerfile 中的所有后续指令的缓存无效。<src>
这包括使RUN
指令缓存无效。有关详细信息,请参阅Dockerfile
最佳实践指南 - 利用构建缓存 。
ENTRYPOINT 有两种形式:
exec形式,这是首选形式:
ENTRYPOINT ["executable", "param1", "param2"]
外壳形式:
ENTRYPOINT command param1 param2
AnENTRYPOINT
允许您配置将作为可执行文件运行的容器。
例如,以下内容使用其默认内容启动 nginx,侦听端口 80:
$ docker run -i -t --rm -p 80:80 nginx
命令行参数 todocker run <image>
将附加在exec表单中的所有元素之后ENTRYPOINT
,并将覆盖使用 指定的所有元素CMD
。这允许将参数传递给入口点,docker run <image> -d
即将-d
参数传递给入口点。 您可以使用标志覆盖ENTRYPOINT
指令。docker run --entrypoint
shell形式阻止使用任何或CMD
命令run
行参数,但缺点是您ENTRYPOINT
将作为 的子命令启动/bin/sh -c
,它不会传递信号。这意味着可执行文件将不是容器的PID 1
- 并且不会接收 Unix 信号 - 因此您的可执行文件将不会收到 SIGTERM
from docker stop <container>
。
只有将ENTRYPOINT
中的最后一条指令Dockerfile
有效。
执行表单 ENTRYPOINT 示例
您可以使用exec形式ENTRYPOINT
设置相当稳定的默认命令和参数,然后使用任一形式CMD
设置更可能更改的其他默认值。
FROM ubuntu
ENTRYPOINT ["top", "-b"]
CMD ["-c"]
When you run the container, you can see that top
is the only process:
$ docker run -it --rm --name test top -H
top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05
Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.1 us, 0.1 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers
KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top
To examine the result further, you can use docker exec
:
$ docker exec -it test ps aux
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
And you can gracefully request top
to shut down using docker stop test
.
The following Dockerfile
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 final executable receives the Unix signals by using exec
and gosu
commands:
#!/usr/bin/env bash
set -e
if [ "$1" = 'postgres' ]; then
chown -R postgres "$PGDATA"
if [ -z "$(ls -A "$PGDATA")" ]; then
gosu postgres initdb
fi
exec gosu postgres "$@"
fi
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
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
start service in background here
/usr/sbin/apachectl start
echo "[hit enter key to exit] or run 'docker stop <container>'"
read
stop service and clean up here
echo "stopping apache"
/usr/sbin/apachectl stop
echo "exited $0"
如果您使用 运行此映像,则可以使用、 或docker run -it --rm -p 80:80 --name test apache
检查容器的进程,然后要求脚本停止 Apache:docker exec
docker top
$ docker exec -it test ps aux
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 cmd cmd2
root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start
www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start
www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start
root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux
$ docker top test
PID USER COMMAND
10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2
10054 root /usr/sbin/apache2 -k start
10055 33 /usr/sbin/apache2 -k start
10056 33 /usr/sbin/apache2 -k start
$ /usr/bin/time docker stop test
test
real 0m 0.27s
user 0m 0.03s
sys 0m 0.03s
笔记
您可以使用 覆盖ENTRYPOINT
设置--entrypoint
,但这只能将二进制文件设置为exec(不会sh -c
使用)。
笔记
exec形式被解析为 JSON 数组,这意味着您必须在单词周围使用双引号 (") 而不是单引号 (')。
与shell形式不同,exec形式不调用命令 shell。这意味着不会发生正常的外壳处理。例如, ENTRYPOINT [ "echo", "$HOME" ]
不会对$HOME
. 如果你想要 shell 处理,那么要么使用shell形式,要么直接执行 shell,例如:ENTRYPOINT [ "sh", "-c", "echo $HOME" ]
. 当使用 exec 形式并直接执行 shell 时,与 shell 形式一样,是 shell 进行环境变量扩展,而不是 docker。
Shell 形式 ENTRYPOINT 示例
您可以为 指定一个纯字符串,ENTRYPOINT
它将在 中执行/bin/sh -c
。此表单将使用 shell 处理来替换 shell 环境变量,并将忽略任何CMD
或docker run
命令行参数。为确保正确docker stop
发出任何长时间运行的ENTRYPOINT
可执行文件,您需要记住以以下方式启动它exec
:
FROM ubuntu
ENTRYPOINT exec top -b
运行此映像时,您将看到单个PID 1
进程:
$ docker run -it --rm --name test top
Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached
CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq
Load average: 0.08 0.03 0.05 2/98 6
PID PPID USER STAT VSZ %VSZ %CPU COMMAND
1 0 root R 3164 0% 0% top -b
哪个干净地退出docker stop
:
$ /usr/bin/time docker stop test
test
real 0m 0.20s
user 0m 0.02s
sys 0m 0.04s
如果您忘记添加exec
到您的开头ENTRYPOINT
:
FROM ubuntu
ENTRYPOINT top -b
CMD -- --ignored-param1
然后您可以运行它(为下一步命名):
$ docker run -it --name test top --ignored-param2
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
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 20 0 2612 604 536 S 0.0 0.0 0:00.02 sh
6 root 20 0 5956 3188 2768 R 0.0 0.2 0:00.00 top
您可以从输出中top
看到指定ENTRYPOINT
的 is not PID 1
。
如果你然后运行docker stop test
,容器将不会干净地退出 - 该 stop
命令将SIGKILL
在超时后强制发送:
$ docker exec -it test ps waux
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 --ignored-param2
root 6 0.0 0.1 5956 3188 pts/0 S+ 13:58 0:00 top -b
root 7 0.0 0.1 5884 2816 pts/1 Rs+ 13:58 0:00 ps waux
$ /usr/bin/time docker stop test
test
real 0m 10.19s
user 0m 0.04s
sys 0m 0.03s
了解 CMD 和 ENTRYPOINT 如何交互
CMD
和ENTRYPOINT
指令都定义了运行容器时执行的命令。很少有规则描述他们的合作。
-
Dockerfile 应该至少指定一个
CMD
或ENTRYPOINT
命令。 -
ENTRYPOINT
应在将容器用作可执行文件时定义。 -
CMD
应该用作为ENTRYPOINT
命令定义默认参数或在容器中执行临时命令的一种方式。 -
CMD
使用替代参数运行容器时将被覆盖。
The table below shows what command is executed for different ENTRYPOINT
/ CMD
combinations:
No ENTRYPOINT | ENTRYPOINT exec_entry p1_entry | ENTRYPOINT [“exec_entry”, “p1_entry”] | |
---|---|---|---|
No CMD | error, not allowed | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry |
CMD [“exec_cmd”, “p1_cmd”] | exec_cmd p1_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry exec_cmd p1_cmd |
CMD [“p1_cmd”, “p2_cmd”] | p1_cmd p2_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry p1_cmd p2_cmd |
CMD exec_cmd p1_cmd | /bin/sh -c exec_cmd p1_cmd | /bin/sh -c exec_entry p1_entry | exec_entry p1_entry /bin/sh -c exec_cmd p1_cmd |
Note
If CMD
is defined from the base image, setting ENTRYPOINT
will reset CMD
to an empty value. In this scenario, CMD
must be defined in the current image to have a value.
VOLUME
VOLUME ["/data"]
The VOLUME
instruction creates a mount point with the specified 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 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 specified location within the base image. For example, consider the following Dockerfile snippet:
FROM ubuntu
RUN mkdir /myvol
RUN echo "hello world" > /myvol/greeting
VOLUME /myvol
This Dockerfile results in an image that causes docker run
to create a new mount point at /myvol
and copy the greeting
file into the newly created volume.
Notes about specifying volumes
Keep the following things in mind about volumes in the Dockerfile
.
-
Volumes on Windows-based containers: When using Windows-based containers, the destination of a volume inside the container must be one of:
- a non-existing or empty directory
- a drive other than
C:
-
Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded.
-
JSON formatting: The list is parsed as a JSON array. You must enclose words with double quotes (
"
) rather than single quotes ('
). -
The host directory is declared at container run-time: The host directory (the mountpoint) is, by its nature, host-dependent. This is to preserve image portability, since a given host directory can’t be guaranteed to be available on all hosts. For this reason, you can’t mount a host directory from within the Dockerfile. The
VOLUME
instruction does not support specifying ahost-dir
parameter. You must specify the mountpoint when you create or run the container.
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 when running the image and for any RUN
, CMD
and ENTRYPOINT
instructions that follow it in the Dockerfile
.
Note that when specifying a group for the user, the user will have only the specified group membership. Any other configured group memberships will be ignored.
Warning
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 first if it’s not a built-in account. This can be done with the net user
command called as part of a Dockerfile.
FROM microsoft/windowsservercore
# Create Windows user in the container
RUN net user /add patrick
# Set it for subsequent commands
USER patrick
WORKDIR
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 Dockerfile
. If the WORKDIR
doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile
instruction.
The WORKDIR
instruction can be used multiple times in a Dockerfile
. 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 final pwd
command in this Dockerfile
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 Dockerfile
. For example:
ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd
The output of the final pwd
command in this Dockerfile
would be /path/$DIRNAME
If not specified, the default working directory is /
. In practice, if you aren’t building a Dockerfile 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 is best practice to set your WORKDIR
explicitly.
ARG
ARG <name>[=<default value>]
The ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build
command using the --build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning.
[Warning] One or more build-args [foo] were not consumed.
A Dockerfile may include one or more ARG
instructions. For example, the following is a valid Dockerfile:
FROM busybox
ARG user1
ARG buildno
# ...
Warning:
It is not recommended to use build-time variables for passing secrets like github keys, user credentials etc. Build-time variable values are visible to any user of the image with the docker history
command.
Refer to the “build images with BuildKit” section to learn about secure ways to use secrets when building images.
Default values
An ARG
instruction can optionally include a default value:
FROM busybox
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 definition comes into effect from the line on which it is defined in the Dockerfile
not from the argument’s use on the command-line or elsewhere. For example, consider this Dockerfile:
FROM busybox
USER ${user:-some_user}
ARG user
USER $user
# ...
A user builds this file by calling:
$ docker build --build-arg user=what_user .
The USER
at line 2 evaluates to some_user
as the user
variable is defined on the subsequent line 3. The USER
at line 4 evaluates to what_user
as user
is defined and the what_user
value was passed on the command line. Prior to its definition 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 defined. To use an arg in multiple stages, each stage must include the ARG
instruction.
FROM busybox
ARG SETTINGS
RUN ./run/setup $SETTINGS
FROM busybox
ARG SETTINGS
RUN ./run/other $SETTINGS
Using ARG variables
You can use an ARG
or an ENV
instruction to specify variables that are available to the RUN
instruction. Environment variables defined using the ENV
instruction always override an ARG
instruction of the same name. Consider this Dockerfile with an ENV
and ARG
instruction.
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=v1.0.0
RUN echo $CONT_IMG_VER
Then, assume this image is built with this command:
$ docker build --build-arg CONT_IMG_VER=v2.0.1 .
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 definition.
Using the example above but a different ENV
specification 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 docker build without the --build-arg
flag:
$ docker build .
Using this Dockerfile 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 final image by leveraging the ENV
instruction. Variable expansion is only supported for a limited set of Dockerfile instructions.
Predefined ARGs
Docker has a set of predefined ARG
variables that you can use without a corresponding ARG
instruction in the Dockerfile.
HTTP_PROXY
http_proxy
HTTPS_PROXY
https_proxy
FTP_PROXY
ftp_proxy
NO_PROXY
no_proxy
To use these, pass them on the command line using the --build-arg
flag, for example:
$ docker build --build-arg HTTPS_PROXY=https://my-proxy.example.com .
By default, these pre-defined 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.
For example, consider building the following Dockerfile using --build-arg HTTP_PROXY=http://user:pass@proxy.lon.example.com
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:pass@proxy.sfo.example.com
, 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 Dockerfile as follows:
FROM ubuntu
ARG HTTP_PROXY
RUN echo "Hello World"
When building this Dockerfile, the HTTP_PROXY
is preserved in the docker history
, and changing its value invalidates the build cache.
Automatic platform ARGs in the global scope
This feature is only available when using the BuildKit backend.
Docker predefines a 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 specified with the --platform
flag on docker build
.
The following ARG
variables are set automatically:
TARGETPLATFORM
- platform of the build result. Eglinux/amd64
,linux/arm/v7
,windows/amd64
.TARGETOS
- OS component of TARGETPLATFORMTARGETARCH
- architecture component of TARGETPLATFORMTARGETVARIANT
- variant component of TARGETPLATFORMBUILDPLATFORM
- platform of the node performing the build.BUILDOS
- OS component of BUILDPLATFORMBUILDARCH
- architecture component of BUILDPLATFORMBUILDVARIANT
- variant component of BUILDPLATFORM
These arguments are defined 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 redefine it without value.
For example:
FROM alpine
ARG TARGETPLATFORM
RUN echo "I'm building for $TARGETPLATFORM"
Impact on build caching
ARG
variables are not persisted into the built image as ENV
variables are. However, ARG
variables do impact the build cache in similar ways. If a Dockerfile defines an ARG
variable whose value is different from a previous build, then a “cache miss” occurs upon its first usage, not its definition. 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 predefined ARG
variables are exempt from caching unless there is a matching ARG
statement in the Dockerfile
.
For example, consider these two Dockerfile:
FROM ubuntu
ARG CONT_IMG_VER
RUN echo $CONT_IMG_VER
FROM ubuntu
ARG CONT_IMG_VER
RUN echo hello
If you specify --build-arg CONT_IMG_VER=<value>
on the command line, in both cases, the specification on line 2 does not cause a cache miss; line 3 does cause a cache miss.ARG CONT_IMG_VER
causes the RUN line to be identified as the same as running CONT_IMG_VER=<value> echo hello
, so if the <value>
changes, we get a cache miss.
Consider another example under the same command line:
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.
If an ENV
instruction overrides an ARG
instruction of the same name, like this Dockerfile:
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=hello
RUN echo $CONT_IMG_VER
第 3 行不会导致缓存未命中,因为 的值CONT_IMG_VER
是一个常量 ( hello
)。因此,在RUN
(第 4 行)中使用的环境变量和值在构建之间不会发生变化。
🔗
ONBUILD <INSTRUCTION>
该ONBUILD
指令向图像添加了一条触发指令,该指令将在以后执行,当该图像用作另一个构建的基础时。触发器将在下游构建的上下文中执行,就好像它是 FROM
在下游指令之后立即插入的一样Dockerfile
。
任何构建指令都可以注册为触发器。
如果您正在构建将用作构建其他镜像的基础的镜像,例如应用程序构建环境或可以使用用户特定配置自定义的守护程序,这将非常有用。
例如,如果您的图像是一个可重用的 Python 应用程序构建器,则需要将应用程序源代码添加到特定目录中,然后可能需要调用构建脚本 。您不能只调用ADD
and RUN
now,因为您还没有访问应用程序源代码的权限,而且每个应用程序构建都会有所不同。您可以简单地为应用程序开发人员提供一个样板Dockerfile
文件以将其复制粘贴到他们的应用程序中,但这效率低下、容易出错并且难以更新,因为它与特定于应用程序的代码混合在一起。
解决方案是用于ONBUILD
注册高级指令,以便在下一个构建阶段稍后运行。
以下是它的工作原理:
- 当遇到
ONBUILD
指令时,构建器将触发器添加到正在构建的图像的元数据中。该指令不会影响当前的构建。 - 在构建结束时,所有触发器的列表都存储在镜像清单中,位于 key 下
OnBuild
。可以使用docker inspect
命令检查它们。 FROM
稍后,可以使用该指令将映像用作新构建的基础 。作为处理FROM
指令的一部分,下游构建器查找ONBUILD
触发器,并按照它们注册的顺序执行它们。如果任何触发器失败,则该FROM
指令被中止,进而导致构建失败。如果所有触发器都成功,则FROM
指令完成并且构建照常继续。- 触发器在执行后会从最终图像中清除。换句话说,它们不会被“孙子”构建继承。
例如,您可以添加如下内容:
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src
警告
不允许使用链接ONBUILD
指令。ONBUILD ONBUILD
警告
该ONBUILD
指令可能不会触发FROM
或MAINTAINER
指令。
STOPSIGNAL signal
该STOPSIGNAL
指令设置将发送到容器以退出的系统调用信号。该信号可以是格式中的信号名称SIG<NAME>
,例如SIGKILL
,也可以是匹配内核系统调用表中某个位置的无符号数,例如9
。SIGTERM
如果未定义,则默认为。
可以使用 --stop-signal
标志 ondocker run
和覆盖每个容器的图像的默认停止信号docker create
。
🔗
HEALTHCHECK
指令有两种形式:
HEALTHCHECK [OPTIONS] CMD command
(通过在容器内运行命令检查容器运行状况)HEALTHCHECK NONE
(禁用从基础映像继承的任何运行状况检查)
该HEALTHCHECK
指令告诉 Docker 如何测试容器以检查它是否仍在工作。这可以检测诸如 Web 服务器陷入无限循环并且无法处理新连接的情况,即使服务器进程仍在运行。
当容器指定了健康检查时,除了正常状态外,它还具有健康状态。此状态最初为starting
. 每当健康检查通过时,它就会变成healthy
(无论它以前处于什么状态)。在连续失败一定次数后,就变成了unhealthy
。
之前可以出现的选项CMD
有:
--interval=DURATION
(默认30s
:)--timeout=DURATION
(默认30s
:)--start-period=DURATION
(默认0s
:)--retries=N
(默认3
:)
健康检查将首先在容器启动后运行间隔秒,然后在每次之前的检查完成后再次运行间隔秒。
如果单次运行检查花费的时间超过timeout秒,则认为检查失败。
它需要重试健康检查的连续失败才能考虑容器unhealthy
。
start period为需要时间引导的容器提供初始化时间。在此期间探测失败将不计入最大重试次数。但是,如果在启动期间健康检查成功,则认为容器已启动,所有连续失败将计入最大重试次数。
Dockerfile中只能有一条HEALTHCHECK
指令。如果您列出多个,则只有最后一个HEALTHCHECK
才会生效。
关键字后面的命令CMD
可以是 shell 命令(例如HEALTHCHECK CMD /bin/check-running
),也可以是exec数组(与其他 Dockerfile 命令一样;ENTRYPOINT
有关详细信息,请参见 eg)。
该命令的退出状态指示容器的健康状态。可能的值是:
- 0:成功 - 容器健康且可以使用
- 1:不健康 - 容器工作不正常
- 2:保留 - 不要使用此退出代码
例如,每隔五分钟左右检查一次网络服务器是否能够在三秒内为网站的主页提供服务:
HEALTHCHECK --interval=5m --timeout=3s \
CMD curl -f http://localhost/ || exit 1
为了帮助调试失败的探测,该命令在 stdout 或 stderr 上写入的任何输出文本(UTF-8 编码)都将存储在健康状态中,并且可以使用 docker inspect
. 此类输出应保持简短(当前仅存储前 4096 个字节)。
当容器的健康状态发生变化时,health_status
会生成一个带有新状态的事件。
壳牌
SHELL ["executable", "parameters"]
该指令允许覆盖用于命令的shell形式SHELL
的默认 shell 。Linux 上的默认 shell 是,而 Windows 上是. 该指令必须以 JSON 格式写入 Dockerfile。["/bin/sh", "-c"]
["cmd", "/S", "/C"]
SHELL
该SHELL
指令在 Windows 上特别有用,其中有两个常用且完全不同的原生 shell:cmd
和powershell
,以及可用的备用 shell,包括sh
.
该SHELL
指令可以出现多次。每条SHELL
指令都会覆盖所有先前的SHELL
指令,并影响所有后续指令。例如:
FROM microsoft/windowsservercore
Executed as cmd /S /C echo default
RUN echo default
Executed as cmd /S /C powershell -command Write-Host default
RUN powershell -command Write-Host default
Executed as powershell -command Write-Host hello
SHELL ["powershell", "-command"]
RUN Write-Host hello
Executed as cmd /S /C echo hello
SHELL ["cmd", "/S", "/C"]
RUN echo hello
在 Dockerfile 中使用它们的shellSHELL
形式时, 以下指令可能会受到指令的影响:和.RUN
CMD
ENTRYPOINT
以下示例是在 Windows 上发现的常见模式,可以使用SHELL
指令进行简化:
RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt"
docker调用的命令将是:
cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt"
由于两个原因,这是低效的。首先,调用了一个不必要的 cmd.exe 命令处理器(又名 shell)。其次,shellRUN
形式的每条指令都 需要一个额外的命令前缀。powershell -command
为了提高效率,可以采用两种机制之一。一种是使用 JSON 形式的 RUN 命令,例如:
RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""]
虽然 JSON 格式是明确的并且不使用不必要的 cmd.exe,但它确实需要通过双引号和转义来增加详细信息。另一种机制是使用SHELL
指令和shell形式,为 Windows 用户提供更自然的语法,尤其是与escape
parser 指令结合使用时:
# escape=`
FROM microsoft/nanoserver
SHELL ["powershell","-command"]
RUN New-Item -ItemType Directory C:\Example
ADD Execute-MyCmdlet.ps1 c:\example
RUN c:\example\Execute-MyCmdlet -sample 'hello world'
导致:
PS E:\myproject> docker build -t shell .
Sending build context to Docker daemon 4.096 kB
Step 1/5 : FROM microsoft/nanoserver
---> 22738ff49c6d
Step 2/5 : SHELL powershell -command
---> Running in 6fcdb6855ae2
---> 6331462d4300
Removing intermediate container 6fcdb6855ae2
Step 3/5 : RUN New-Item -ItemType Directory C:\Example
---> Running in d0eef8386e97
Directory: C:\
Mode LastWriteTime Length Name
d----- 10/28/2016 11:26 AM Example
---> 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>
该SHELL
指令还可以用于修改 shell 的操作方式。例如,SHELL cmd /S /C /V:ON|OFF
在 Windows 上使用,可以修改延迟的环境变量扩展语义。
SHELL
如果需要备用 shell,例如zsh
、等csh
,该指令也可以在 Linux 上使用tcsh
。
Dockerfile 示例
有关 Dockerfile 的示例,请参阅: