Dockerfile file instructions

    The Dockerfile file is similar to a configuration file. Docker can automatically build the image by reading the instructions in it. The official website address: https://docs.docker.com/engine/reference/builder/ .   
    The content format of Dockerfile is as follows:
        # comment
        # INSTRUCTION arguments
    Although Dockerfile is not case-sensitive, by convention, general instructions are capitalized to distinguish them from the parameters.
    Similar to the "#!/bin/bash" in the beginning of the shell script, there can also be corresponding parsing instructions at the beginning of the Dockerfile, the format is as follows:
        # directive=value (Note: cross-line is not allowed)
    The parsing instructions currently listed on the official website There is only "escape", which is used to customize the escape character, and the default is "\".
    The following begins to introduce the usage of each instruction in the Dockerfile file.
    * FROM
    format:
        FROM image[:tag] or FROM image@digest
    Regarding the FROM instruction, the following points should be noted:
    (1) FROM sets a base image for the subsequent instruction, so it must be in the first non-comment line of the Dockerfile .
    (2) FROM can appear multiple times to create multiple images.
    (3) When tag or digest is omitted, it will be replaced by latest by default.
    * RUN
    The RUN instruction can be used to execute any command in the current image and pass the execution result to the next step in the Dockerfile. The format of the RUN command is:
        RUN command or RUN ["executable", "param1", "param2"]
    Among them, the former belongs to the "shell" form, and the shell for running the command is "/bin/sh -c" by default on Linux ", which defaults to "cmd /S /C" on Windows. The running shell can be changed with a command, such as:
        RUN /bin/bash -c 'echo $HOME'
    The latter is in the "exec" form (it will be parsed as a JSON array, so double quotes must be used), it avoids Trim the shell string to run the command using a base image that does not contain the specified shell to run. It is also possible to use a different run shell with a command like:
        RUN ["/bin/bash", "-c", "echo $HOME"]
    Also, the command shell is not invoked in the "exec" form , so running RUN ["echo", "$HOME"] will not do variable substitution on $HOME (unless you use something like RUN ["sh", "-c", "echo $HOME" ] to execute the shell directly), since it is the shell's job, not docker, to perform environment variable expansion. In addition to this, escaping the backslash "\" is also mandatory, especially on Windows-like systems.
    RUN caches are not automatically invalidated unless a command like "docker build --no-cache" is used or the ADD directive is used (see the ADD directives section below).
    * CMD
    The CMD command sets the default command to run after the image is started. It has the following three forms:
        CMD ["executable", "param1", "param2"] # exec form, recommended
        CMD ["param1", "param2" ] # Default as the parameter of the ENTRYPOINT command
        CMD command param1 param2 #
    There can only be one CMD command in a Dockerfile in shell form. If there are more than one, only the last one will take effect.
    If the user includes parameters when running the "docker run" command, the default corresponding parameters set by CMD will be overwritten.
    * LABEL
    The LABEL directive can create metadata information for an image. The format is:
        LABEL key1=value1 key2=value2 ...
    Among them, when the key or value contains spaces, it should be enclosed in quotation marks. In addition, LABEL also supports the use of escape characters for cross-line definitions.
    * EXPOSE
    The EXPOSE directive is used to indicate to Docker the network port to listen on when the container is running. Its format is:
        EXPOSE port [port ...]
    Note that the port in the container cannot be accessed by external hosts, and the mapped port must be specified with "-p" or "-P" of the "docker run" command.
    * ENV
    This directive can be used to set environment variables. The format is:
        ENV key value
        ENV key=value ...
    When a container is running in an image, its environment variables will always exist. Users can use the command "docker inspect" to view environment variable information, and also use "docker run --env key=value" to modify. However, the persistence of variables can also have some side effects. For example, using the setting "ENV DEBIAN_FRONTEND noninteractive" in a Debian-like base image may confuse the "apt-get" command. To set a value for a single command, use the form "RUN key=value command".
    * ADD
    The ADD command can be used to copy local or remote files or directories (including metadata) to the image. The format is as follows:
        ADD src1 src2 ... dest
        ADD ["src1", ..., "dest"] # When the path contains spaces,
    when multiple srcs (including wildcards) are specified, they must be relative to the Context original directory.
    dest is an absolute path or a path relative to WORKDIR. All newly created files have UID and GID of 0. When src is a remote address, the permissions of the target file will be 600.
    If the image is built by passing the Dockerfile file to the "docker build" command in the standard input, there is no build context in this case, which requires that the Dockerfile can only contain one URL-like ADD command. Alternatively, you can pass a tarball to "docker build", but require that the Dockerfile be in the root directory of the tarball, and the rest will be used as the build context.
    The ADD command does not support file permission authentication, so when the remote file is protected by permission, you should first use a tool such as "RUN wget" or "RUN curl" to authenticate the corresponding permission.
    When the content of src changes, the first parsed ADD instruction will invalidate the cache of subsequent instructions, including the RUN instruction.
    In addition, ADD follows these rules:
    (1) The src path must be in the context to be built, and cannot use something like "ADD ../something dest", because the first step of "docker build" is to send the build context directory to docker daemon.
    (2) If src is a remote address, and dest does not end with "/", then the remote file will be downloaded first, and then copied to dest; otherwise, it will be copied directly to the dest directory.
    (3) When src is a local compressed file, it will be decompressed before copying, but the remote compressed file will not.
    (4) If src is a file of another type, it is copied separately along with its metadata. At this point, if dest ends with "/", it will be treated as a directory, and the contents of src will be written to dest/base(src).
    (5) When multiple srcs are specified (including the case of using wildcards), dest must be a directory ending with "/".
    (6) If dest does not end with "/", it will be treated as a normal file, and the content of src will be written directly to dest.
    (7) When dest does not exist, it will be recursively created.
    * COPY
    format:
        COPY src1 src2 ... dest
        COPY ["src1", ..., "dest"] # When the path contains spaces,
    both COPY and ADD can copy the content of src to dest, the difference is that COPY cannot copy remote files , then the rest of the rules and restrictions are the same.
    * ENTRYPOINT
    ENTRYPOINT configures the container as an executable. The format is as follows:
        ENTRYPOINT ["executable", "param1", "param2"] # exec format, recommended
        ENTRYPOINT command param1 param2 # shell format
    Command line arguments after "docker run image" will be added to the "exec" form of ENTRYPOINT, and will override any CMD-specified arguments. For example, "docker run image -d" will pass "-d" to ENTRYPOINT. The ENTRYPOINT directive can be overridden with "docker run --entrypoint".
    The "shell" form of ENTRYPOINT will prevent the execution of CMD and run command line arguments, but the disadvantage is that it will be treated as a subcommand of "/bin/sh -c", which means that the PID 1 of the container will not be the executable file, And also can't receive UNIX signals, so can't receive SIGTERM signal from "docker stop container" (but stop will be forced to send a SIGKILL signal after timeout to force stop). For it to handle signals correctly and as PID 1, you need to prefix the command with "exec", eg, "ENTRYPOINT exec top -b".
    Also, only the last ENTRYPOINT will take effect.
    Both ENTRYPOINT and CMD define the commands to be executed when the container is running, and their relationship is as follows:
    (1) Dockerfile must specify at least one CMD or ENTRYPOINT.
    (2) When the container is to be regarded as an executable file, ENTRYPOINT should be defined.
    (3) CMD should be used to define additional default parameters for ENTRYPOINT, or to execute ad hoc commands in the container.
    (4) CMD will be overridden by alternative parameters specified when running the container.
    The following table shows the actual command execution when different combinations of ENTRYPOINT and CMD are specified:

    * VOLUME
    This command can be used to create a mount point with the specified name, and can also be used to store externally mounted volumes on the local host or other containers. The format is:
        VOLUME ["/data", ...]
        VOLUME /data ...
    The "docker run" command initializes the newly created mount point and retains data that existed or was generated before parsing to VOLUME.
    The following points need to be noted about VOLUME:
    (1) When using a Windows-like container, the mount point must be either a) non-existent or an empty directory and b) a drive that is not the system drive C:.
    (2) Data changed by subsequent build steps after the mount point is declared will not take effect.
    (3) The mount point is related to the host and is declared when the container is running. This is to maintain image portability, since a given host is not necessarily available on other hosts. Therefore, a host directory (ie, mount point) cannot be mounted in a Dockerfile. VOLUME also does not support specifying a host-dir parameter, you must specify the mount point when creating or running the container.
    * USER
    This command can be used to set the user name and UID when running the image and executing subsequent RUN, CMD and ENTRYPOINT commands. The format is:
        USER daemon
    * WORKDIR
    This command can set the working directory for subsequent RUN and CMD commands (create it if it does not exist). The format is:
        WORKDIR /path/to/workdir
    WORKDIR can be specified multiple times, and if it contains a relative path, it is relative to its previous WORKDIR. Also, WORKDIR can only handle environment variables explicitly set using ENV.
    * ARG
    The ARG instruction defines the variables required by "docker build --build-arg varname=value", and the value set by this option will in turn affect the value of the corresponding variable defined by the ARG in the Dockerfile. The format is:
        ARG varname[=defaultValue]
    The ARG directive can be used multiple times to define multiple variables.
    Note that using this directive in conjunction with "--build-arg" to receive sensitive information should be avoided, since any user of this image can use the "docker history" command to view all build-time variable values.
    The variables defined by the ARG and ENV instructions can be used by the RUN instruction. The environment variable defined by ENV will overwrite the value of the variable of the same name defined by ARG before (including the command line parameter value passed in by "--build-arg"). Combining the two can produce useful interactions, such as the following Dockerfile:
