Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Docker Dockerfile

Docker Dockerfile

What is a Dockerfile?

A Dockerfile is a text file that contains all the instructions for building a Docker image.

A Dockerfile is a text file used to build an image; its contents include the instructions and descriptions needed to build the image, one by one.

By defining a series of commands and parameters, a Dockerfile guides Docker in building a custom image.

Customize an image using a Dockerfile

Here we only explain how to run a Dockerfile to customize an image; detailed explanations of the instructions inside a Dockerfile will be introduced in the next section. For now, you only need to understand the build process.

1. Let's customize an nginx image as an example (the built image will contain a /usr/share/nginx/html/index.html file)

In an empty directory, create a new file named Dockerfile and add the following content to it:

FROM nginx

RUN echo '这是一个本地构建的nginx镜像' > /usr/share/nginx/html/index.html

2. The roles of the FROM and RUN instructions

FROM: Custom images are all based on a FROM image; here nginx is the base image needed for customization. All subsequent operations are based on nginx.

RUN: Used to execute the command line that follows. There are two formats:

shell format:

RUN <命令行命令>

# <命令行命令> 等同于,在终端操作的 shell 命令。

exec format:

RUN ["可执行文件", "参数1", "参数2"]

# 例如:

# RUN ["./test.php", "dev", "offline"] is equivalent to RUN ./test.php dev offline

Note: Each time a Dockerfile instruction is executed, a new layer is created in docker. Therefore, too many meaningless layers will cause the image to become bloated. For example:

FROM centos

RUN

yum

-y

install

wget

RUN

wget

-O

redis.tar.gz

"http://download.redis.io/releases/redis-5.0.3.tar.gz"

RUN

tar

-xvf

redis.tar.gz

The above execution creates 3 image layers. It can be simplified to the following format:

FROM centos

RUN

yum

-y

install

wget

\

   

&&

wget

-O

redis.tar.gz

"http://download.redis.io/releases/redis-5.0.3.tar.gz"

\

   

&&

tar

-xvf

redis.tar.gz

As above, commands are connected with the && symbol, so only 1 image layer is created after execution.

Start building the image

In the directory where the Dockerfile is located, execute the build action.

The following example builds an nginx:v3 (image name:image tag) using the Dockerfile in the directory.

Note: The final . represents the context path for this execution, which will be introduced in the next section.

$ docker build

-t

nginx:v3 .

The output above indicates that the build succeeded.

Context path

In the previous section, we mentioned that the final . of the instruction is the context path. So what is the context path?

$ docker build

-t

nginx:v3 .

The context path refers to this: when docker builds an image and sometimes needs to use files from the local machine (for example, copying), the docker build command, upon learning this path, will package everything under that path.

Parsing: Since docker operates in a C/S mode, our local machine is C and the docker engine is S. The actual build process is completed under the docker engine, so our local files cannot be used at that time. This requires packaging the files in the specified directory on our local machine and providing them to the docker engine.

If the last parameter is not specified, the default context path is the location of the Dockerfile.

Note: Do not put useless files in the context path, because they will be packaged and sent to the docker engine together; too many files will slow down the process.


Instruction details

Dockerfile instructions Description
FROM Specify the base image for subsequent instruction builds.
MAINTAINER Specify the author/maintainer of the Dockerfile. (Deprecated; the LABEL instruction is recommended instead.)
LABEL Add metadata to the image in the form of key-value pairs.
RUN Execute commands in the image during the build process.
CMD Specify the default command when the container is created. (Can be overridden)
ENTRYPOINT Set the main command when the container is created. (Cannot be overridden)
EXPOSE Declare the specific network port the container listens on at runtime.
ENV Set environment variables inside the container.
ADD Copy files, directories, or remote URLs into the image.
COPY Copy files or directories into the image.
VOLUME Create a mount point for the container or declare a volume.
WORKDIR Set the working directory for subsequent instructions.
USER Specify the user context for subsequent instructions.
ARG Define variables passed to the builder during the build process; can be set with the "docker build" command.
ONBUILD Add a trigger when this image is used as the base for another build process.
STOPSIGNAL Set the system call signal sent to the container to exit.
HEALTHCHECK Define a command that periodically checks the container's health status.
SHELL Override the default shell in Docker, used for the RUN, CMD, and ENTRYPOINT instructions.

COPY

The copy instruction copies files or directories from the context directory to a specified path in the container.

Format:

COPY [--chown=:] <源路径1>...  <目标路径>

COPY [--chown=:] ["<源路径1>",...  "<目标路径>"]

[--chown= :] : Optional parameter that lets the user change the owner and group of the files copied into the container.

: The source file or source directory; this can be a wildcard expression whose rules must satisfy Go's filepath.Match rules. For example:

COPY hom* /mydir/

