Dockerfile common directives
A, Dockerfile
Docker can automatically build images from a Dockerfile, which is a document containing multiple instructions. The following
# syntax=docker/dockerfile:1
FROM ubuntu:18.04
COPY . /app
RUN make /app
CMD python /app/app.py
Copy the code
Second, the FROM
The FROM command is used to initialize a new build phase and set the base image for subsequent instructions:
FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]
Copy the code
FROM
The directive is used to specify the base image,ARG
Is the only one that can be locatedFROM
The instruction that precedes the instruction, usually used to declare the version of the underlying image.- A single
Dockerfile
You can have multiple occurrencesFROM
To use the previous build phase as a dependency for another build phase. --platform
Options are available inFROM
Specify platforms in case of multi-platform mirroring. For example, Linux/AMD64, LUNux/ARM64, and Windows/AMD64.AS name
Represents the build phase command, laterFROM
andCOPY --from=name
This term can be used in the notes to refer to the images built at this stage.tag
ordigest
The value is optional. If you omit any of them, the builder defaults to uselatest
The label. If the designation cannot be foundtag
, build will return an error.
ARG CODE_VERSION=latest
FROM base:${CODE_VERSION}
CMD /code/run-app
FROM extras:${CODE_VERSION}
CMD /code/run-extras
Copy the code
Third, the RUN
The RUN command executes commands in a new layer above the current image and commits the results. Run at docker build time.
RUN /bin/bash -c 'source $HOME/.bashrc; \ echo $HOME'
Copy the code
There are two forms of RUN:
- RUN: in shell format, commands are RUN in shell and used on Linux by default
/bin/sh -c
For use on Windowscmd /S /C
. - RUN [” program name “,”param1″,”param1”] : exec form, does not trigger shell, so environment variables like $HOME cannot be used, but it can be executed in a mirror without bash.
Description:
- You can use a backslash (\) to place a single
RUN
The command continues to the next line. RUN
The instruction cache is not automatically invalidated during the next build. You can use--no-cache
Option invalidates the instruction cache. Build caches such as RUN apt-get update will be reused during the next build, when an outdated version of the tool may be installed, but we can invalidate the RUN command cache with the –no-cache flag, as in docker build –no-cache.- Each execution of the Dockerfile instruction creates a new read-only layer for the image. Too many meaningless layers will cause the image to swell too much. You can use && to concatenate multiple commands so that a single image is created after the RUN command is executed.
Some commands will use pipe (|), such as:
RUN wget -O - https://some.site | wc -l > /number
Copy the code
Docker uses the /bin/sh -c interpreter, which only calculates the exit status code of all commands to determine whether the command was successfully executed. As shown above, as long as wc -L is successfully executed, even if the wget command fails, this construction step will generate a new layer of images. If you want the command to fail due to an error at any stage of the command in the pipeline, set set-o pipefail&& as follows:
RUN set -o pipefail && wget -O - https://some.site | wc -l > /number
Copy the code
Note that Debian-based images use exec form support -o pipefail:
RUN ["/bin/bash"."-c"."set -o pipefail && wget -O - https://some.site | wc -l > /number"] Copy the code
Fourth, the CMD
Dockerfile uses the RUN command to complete the installation and configuration of all the environment of docker build, and uses the CMD command to indicate the commands to be executed when the docker RUN command runs the image. Only one CMD command is allowed for Dockerfile. Using more than one CMD cancels all previous commands, with only the last one taking effect. Typically, this is the last command in the entire Dockerfile script.
FROM ubuntu
CMD ["/usr/bin/wc"."--help"]
Copy the code
CMD has three forms:
- CMD [“exec”,”param1″,”param2″] : Run the command exec.
- CMD command param1 param2: Runs in /bin/sh to provide interactive operations.
- CMD [“param1″,”param2”] : Default argument provided to ENTRYPOINT (rarely used).
Fifth, EXPOSE
The EXPOSE directive notification container listens for a port at run time and can specify TCP or UDP. If no protocol is specified, the default is TCP. However, for security, if the Docker run command does not carry the corresponding port mapping parameter, Docker will not map the port out.
EXPOSE 80/tcp
EXPOSE 80/udp
Copy the code
Specify the port mapping mode:
Docker run -p: Publishes all ports to the host interface. Each public port is bound to a random port on the host within the temporary port range defined by /proc/sys/net/ipv4/ip_local_port_range.
Docker run -p: explicitly maps a single port or range of ports.
Sixth, the LABEL
The LABEL command adds a LABEL to an image. The current image inherits the LABEL of the parent image. If the LABEL is the same as the parent image, the previous LABEL is overwritten.
LABEL multi.label1="value1" \
multi.label2="value2" \
other="value3"
或
LABEL multi.label1="value1" multi.label2="value2" other="value3"
Copy the code
You can view image labels in the following ways:
docker image inspect --format=' ' myimage
Copy the code
View the result example:
{
"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"
}
Copy the code
Seven, ENV
Using the ENV command, you can specify environment variables to be automatically set when running the image using the docker run command. This environment variable can be used in any subsequent RUN command and is held while the container runs. Generally used to make software run more easily, for example:
ENV PATH=/usr/local/nginx/bin:$PATH
CMD ["nginx"]
Copy the code
The set environment variable persists and can be viewed using Docker Inspect. These environment variables can be modified using arguments to the docker run –env
=
command.
Eight, ARG
The ARG command defines a variable that the user will only use at build time. It has the same effect as docker build –build-arg
=
. This parameter only exists at build time and is not retained in the image.
ARG <name>[=<default value>]
Copy the code
An ARG is similar to an ENV, except that ENV remains in the container after the mirror build ends, while an ARG disappears after the mirror build ends. The ARG command (Debian distribution only) can be used when you want the entire build process to be non-interactive.
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y ...
Copy the code
Docker has a predefined set of ARG variables that you can use without corresponding directives in 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 with the –build-arg flag, for example:
docker build --build-arg HTTPS_PROXY=https://my-proxy.example.com .
Copy the code
Nine, the ADD
The ADD directive is used to copy a new file, directory, or remote file URL to the container path. Multiple resources can be specified, but if they are files or directories, their paths are interpreted as the source relative to the build context, which is WORKDIR.
The ADD directive has two forms:
ADD [--chown=<user>:<group>] <src>... <dest>
ADD [--chown=<user>:<group>] ["<src>"."<dest>"]
Copy the code
Each may contain a wildcard, and the Match will use Go’s Filepath.Match rule. Is an absolute path, or relative path to WORKDIR. Such as:
Add all files starting with “hom” :
ADD hom* /mydir/
Copy the code
In the following example,? Is replaced with any single character, such as home.txt.
ADD hom? .txt /mydir/Copy the code
All newly created files and directories have UID and GID 0, unless –chown is used to specify UID/GID and permissions. – Chown is only used to build Linux containers.
ADD --chown=55:mygroup files* /somedir/
ADD --chown=bin files* /somedir/
ADD --chown=1 files* /somedir/
ADD --chown=10:11 files* /somedir/
Copy the code
If it is a local tar archive in a ziplable format (identity, Gzip, bzip2, or XZ), it will be unpacked into a directory. Resources in remote urls are not decompressed. When a directory is copied or unpacked, it behaves the same as tar-x.
Ten, COPY
The only difference between the COPY directive and the ADD directive is whether it supports fetching resources from a remote URL. The COPY command can only read resources from the host where the Docker build is executed and COPY them to the image. The ADD directive also supports reading resources from a remote server through a URL and copying them to an image.
For the same COPY command, the volume of the image created by using ADD is larger than that created by using COPY. Therefore, run the COPY command to COPY only files. The ADD directive is better at reading and decompressing local tar files.
11, the ENTRYPOINT
ENTRYPOINT, like CMD, specifies the container launcher and parameters. It is not overridden by the docker Run command line. If you want to override it, you need to specify it via Docker Run — entryPoint.
ENTRYPOINT comes in two forms:
ENTRYPOINT ["exec"."param1"."param1"]
ENTRYPOINT command param1 param2
Copy the code
After ENTRYPOINT is specified, the content of CMD is passed to the ENTRYPOINT directive as a parameter.
Twelve, VOLUME
Creates an attached data volume with the specified name.
VOLUME ["/var/log/"]
VOLUME /var/log
Copy the code
VOLUME provides the following functions:
- Avoid the loss of important data due to container restart.
- Avoid growing containers.
- Save the configuration file.
13, ONBUILD
The ONBUILD directive is added to the image as a trigger directive and is executed only if the image is the base image. The trigger will execute after the FROM directive in the Dockerfile built downstream. If any triggers fail, the FROM instruction aborts, resulting in a build failure. If all triggers succeed, the FROM instruction completes and the build continues as usual.
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src
Copy the code
Note that the ONBUILD directive cannot trigger the FORM and MAINTAINER directives.
14, STOPSIGNAL
Sets the system call signal evoked when the container exits. The signal can be a valid unsigned number that matches a location in the kernel system call table, such as 9, or a signal name in the form of SIGNAME, such as SIGKILL.
STOPSIGNAL signal
Copy the code
The default stop-signal is SIGTERM, which is sent to the docker process whose PID is 1 when the docker stops. After receiving the signal, applications in a container can process unfinished transactions first. This allows applications to gracefully terminate the process and exit the container. If no operation is performed, the container forcibly exits the container after a period of time. Services may be forcibly interrupted. The default time is 10 seconds.
15 and HEALTHCHECK
The HEALTHCHECK directive tells the container how to check that it is still running. When a container has the specified HEALTHCHECK, it has a healthy state in addition to its normal state. The state of the container is initially starting, and the state of the container becomes healthy (regardless of its previous state) as soon as it passes the health check. If a certain number of failed checks are performed, the container status becomes unhealthy.
The HEALTHCHECK directive has two forms:
- HEALTHCHECK [OPTIONS] CMD command: Checks the container health status by running commands inside the container. The exit status of subsequent commands affects the health status of the container, for example:
- 0: SUCCESS – The container is healthy and ready for use
- 1: unhealthy – The container does not work properly
- 2: reserved – No use exit status
- HEALTHCHECK NONE: Disables any health checks inherited from the underlying image.
HEALTHCHECK option (should precede CMD) :
--interval=DURATION
: Check interval. Default:30s
.--timeout=DURATION
If the check timeout period exceeds the threshold, the check fails. Default:30s
.--start-period=DURATION
: Indicates the time during the container initialization phase. If the health check fails in this phase, the container is not counted as the maximum retries. If the check succeeds, the container is started.0s
.--retries=N
: Number of consecutive health check failures. Default:3
.
For example:
HEALTHCHECK --interval=5m --timeout=3s \
CMD curl -f http://localhost/ || exit 1
Copy the code
16, SHELL
The SHELL directive is used to set the default SHELL. On Linux the default shell is [“/bin/sh “, “-c”], Windows is [” CMD “, “/ S”, “/ c”].
SHELL ["exec"."param1"]
Copy the code
SHELL directives are particularly useful on Windows, which has two distinct native shells: CMD and Powershell, and the alternate SH. This SHELL instruction can occur more than once. Each SHELL instruction overrides all previous SHELL instructions and affects subsequent instructions.
FROM
Learn more about the "FROM" Dockerfile command.
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
Copy the code
In the 17th and WORKDIR
The WORKDIR directive sets the working directory for the next RUN, CMD, ENTRYPOINT, ADD, COPY directives in the Dockerfile. If WORKDIR does not exist, it will be created even if it is not used in subsequent Dockerfile directives.
WORKDIR can be used multiple times in a Dockerfile, and if a relative path is provided, it will be relative to the path of the previous WORKDIR directive.
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd
Copy the code
The final output of the PWD command is /a/b/c.
The WORKDIR directive can resolve previous uses of ENV, for example:
ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd
Copy the code
The final output of the PWD command is /path/$DIRNAME.
It is recommended that WORKDIR always use an absolute path. Also, try to avoid using RUN CD.. &&dosomething, a large number of such instructions will reduce readability and make dockerfiles difficult to maintain.
18 and the USER
The RUN directive sets the user name or (UID) and optional user group (or GID) used to RUN the next RUN, CMD, and ENTRYPOINT directives in the Dockerfile.
USER <user>[:<group>]
USER <UID>[:<GID>]
Copy the code
Note that on Linux, when the user does not have a primary group, the mirror (or directive) runs with the root group. On Windows, you must create a user first if the user is not a built-in account. You can also create a user through net User and then specify a user.
FROM microsoft/windowsservercore # Create Windows user in the container RUN net user /add patrick # Set it for subsequent commands USER patrick Copy the code
In the 19th, MAINTAINER
The MAINTAINER directive sets the MAINTAINER of image generation. Such as:
MAINTAINER <name>
Copy the code
Original translation from official document:
Docs.docker.com/engine/refe…
Welcome to pay attention to me, more Linux dry goods waiting for you!