FROM ubuntu
ARG CONT_IMG_VAR
ENV CONT_IMG_VAR $ {CONT_IMG_VAR: -v1.0.0}
RUN echo $CONT_IMG_VAR

    Unlike ARG, the variables defined by ENV are persistent, so you can use ENV like the above example to long-term save the command line parameters received by ARG to the final image.
    The following ARG variables are predefined in Docker (including their capitalized forms):
        http_proxy, https_proxy, ftp_proxy, no_proxy
    Although ARG variables cannot be persisted, they will still affect the build if they are different from the values ​​used in previous builds cached.
    * ONBUILD The
    ONBUILD directive adds trigger directives to an image that are executed when the image is used as a base for another build process. The format is:
        ONBUILD INSTRUCTION
    ONBUILD works like this:
    (1) When the ONBUILD instruction is parsed, the builder adds the trigger instruction to the metadata of the image currently being built without affecting the current build Process.
    (2) At the end of the build, the trigger command list is stored under the "OnBuild" keyword in the image metadata list, which can be viewed using the "docker inspect" command.
    (3) Afterwards, the image can be used as a base for another build process using the FROM instruction. These trigger instructions are executed sequentially in the order in which they are registered when the FROM instruction is processed by the downstream builder. Any error in the execution of any instruction will cause the build process to fail.
    (4) After a successful build, the trigger is removed from the final image and thus cannot be inherited by the grandchild build process.
    Example:
