Docker Learning Notes---Dockerfile

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Docker can automatically build the image by reading instructions from a text file that contains all the commands in the Dockerfile.

Every project that needs to use Docker should have a dockerfile that describes the mirroring environment we need.

Dockerfile directive

From

The valid Dockerfile must start from the from and the mirror can be any valid mirror.
The official recommendation is that if you only need a Linux base image, it is recommended to use a Debian image with minimal control.

FROM <image> [AS <name>]或FROM <image>[:<tag>] [AS <name>]或FROM <image>[@<digest>] [AS <name>]

LABEL

LABEL <key>=<value> <key>=<value> <key>=<value> ...

The label directive adds metadata to the image. A label is a key-value pair. To include spaces in a label value, use quotation marks and backslashes, as in command-line parsing. Several usage examples

LABEL "com.example.vendor"="ACME Incorporated"LABEL com.example.label-with-value="foo"LABEL version="1.0"LABEL description="This text illustrates \that label-values can span multiple lines."

An image can have more than one label. To specify more than one label, Docker recommends that label be combined into a single instruction if possible. Each label instruction produces a new layer

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

To view the label of an image, use the Docker inspect command.

$ docker inspect Ubuntu

RUN

If you need to RUN multiple commands, it is recommended to use multiple lines to write out, using (\) separate multiple lines

There are two forms of run

    • Run <command> shell form, command runs in shell, default is/bin/sh
    • RUN ["Executable", "param1", "param2"]
      The run command executes any command in the new layer at the top of the current mirror, submits the result of the disease, and submits the resulting image when the user next Dockerfile

You can use the command to change the default shellin the shell.

In the shell form, you can continue to the next line using \ Speaking an instruction
For example:

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

Equivalent:

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

Note: If you want to use other shells such as bash, use the required shell to pass parameters,RUN ["/bin/bash", "-C", "echo Hello"]

Apt-get

If your base image uses Debian, you will often use the apt-get command to install the software

In general, we'd better not use Apt-get upgrade or apt-get dist-upgrade, which would cause many non-mandatory packages to be installed, which is unnecessary. If you know that you want to update one of the software in the current base image, such as Nginx, use the apt-get install-y nginx to install the update

Usually we will use him as follows:

RUN apt-get update && apt-get install -y \        package-bar \        package-baz \        package-foo

The apt-get update is performed first to ensure that the installed software is a newer version if it is not disturbed by the cache.

Here is an example of using RUN and apt-get :

