7
头图

Docker can automatically build an image by reading the instructions in the Dockerfile. Dockerfile is a text document that contains all the commands and instructions for users to create images.

1. Variables

Variables are represented by $variable_name or ${variable_name} .

  • ${variable:-word} means that if variable is set, the result will be that value. If variable is not set, word will be the result.
  • ${variable:+word} means that if variable is set, it will be a word result, otherwise it will be an empty string.

\ before the variable can be escaped into an ordinary string: \$foo or \${foo} , which means that it is converted into $foo and ${foo} text.

Two, FROM

Initiate a new build phase and set the base image:

FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]

A single Dockfile can appear FROM multiple times to use the previous build stage as a dependency of another build stage

AS name represents the name of the build stage, COPY --from=<name> descriptions to refer to the image built at this stage

Digest is actually an ID generated according to the content of the image, as long as the content of the image does not change, the digest will not change.

The tag or digest value is optional. If you omit any of them, the builder uses a latest tag by default. If the tag value is not found, the builder will return an error.

The --platform flag can be used to specify the platform when FROM refers to a multi-platform image. For example, linux/amd64, linux/arm64, or windows/amd64.

Three, RUN

The command will be executed in a new layer above the current image and run during docker build.

RUN /bin/bash -c 'source $HOME/.bashrc; \
echo $HOME'

RUN has two forms:

RUN<command>(shell 形式,命令在 shell 中运行,默认 /bin/sh -c 在 Linux 或 cmd /S /CWindows 上)
RUN ["executable", "param1", "param2"](执行形式)

illustrate:

可以使用 \(反斜杠)将单个 RUN 指令延续到下一行
RUN 在下一次构建期间,指令缓存不会自动失效。可以使用 --no-cache 标志使指令缓存无效
Dockerfile 的指令每执行一次都会在 Docker 上新建一层。所以过多无意义的层,会造成镜像膨胀过大,可以使用 && 符号连接命令,这样执行后,只会创建 1 层镜像

Four, CMD

To run the program, it runs during docker run, but unlike the run command, RUN runs during docker build.

FROM ubuntu
CMD ["/usr/bin/wc","--help"]

Three formats are supported:

CMD ["executable","param1","param2"] 使用 exec 执行,推荐方式;
CMD command param1 param2 在 /bin/sh 中执行,提供给需要交互的应用;
CMD ["param1","param2"] 提供给 ENTRYPOINT 的默认参数。

Specify the command to be executed when the container is started. Each Dockerfile can only have one CMD command. If multiple commands are specified, only the last one will be executed.

If the user specifies a command to run when starting the container, the command specified by CMD will be overwritten.

Five, LABEL

Add metadata:

LABEL multi.label1="value1" \
      multi.label2="value2" \
      other="value3"

Six, EXPOSE

EXPOSE <port> [<port>/<protocol>...]

The Docker container listens on the specified network port at runtime. You can specify whether the port is listening on TCP or UDP. If the protocol is not specified, the default is TCP.

The EXPOSE command does not actually publish the port. To actually publish the port when running the container, docker run -P to publish and map one or more ports.

By default, EXPOSE assumes TCP. You can also specify UDP:

EXPOSE 80/udp

Seven, ENV

Set environment variables:

ENV <key>=<value> ...

The environment variables set will continue to exist, and you can use docker inspect to view them. Use docker run --env <key>=<value> to change the value of environment variables.

If the environment variable is only needed during the build, consider setting a value for a single command:

RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y ...

Or use ARG, it will not remain in the final image:

ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y ...

Eight, ADD

Copy new files, directories or remote files URL <src> and add them to <dest> .

<src> can specify multiple resources, but if they are files or directories, their paths are interpreted as relative to the source of the build context, which is WORKDIR.

Each <src> may contain wildcards, and the matching will use Go's filepath.Match rules. E.g:

Add all files starting with "hom":

ADD hom* /mydir/

In the example below,? Is replaced with any single character, such as "home.txt".

ADD hom?.txt /mydir/