[...]
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src
[...]

    Note: Using ONBUILD ONBUILD to link ONBUILD is not allowed, and the ONBUILD instruction will not trigger the FROM and MAINTAINER instructions.
    * STOPSIGNAL The
    STOPSIGNAL directive sets the signal sent to the container to terminate it. The format is:
        STOPSIGNAL signalNum/signalName
    * HEALTHCHECK
    This command can be used to test whether a container is working. The format is:
        HEALTHCHECK [options] CMD command # Run the command in the container to detect the health status of the container
        HEALTHCHECK NONE # Disable HEALTHCHECK inherited from the base image The
    options options before CMD are:
    (1) --interval=DURATION (default : 30s)
    (2) --timeout=DURATION (default: 30s)
    (3) --retries=N (default: 3)
    It can detect if a running web server is abnormal and cannot handle new connections Case.
    When a container specifies a healthcheck, in addition to the normal state, it also has a "health state", which is initially "starting". No matter what state it was in before, as long as it passes the health check now, it is considered "healthy"; and if it fails multiple times in a row, it is considered "unhealthy".
    In a Dockerfile, there can only be one HEALTHCHECK directive.
    The command after CMD can be of "shell" form or "exec" form.
    The exit status of this instruction represents the health status of the container. Possible values ​​are:
    (1) 0: successful (container is "healthy" and ready to use)
    (2) 1: unhealthy (container does not work correctly)
    (3) 2: reserved
    the following is a check every 5 minutes Example of whether a web server can correctly serve the home page within 3 seconds at a time:
...
HEALTHCHECK --interval=5m --timeout=3s CMD curl -f http://localhost || exit 1
...

    To aid debugging, the output of any command is stored in a healthy state, which can be viewed with the "docker inspect" command.
    When the health status of the container changes, a "health_status" event is generated with the new status.
    * SHELL
    This command can be used to override the default execution shell for commands of the form "shell" (the default shell on Linux is ["/bin/sh", "-c"], on Windows it is ["cmd", "/S ", "/C"]). The format is:
        SHELL ["executable", "param"] The
    SHELL instruction can appear multiple times. Each overwrites the previous SHELL and is then used as the shell to execute other commands that follow. Example:
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 (more efficient)
SHELL ["powershell", "-command"]
RUN Write-Host hello

# Executed as cmd /S /C echo hello (more efficient)
SHELL ["cmd", "/S"", "/C"]
RUN echo hello

    In addition, the SHELL command can be used to modify the way the shell operates. For example, using "SHELL cmd /S /C /V:ON|OFF" on Windows will change the environment variable delayed expansion syntax.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326177943&siteId=291194637