The Docker Dockerfile command Detailed FROM RUN COPY ADD ENTRYPOINT ...

Dockerfile instruction

These recommendations are designed to help you create an efficient and maintainable Dockerfile.

FROM

Dockerfile FROM command reference

Using the current official image as a base image as much as possible. We recommend Alpine image, because it is tightly controlled and small size (currently less than 5 MB), while still being a full Linux distribution.

label

Understanding Object tag

You can tag your images to help organize the project by image, recording license information to help automate or for other reasons. For each label, LABEL to add one or more lines of the beginning of the key. The following examples show different formats acceptable. Including explanatory comments.

You must refer to a string with spaces or have escaped spaces. Within the quote character ( ") must be escaped.

# Set one or more individual labels

LABEL com.example.version="0.0.1-beta"

LABEL vendor1="ACME Incorporated"

LABEL vendor2=ZENITH\ Incorporated

LABEL com.example.release-date="2015-02-12"

LABEL com.example.version.is-production=""

The image can have multiple labels. Before Docker 1.10, suggested that a combination of all the labels to a LABEL instruction in order to prevent the creation of additional layers. This is no longer necessary, but still support the combination tag.

# Set multiple labels on one line

LABEL com.example.version="0.0.1-beta" com.example.release-date="2015-02-12"

Above can also be written as:

# Set multiple labels at once, using line-continuation characters to break long lines

LABEL vendor=ACME\ Incorporated \

      com.example.is-beta= \

      com.example.is-production="" \

      com.example.version="0.0.1-beta" \

      com.example.release-date="2015-02-12"

Guidance on acceptable label keys and values, see Understanding Object label . For information about query labels, see the managed object tag associated with the filtration project. See Dockerfile Reference LABEL .

RUN

Reference RUN command Dockerfile

RUN Split long or complex statements in the use of the backslash-separated multi-line so that you Dockerfile more readable, understandable and maintainable.

APT-GET are

Probably the most common use cases RUN is an application apt-get. Because it installed package, so the RUN apt-get command has several problems that need attention.

Avoid RUN apt-get upgrade and dist-upgrade, because the parent image many "basic" package can not be in a non-privileged vessel upgrades. If the parent image contained in the package has expired, its maintenance personnel. If you know a particular package, foo needs to be updated, use apt-get install -y foo automatically updated.

Always combine RUN apt-get update in the same statement. For example: apt-get installRUN

RUN apt-get update && apt-get install -y \

    package-bar \

    package-baz \

    package-foo

apt-get update statement in RUN alone causes the cache problems, and the subsequent apt-get install command will fail. For example, suppose you have a Dockerfile:

FROM ubuntu:18.04

RUN apt-get update

RUN apt-get install -y curl

After building the image, all layers in Docker cache. Suppose you later apt-get install package by adding additional modifications:

FROM ubuntu:18.04

RUN apt-get update

RUN apt-get install -y curl nginx

Docker initial instruction and modifications as identical with the previous step cached and reused. As a result, apt-get update in not executed, because the compiler uses the cached version. Because apt-get update is not running, your build likely to get an outdated version of the curl and nginx package.

Use RUN apt-get update && apt-get install -y ensure your Dockerfile install the latest version of the package, without further coding or manual intervention. This technique is called "Cache destruction." You can also be achieved by specifying the package clears the cache version. This is called a fixed version, for example:

RUN apt-get update && apt-get install -y \

    package-bar \

    package-baz \

    package-foo=1.3.*

Version fixed Forces building to retrieve a specific version, regardless of the contents of the cache is. This technique can also reduce failures due to the required package accidental changes caused.

Here is a well-structured RUN explanation, demonstrates all apt-get recommendations.

RUN apt-get update && apt-get install -y \

    on-tools \

    automake \

    build-essential \

    curl \

    dpkg-sig \

    libcap-dev \

    libsqlite3-dev \

    mercurial \

    reprepro \

    ruby1.9.1 \

    ruby1.9.1-dev \

    s3cmd=1.1.* \

 && rm -rf /var/lib/apt/lists/*

The s3cmd parameter specifies a version 1.1. *. If the image was previously used an older version, you specify the new version will lead to destruction of the cache, apt-get update and make sure to install the new version. Each row lists a packet duplicate packet errors can be prevented.

Also, when you are apt to clean it by deleting the cache / var / lib / apt / lists will reduce the image size as apt cache is not stored in the layer. Since RUN statement beginning with # apt-get update, therefore always refresh the package cache apt-get install before refreshing.

The official Debian and Ubuntu images automatically run-GET Clean APT , there is no need to explicitly call.

Use pipe

Some RUN command depends on the use the pipe (|) to pass the output of a command to the ability of another command, the following example:

RUN wget -O - https://some.site | wc -l > /number

Use Docker / bin / sh -c interpreter executes the commands, the code interpreter exit conduit evaluate only the last operation to determine success. In the above example, as long as the wc -l command is successful, even wget command fails, this step also successfully constructed and generate a new image.

If you want the command due to the pipeline at any stage failed with an error, please pre-set -o pipefail && identify unexpected errors, in order to prevent inadvertent build success. E.g:

RUN set -o pipefail && wget -O - https://some.site | wc -l > /number

Not all shell supports the -o pipefail option.

In the case of such dash shell based on the Debian image, consider using exec forms RUN clear choice to support the shell pipefail options. E.g:

RUN ["/bin/bash", "-c", "set -o pipefail && wget -O - https://some.site | wc -l > /number"]

CMD

Reference CMD command Dockerfile

The command CMD is applied to software image including runs and any parameters. CMD should almost always in the form of use CMD [ "executable", "param1", "param2" ...]. Therefore, if the image is used for services, such as Apache and Rails, then you can run something like CMD [ "apache2", "- DFOREGROUND"]. In fact, this form of instruction is recommended for any image-based services.

In most other cases, CMD should give an interactive shell, such as bash, python and perl. For example, CMD [ "perl", " -de0"], CMD [ "python"], or CMD [ "php", "-a "]. Use this form means docker run -it python when you perform a similar operation, you will be placed in the shell available, ready to be used. CMD should be very few ways to use CMD [ "param", "param "] in conjunction with ENTRYPOINT , unless you and your intended user is already very familiar with how ENTRYPOINT work.

EXPOSE

EXPOSE command reference Dockerfile

The EXPOSE command indicating container port listening for connections. Therefore, you should use a common legacy ports for your application. For example, the image 80 includes the Apache Web server EXPOSE will use, and contains images MongoDB will use EXPOSE 27017, and so on.

For external access, your users can use docker run a flag to execute, this flag indicates how to specify the port mapping to port their choice. For containers link, Docker provides environment variables (i.e. MYSQL_PORT_3306_TCP) is returned to the source from the receiving container path.

ENV

Dockerfile reference instruction ENV

To make it easier to run the new software, you can update the PATH environment variable ENV container installed software. For example, ENV PATH / usr / local / nginx / bin: $ PATH ensure CMD [ "nginx"] work.

The ENV instructions specific to your wish to provide the necessary services to accommodate the environment variable is also useful, such as Postgres PGDATA.

Finally, ENV also be used to set common version for easier maintenance release bumps, as shown in the following example:

ENV PG_MAJOR 9.3

ENV PG_VERSION 9.3.4

RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && …

ENV PATH /usr/local/postgres-$PG_MAJOR/bin:$PATH

(Relative to the hard-coded value) using a procedure similar to the constant variable, this method allows you to change a single magic ENV instructions to automatically destroy the software version of the container.

Each ENV line creates a new intermediate layer, like the RUN command. This means that even if you cancel set environment variables in future layers, it will still remain in this layer, and can dump its value. You can test it by creating Dockerfile shown below, and then build it.

FROM alpine

ENV ADMIN_USER="mark"

RUN echo $ADMIN_USER > ./mark

RUN unset ADMIN_USER

$ docker run --rm test sh -c 'echo $ADMIN_USER'

 

mark

To prevent this, and indeed unset environment variables, use the RUN command with shell commands, set in a single layer, use the unset variables and all. You can use; or separate command &&. If you use the second method, and one command fails, the docker build will fail. This is usually a good idea. Use \ Linux Dockerfiles as a line continuation character can improve readability. You can also use all the commands into a shell script, and let the RUN command to run the shell script.

FROM alpine

RUN export ADMIN_USER="mark" \

    && echo $ADMIN_USER > ./mark \

    && unset ADMIN_USER

CMD sh

$ docker run --rm test sh -c 'echo $ADMIN_USER'

 

ADD COPY

Generally, ADD and COPY although similar in function, it is preferable COPY. That is because it is more transparent ADD. COPY supports only basic local files copied to the container while ADD has some features (such as local and remote tar extract URL support is limited), these functions are not obvious. Therefore, the best use of local ADD is automatically extracted tar file to the image, such as ADD rootfs.tar.xz /.

If you have multiple Dockerfile steps using a different file context, it COPIES they are alone, and not one time. This ensures that each step of the construction of the cache only failure (forced re-execute the step) at a specific desired file changes.

E.g:

COPY requirements.txt /tmp/

RUN pip install --requirement /tmp/requirements.txt

COPY . /tmp/

RUN step causes the cache is less than the number of failures is placed COPY. / Tmp / cache invalidation before the number.

Since the image size is very important, ADD is strongly recommended not to use the URL to obtain the package remotely. You should use the curl or wget instead. This way, you can delete files no longer needed after the extraction, there is no need to add other layers in the image. For example, you should avoid doing the following things:

ADD http://example.com/big.tar.xz /usr/src/things/

RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things

RUN make -C /usr/src/things all

But to do something like:

RUN mkdir -p /usr/src/things \

    && curl -SL http://example.com/big.tar.xz \

    | tar -xJC /usr/src/things \

    && make -C /usr/src/things all

For other items (files, directories) do not need to ADDtar automatic extraction function, you should always use COPY.

ENTRYPOINT

Dockerfile reference instruction ENTRYPOINT

The best usage of the host command ENTRYPOINT image is provided, allowing the image of the image as run command (CMD is then used as the default flag).

Let's start from the command line tool example image s3cmd:

ENTRYPOINT ["s3cmd"]

CMD ["--help"]

Now you can display help run a command like this image:

$ docker run s3cmd

Or run with the correct parameters:

$ docker run s3cmd ls s3://mybucket

This is useful, because the image name can serve as a reference binary, as shown in the above command.

The ENTRYPOINT instructions may also be used in combination with an auxiliary script that allows it to run commands similar to the above manner, even if the tool is started may require multiple steps.

For example, Postgres official image  using the following script as its ENTRYPOINT:

#!/bin/bash

Seven

 

if [ "$1" = 'postgres' ]; then

    chown -R postgres "$PGDATA"

 

    if [ -z "$(ls -A "$PGDATA")" ]; then

        gosu postgres initdb

    be

 

    exec gosu postgres "$@"

be

 

exec "$@"

The app configured as PID 1

This script uses a execbash command  , so that the application be running the final container PID 1. This allows the application to send the received signal any Unix container. For more information, see ENTRYPOINT reference .

Help script is copied into the container and start the run by ENTRYPOINT container:

COPY ./docker-entrypoint.sh /

ENTRYPOINT ["/docker-entrypoint.sh"]

CMD ["postgres"]

The script allows multiple users to interact with Postgres.

It can simply start Postgres:

$ docker run postgres

Alternatively, it can be used to run and pass parameters to the server Postgres:

$ docker run postgres postgres --help

Finally, it can be used to start a completely different tools, such as Bash:

$ docker run --rm -it postgres bash

VOLUME

VOLUME command reference Dockerfile

Any database storage area applies to the disclosed VOLUME command created by the docker container or storage configuration files / folders. It is strongly recommended that you use any variable and / or the user's image VOLUME serviceable parts.

USER

USER command reference Dockerfile

If the service can run without permission, please use the USER to change a non-root user. First, create users and groups RUN groupadd -r postgres in something like Dockerfile in && useradd --no-log-init -r -g postgres postgres.

Consider an explicit UID / GID

Image users and groups are assigned to non-deterministic UID / GID, because the "next" regardless of image reconstruction, is assigned UID / GID. Therefore, if it is important, you should assign an explicit UID / GID.

Since Go archive / tar package handling sparse files unresolved errors , try to create a user with a very large UID in Docker container could result in volume depletion, because the / var / log / faillog layer container filled with NULL (\ 0 )character. The solution is to pass --no-log-init flag to useradd. Debian / Ubuntu adduser package does not support this flag.

Avoid installing or using, sudo because of its unpredictable behavior TTY and signal repeaters may be causing problems. If you absolutely need similar functionality sudo, for example, initialize the daemon to run it non-root root, consider using the "gosu" .

Finally, in order to reduce the level and complexity USER avoid frequent switching back and forth.

WORKDIR

Dockerfile reference instruction WORKDIR

For clarity and reliable, you should always use absolute paths WORKDIR. In addition, you should use hard to read, troubleshooting, and maintenance instructions WORKDIR proliferation of RUN cd ... && do-something.

ONBUILD

Dockerfile reference instruction ONBUILD

A ONBUILD command after the current execution Dockerfile build. ONBUILD perform sub-image at any exporting FROM current image. The ONBUILD command deemed Dockerfile parents give their children the instruction Dockerfile.

Docker build ONBUILD execute commands Dockerfile before the offspring of any command.

ONBUILD pictures of a given image is very useful for going to build FROM. For example, you would use a language ONBUILD image stack to build any user software Dockerfile written in this language, just as you are ONBUILD variants of Ruby's seen.

Construction of an image to be obtained ONBUILD individual marking, for example: ruby: 1.9-onbuild or ruby: 2.0-onbuild.

Be careful when you put, ADD or COPY in ONBUILD. If the new building of the context of the lack of resources being added, the "onbuild" image will be a catastrophic failure. As mentioned above, adding a separate labeling helps to alleviate this situation by allowing Dockerfile of choice.

Guess you like

Origin www.cnblogs.com/fusheng11711/p/11238991.html