<dest> is an absolute path, or a relative path relative to WORKDIR.

Nine, COPY

The syntax is the same as ADD, copy and copy files.

The only difference between the COPY instruction and the ADD instruction is whether it supports obtaining resources from a remote URL. The COPY instruction can only read resources from the host where the docker build is executed and copy them to the image. The ADD instruction also supports reading resources from a remote server via URL and copying them to the mirror.

For the same requirements, it is recommended to use the COPY command. The ADD instruction is better at reading local tar files and decompressing them.

Ten, ENTRYPOINT

ENTRYPOINT, like CMD, specifies the container startup program and parameters, but it will not be overwritten by the instructions specified by the command line parameters of docker run. If you want to overwrite it, you need to specify it through docker run --entrypoint.

It has 2 formats:

ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT command param1 param2

After the ENTRYPOINT is specified, the content of CMD is passed to the ENTRYPOINT instruction as a parameter. When it is actually executed, it will become:

<ENTRYPOINT> <CMD>

11. VOLUME

Create a mounted data volume with the specified name.

VOLUME ["/var/log/"]
VOLUME /var/log

Its main role is to :

  • Avoid important data lost due to container restart
  • Avoid containers that keep getting bigger

12. ARG

Defining variables has the same effect as ENV, but ARG variables will not be persisted to the built image like ENV variables.

ARG <name>[=<default value>]

Docker has a set of predefined ARG variables that you can use without corresponding instructions 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 .

13. ONBUILD

Add a trigger instruction to the image to be executed later when the image is used as the basis for another build. That is, it is executed when another dockerfile FROM this image.

ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src

14. STOPSIGNAL

Set the system call signal that will be sent to the container to exit. The signal can be a valid unsigned number that matches the position in the kernel system call table, such as 9, or the signal name in the format of SIGNAME, such as SIGKILL.
STOPSIGNAL signal

The default stop-signal is SIGTERM. When docker stop, this signal will be sent to the process with PID 1 in the container. Through --stop-signal, you can set the signal you need. The main purpose is to make the application in the container in After receiving the signal, you can process some things first to realize the smooth exit of the container. If you do not do any processing, the container will be forced to exit after a period of time, which will cause the forced interruption of the business. The default time is 10s.

15. HEALTHCHECK

Used to specify a program or instruction to monitor the running status of the Docker container service. The HEALTHCHECK instruction has two forms:

HEALTHCHECK [OPTIONS] CMD command(通过在容器内运行命令来检查容器健康状况)
或者
HEALTHCHECK NONE(禁用从基础镜像继承的任何健康检查)

16. SHELL

Override the default shell in the form of shell used for commands. The default shell on Linux is ["/bin/sh", "-c"] and on Windows is ["cmd", "/S", "/C"] .

SHELL ["executable", "parameters"]

The SHELL command is particularly useful on Windows, because Windows has two commonly used and very different native SHELLs: cmd and powershell, as well as alternate shells available, including sh. The SHELL instruction can appear multiple times. Each SHELL instruction will overwrite all previous SHELL instructions and affect all subsequent instructions.

17. WORKDIR

The working directory. If WORKDIR does not exist, it will be created even if it is not used in subsequent Dockerfile instructions.

In the process of docker build building the image, each RUN command will create a new layer. Only the directory created by WORKDIR will always exist.

Multiple WORKDIRs can be set. If a relative path is provided, it will be relative to the path of the previous WORKDIR instruction. E.g:

WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd

The final output of the pwd command is /a/b/c.

The WORKDIR instruction can resolve the previous use of ENV, for example:

ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd

The final output of the pwd command is /path/$DIRNAME.

18. USER

Set the user name (or UID) and optional user group (or GID).

USER <user>[:<group>]
USER <UID>[:<GID>]

Link: https://zhuanlan.zhihu.com/p/387855002


民工哥
26.4k 声望56.7k 粉丝

10多年IT职场老司机的经验分享,坚持自学一路从技术小白成长为互联网企业信息技术部门的负责人。2019/2020/2021年度 思否Top Writer