RUN apt-get update && apt-get install -y \    aufs-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/*

Finally,/var/lib/apt/lists/ is removed in order to clean up the cache to reduce the size of the image, Debian and Ubuntu will automatically call apt-getClean * At the end, eliminating the need to display calls

Cmd

There are three forms of the directive:

    • CMD ["Executable", "param1", "param2"], this is the first way
    • CMD ["param1", "param2"], as the default parameter of entrypoint
    • CMD command param1 param2 shell form

When used in shell or exec format, the cmd instruction sets the command to be executed when the image is run
If you use the shell in the form of CMD, then <command> will execute/BIN/SH-C:

FROM ubuntuCMD echo "This is a test." | wc -

If you want to run with <command> without a shell, you must express the command as a JSON array and provide the full path to the executable file. This array form is the preferred format for CMD. Any other parameter must represent a string in the array individually:

FROM ubuntuCMD ["/usr/bin/wc","--help"]

The CMD directive applies and runs the software contained in the image, and its parameters. CMD should be cmd ["Executable", "param1", "param2" ...] Said.

In many cases, CMD gives an interactive shell, such as bash,python, such as cmd [" perl", "-de0"],cmd ["python"], or cmd ["PHP", "-A "].

EXPOSE

This directive instructs the container to listen on the port of the link, similar to exposing one of the ports in the container, thereby binding the port on the external access. Inside the container, you should use the application's traditional universal port.

EXPOSE <port> [<port>...]

The expose instruction notifies the Docker container to listen for the specified network port at run time. Expose does not allow the host port to be accessed. To do this, you must use the-P flag to publish a series of ports, or use the-P flag to publish all exposed ports. You can expose a port number and publish another port number externally

Env

ENV <key> <value>ENV <key>=<value> ...

Note:

  • The ENV directive sets the environment variable <key> to the value <value>. This value will be in the environment of all descendants Dockerfile commands
  • There are two forms of the Env directive. The first form, Env <key> <value> will set a variable to a value. The entire string after the first space is treated as <value>-, including characters such as spaces and quotation marks.
  • The second form of Env <key>=<value> ... Allows multiple variables to be set at once. Note that the second form uses the equal sign (=) in the syntax, and the first form does not use the equal sign. Like command-line parsing, quotation marks and backslashes can be used to include spaces in values.

For example:

ENV myName John DoeENV myDog Rex The DogENV myCat fluffy和ENV myName="John Doe" myDog=Rex\ The\ Dog \    myCat=fluffy

The result of the above two methods is the same, it is recommended to use the first way.

Use env to update the environment variable PATHin the container, for example:ENV path/usr/local/nginx/bin: $PATH will ensure that CMD ["Nginx"] Works fine.

ENV directives are used to provide the environment variables required for a particular service

The ENV directive can also be used to set a common version number to make it easier to maintain, as shown in the following example:

ENV PG_MAJOR 9.3ENV PG_VERSION 9.3.4RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && …ENV PATH /usr/local/postgres-$PG_MAJOR/bin:$PATH

ADD or COPY

The above two commands are functionally similar and are copied to the container.

Copy only supports local files being copied to the container
ADD not only supports local file copy to container, but also local extract file and remote URL download

So the appropriate use of ADD is to say that the compressed file is extracted into the container. such as ADD ROOTFS.TAR.XZ/

COPY can be used multiple times, such as the following example to reduce the number of invalid run caches:

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

ADD does not encourage the use of remote URLs and extract packages. You should use wget or curl instead. You can delete the unwanted compressed package after the decompression is complete.
The following practices are the correct example:

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 operations that do not need to extract files, we should use copy for file copy operations.

ADD

There are two ways of this directive

    • ADD <src>...<dest>
    • ["<src>",... "<dest>"]

The add instruction will copy the new file, directory or remote file URL <src> , and add it to the path in the image file system <dest>.

<src> can specify multiple resources, but if they are files or directories, they must be relative to the source directory that is being built (the context of the build).

Each <src> may contain wildcard characters and match using Go's Filepath.match rules. For example

ADD hom* /mydir/        # adds all files starting with "hom"ADD hom?.txt /mydir/    # ? is replaced with any single character, e.g., "home.txt"

<dest> is an absolute path, or relative to a path workdir, to which the source will replicate within the target container

ADD test relativeDir/          # adds "test" to `WORKDIR`/relativeDir/ADD test /absoluteDir/         # adds "test" to /absoluteDir/

When you add files or directories that contain special characters, such as [and], you need to escape these paths according to the Golang rule to prevent them from being treated as matching patterns. For example, to add a file named Arr[0].txt, use the following command:

ADD arr[[]0].txt /mydir/    # copy a file named "arr[0].txt" to /mydir/

COPY

There are also two forms of COPY :

    • COPY <src>. <dest>
    • COPY ["<src>",... "<dest>"] (this form is required for paths that contain spaces)

The Copy instruction copies the new file or directory <src and adds it to the file system <dest>of the container on that path.

See the ADD section for additional information

EntryPoint

There are two forms of this directive:

    • entrypoint ["Executable", "param1", "param2"] (preferred)
    • entrypoint command param1 param2 (Shell form)

entrypoint allows you to configure a container to run as an executable file

For example, the following will use the default content to start Nginx and listen on port 80:

docker run -i -t --rm -p 80:80 nginx

Execute from entrypoint example

You can use the Exec form entrypoint to set fairly stable default commands and parameters, and then use either form of CMD to set additional default values that are more likely to change.

FROM ubuntuENTRYPOINT ["top", "-b"]CMD ["-c"]

When you run the container, you can see that this top is the only process:

$ docker run -it --rm --name test  top -Htop - 08:25:00 up  7:27,  0 users,  load average: 0.00, 0.01, 0.05Threads:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie%Cpu(s):  0.1 us,  0.1 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 stKiB Mem:   2056668 total,  1616832 used,   439836 free,    99352 buffersKiB Swap:  1441840 total,        0 used,  1441840 free.  1324440 cached Mem  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND    1 root      20   0   19744   2336   2080 R  0.0  0.1   0:00.04 top

entrypoint example of performing shell form

You can specify a purely string, entrypoint, and execute/bin/sh-c in it. This form will use shell processing to replace the shell environment variable and will ignore any cmd or Docker Run command-line arguments. In order to ensure that Docker stop is issued correctly for any long-running entrypoint executable, you need to remember to start it exec:

FROM ubuntuENTRYPOINT exec top -b

When you run this image, you will see a single PID 1 procedure:

$ docker run -it --rm --name test topMem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cachedCPU:   5% usr   0% sys   0% nic  94% idle   0% io   0% irq   0% sirqLoad average: 0.08 0.03 0.05 2/98 6  PID  PPID USER     STAT   VSZ %VSZ %CPU COMMAND    1     0 root     R     3164   0%   0% top -b

The most appropriate user of the directive is the primary command for the social image, allowing the image to run like the command, and then using CMD as the default flag

ENTRYPOINT ["s3cmd"]CMD ["--help"]

We can enter the following command to display Help for the command

$ docker run s3cmd

Execute the command with the correct parameters:

$ docker run s3cmd ls s3://mybucket

VOLUME

This directive is used to expose any data storage area created by the container, and to configure the storage file or folder. Use the VOLUME directive to configure any mutable or user-maintainable portions.

VOLUME ["/data"]

The volume directive creates an installation point with the specified name and marks it as saving externally installed volumes from the native host or other containers. The value can be a JSON array, VOLUME ["/var/log/"] or a pure string with multiple parameters, such as Volume/var/log or volume/var/log/var/db

USER

This directive is used to configure the user running the service, the general user to change the ordinary user my root user, to resolve the problem of insufficient permissions

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

This user instruction sets the username (or UID) and the optional user group (or GID) to use run when the image is running

Note: When a user does not have a primary group, the image is run using that root group

Workdir

WORKDIR /path/to/workdir

The directive is used to configure the working directory, and its parameters should use an absolute directory. This command is actually a variant of the RUN cd ... && do-something . Make it clearer

The workdir instruction can be used multiple times dockerfile at once. If a relative path is provided, it will be relative to the path of the previous workdir instruction. For example:

WORKDIR /aWORKDIR bWORKDIR cRUN pwd

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

ARG

ARG <name>[=<default value>]

The ARG directive defines the variables that the user can use for Docker build to pass to the builder at build time using the --build-arg <varname>=<value> flag. If the user specifies a build parameter that is not defined in Dockerfile, the build outputs a warning [Warning] One or more Build-args [foo] were not consumed.

Docker files can include one or more arg directives. For example, the following is a valid Docker file

FROM busyboxARG user1ARG buildno...

Arg default value

The ARG directive may optionally include a default value

FROM busyboxARG user1=someuserARG buildno=1...

If the ARG directive has a default value, and if no value is passed at build time, the builder uses the default value.

Onbuild

The directive executes after the current Dockerfile build is complete. Onbuild is executed in any sub-image that is exported from the current image. Treat the Onbuild command as an instruction dockerfile the parent dockerfile give the child.

Note:

  • ddocker version:17.05.0-ce
  • docker-machine Version 0.12.2, build 9371605
  • The above environment is tested successfully in ubuntu16.04 lts
  • The above text is personal view, if there are errors or suggestions please contact me

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.