COPY hom?.txt /mydir/

: The specified path inside the container. This path does not need to be created beforehand; if it does not exist, it will be created automatically.

ADD

The ADD instruction is used similarly to COPY (for the same needs, the official recommendation is to use COPY). Their functions are also similar, with the following differences:

CMD

Similar to the RUN instruction, it is used to run programs, but the two run at different points in time:

Purpose: Specify the default program to run for the started container; when the program ends, the container ends. The program specified by the CMD instruction can be overridden by a program specified in the docker run command-line arguments.

Note: If there are multiple CMD instructions in a Dockerfile, only the last one takes effect.

Format:

CMD  

CMD ["<可执行文件或命令>","","",...] 

CMD ["","",...]  # 该写法是为 ENTRYPOINT 指令指定的程序提供默认参数

The second format is recommended because the execution process is clearer. The first format is actually automatically converted to the second format at runtime, and the default executable is sh.

ENTRYPOINT

Similar to the CMD instruction, but it is not overridden by instructions specified in the docker run command-line arguments; instead, those command-line arguments are passed as parameters to the program specified by the ENTRYPOINT instruction.

However, if the --entrypoint option is used when running docker run, it will override the program specified by the ENTRYPOINT instruction.

Advantages: When executing docker run, you can specify the parameters needed by ENTRYPOINT.

Note: If there are multiple ENTRYPOINT instructions in a Dockerfile, only the last one takes effect.

Format:

ENTRYPOINT ["","","",...]

It can be used together with the CMD command: CMD is generally used for variable arguments; here CMD is essentially passing arguments to ENTRYPOINT, as the following examples will show.

Example:

Assume an nginx:test image has been built from a Dockerfile:

FROM nginx



ENTRYPOINT ["nginx", "-c"] # 定参

CMD ["/etc/nginx/nginx.conf"] # 变参 

1. Run without passing arguments

$ docker run  nginx:test

The container will run the following command by default to start the main process.

nginx -c /etc/nginx/nginx.conf

2. Run with arguments

$ docker run  nginx:test -c /etc/nginx/new.conf

The container will run the following command by default to start the main process (/etc/nginx/new.conf: assuming this file already exists in the container)

nginx -c /etc/nginx/new.conf

ENV

Set environment variables. Once an environment variable is defined, it can be used in subsequent instructions.

Format:

ENV  

ENV = =...

The following example sets NODE_VERSION = 7.2.0, which can be referenced as $NODE_VERSION in subsequent instructions:

ENV NODE_VERSION 7.2.0



RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz" \

  && curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc"

ARG

Build arguments have the same function as ENV, but a different scope. Environment variables set by ARG are only valid within the Dockerfile, that is, only during the docker build process; they do not exist in the built image.

In the build command docker build, you can use --build-arg = to override.

Format:

ARG <参数名>[=<默认值>]

VOLUME

Define an anonymous volume. If you forget to mount a volume when starting a container, it will be automatically mounted to an anonymous volume.

Function:

Format:

VOLUME ["<路径1>", "<路径2>"...]

VOLUME <路径>

When starting a container with docker run, we can modify the mount point with the -v parameter.

EXPOSE

It only declares a port.

Function:

Format:

EXPOSE <端口1> [<端口2>...]

WORKDIR

Specify the working directory. The working directory specified by WORKDIR exists in every layer of the built image. The current directory of subsequent layers is changed to the specified directory; if the directory does not exist, WORKDIR will create it for you.

During the docker build image-building process, every RUN command creates a new layer. Only directories created by WORKDIR persist.

Format:

WORKDIR <工作目录路径>

USER

Used to specify the user and group for executing subsequent commands; it simply switches the user under which subsequent commands run (the user and group must already exist).

Format:

USER <用户名>[:<用户组>]

HEALTHCHECK

Used to specify a program or instruction to monitor the running status of the docker container service.

Format:

HEALTHCHECK [选项] CMD <命令>:设置检查容器健康状况的命令

HEALTHCHECK NONE:如果基础镜像有健康检查指令,使用这行可以屏蔽掉其健康检查指令



HEALTHCHECK [选项] CMD <命令> : 这边 CMD 后面跟随的命令使用,可以参考 CMD 的用法。

ONBUILD

Used to delay the execution of build commands. Simply put, commands specified with ONBUILD in a Dockerfile are not executed during the current image build (assume the image is test-build). When a new Dockerfile uses the previously built image with FROM test-build, then during the build of the new image, the commands specified by ONBUILD in test-build's Dockerfile will be executed.

Format:

ONBUILD <其它指令>

LABEL

The LABEL instruction is used to add metadata to an image in the form of key-value pairs; the syntax is as follows:

LABEL = = = ...

For example, we can add the image's author:

LABEL org.opencontainers.image.authors="runoob"