Docker Learning Note five: Dockerfile

Source: Internet
Author: User
Tags file url json min docker run
General references and recommendations

The Docker build command uses Dockerfile or context to build the image, and the build context is a file of the specified local path or URL. The local path is the directory of the local file system, and the URL is the local git repository. The build is run by the Docker daemon, not the CLI. The first thing to do in the build process is to pass the entire context recursively to the daemon, and it is strongly recommended that you build the process in an empty directory. The container should be short-lived using a. dokerignore file to avoid installing unnecessary packages each container only runs a process to minimize the number of layers in multiple-line parameter ordering to set up cache Dockerfile directives

Format:

# commnet
Instruction arguments

Instruction (instruction) is case insensitive, but the Convention uses uppercase.

Environment variables:

The format of the environment variable can be $variable _name or ${variable_name},${variable:-word} indicating that if the variable is set, the result will be that value, if not set, then
The result is Word;${variable:+word}, which indicates that if variable is set, the result is word, and if not set, the result is empty. from

From <image>

OR

From <image>:<tag>

OR

From <image>@<digest>

The from instruction sets the underlying image for the following instruction. A valid Dockerfile file must take from as the first non-annotated instruction. Maintainer

Maintainer <name>

Set the author field of the generated image RUN

Run has two formats: Run <command> Shell, this command executes in the shell, and Linux defaults to/bin/sh-c,windows system default is CMD/S/C RUN ["Executable", " Param1 "," param2 "] exec format

The Run command executes any command at the new level of the current image and submits the result. Apt-get

Avoid executing apt-get upgrade and Dist-upgrade because the required packages in many base images are not upgraded in the privileged container. CMD

CMD has three formats: cmd ["Executable", "param1", "param2"] exec format, preferred format cmd ["param1", "param2"] as the default parameter of entrypoint cmd command param 1 param2 Shell format

The primary purpose of CMD is to provide default values for the execution container. These default values can contain executables, or they can ignore executables, in which case the ENTRYPOINT directive must be specified.

When the shell format or exec format is used, the command set by the cmd instruction is executed when the container is run. Using a JSON array to declare a command, you must use the absolute path of the execution file.

From Ubuntu
CMD ["/USR/BIN/WC", "--help"]

Only one cmd instruction is allowed in a dockerfile file, and if there are multiple cmd instructions, the last cmd command takes effect. If the user has specified a parameter in the Execute Docker Run command, the default value specified by CMD will be overwritten.

Note: the exec format is parsed as a JSON array, so you must use double quotation marks to enclose the word instead of the single quotation mark.

The difference between run and CMD: Run actually runs the command and submits the result during the build image process, and Cmd does nothing during the build image, but specifies the pre-execute command (that is, when the image is run). LABEL

Label execution is to add metadata to the mirror, a label is a key-value pair, and the value of the label is used to add spaces, using double quotes and backslashes. Example:

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. "

Docker can specify multiple labels, each of which produces a new layer, and multiple layers lead to inefficiencies, so it is recommended to merge multiple labels into one label:

LABEL multi.label1= "value1" multi.label2= "value2" other= "Value3"

Or:

LABEL multi.label1= "value1" \
      multi.label2= "value2" \
      other= "Value3"

To view the mirrored label, you can use the Docker inspect command:

"Labels": {
    "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": "Valu E1 ",
    " Multi.label2 ":" value2 ",
    " other ":" Value3 "
},
EXPOSE
EXPOSE <port> [<port>.]

The expose command notifies the Docker container of the ports that are listening at run time. ENV

Env <key> <value>
env <key>=<value> ...

The ENV directive sets the value of the environment variable to. The second format can set multiple key-value pairs, and it is recommended to set multiple key-value pairs in an env instruction because this creates a cache layer. ADD ADD ... ADD ["",... ""] for paths that contain spaces, use this format

The add instruction copies new files, directories, or remote file URLs and adds them to the container's file system path, which can be specified more than one. Each can contain a wildcard character.

All new files or directories are created using UID and GID for 0. If it is a remote file URL, the target will be 600 permissions. If the remote file has an HTTP last-modified header, the timestamp for this HTTP header will be used to set the mtime of the target file.

The Add directive follows the following rules: it must be included in the context of the build and cannot be used with Add. /something/something. If it is a URL and does not end with a slash, the file will be downloaded from the URL and copied to. If it is a URL that ends with a slash, the file name is fetched from the URL and the files are downloaded to/. For example: Add Http://example.com/foobar/will create a file/foobar. Cannot be a URL for the Http://example.com class. If it is a directory, all contents of the directory will be copied, including the file system metadata (the directory itself is not copied, just its contents). If it is a gzip,bzip2 or XZ type of compressed archive file, the file will be extracted as a directory. The remote URL file will not be decompressed. If a directory is copied or decompressed, the same behavior as tar-x: The result is unique:
1, regardless of whether the target path exists and
2, the content of the source directory tree, the conflict on a file-based resolution of "2."

Note: The file is recognized as a compressed format that is based only on the contents of the file, not the file name. For example, an empty file ending with. tar.gz is not recognized as a compressed file, and no decompression error message is generated, but the file is simply copied to the destination by the file. If it is a different type of file, it will be copied separately from its metadata. In this case, if the/end, it will be considered a directory, the content will be written in/base (). If more than one is specified, either directly or using wildcards, it must be a directory and end with/. If it does not end with a slash, it will be considered a regular file and the contents will be written. If it does not exist, all directories that do not exist in the path will be created. COPY Copy <src>, ... <dest> copy ["<src>",... This format is required when you include spaces in the ' <dest> ' path

Copy instructions from copying new file files or directories and adding them to the container's file system path. is an absolute path, or a relative workdir path, in which the source is copied into the target container.

Copy Test relativedir/   # Add "Test" to ' Workdir '/relativedir/
COPY test/absolutedir/  # Add "test" to/absolutedir /

All files and directories are created with UID and GID 0.

Copy follows the following rules: The path must be in the context of the build and cannot use copy. /something/something if it is a directory, all contents of the directory, including metadata, will be copied.

Note: The directory itself will not be copied, only its contents. If it is a different type of file, it will be copied separately from its metadata. In this case, if a slash/end, it will be considered a directory, the content will be written in/base (). If more than one is specified, either directly or using wildcards, it must be a directory and end with/. If you do not end with a slash, it will be considered a generic file, and the contents will be written. If it does not exist, all directories that do not exist in the path will be created. entrypoint entrypoint ["Executable", "param1", "param2"] exec format, recommended entrypoint command param1 param2 shell format

EntryPoint allows the configuration container to run as an executable file.

For example, the following example will start Nginx with the default content, listening on port 80:

Docker run-i-T--rm-p 80:80 Nginx

The command line parameters of Docker run <image> will be appended to all elements in the exec format entrypoint, and will overwrite all elements using the CMD directive. This allows parameters to be passed to the entry point, for example: Docker run <iamge>-D will pass the-D parameter to the entry point, and you can overwrite the entrypoint instruction with the –ENTRYPOINT flag.

Shell forms prevent the use of any cmd or run command-line arguments, but the disadvantage is that entrypoint will start as a/BIN/SH-C subcommand and not pass the signal. This means that the executable file will not be the PID 1 of the container and will not receive the UNIX signal, so your executable won't receive the sigterm from Docker stop <container>.

Only the last entrypoint instruction of the Dockerfile file takes effect. how cmd and entrypoint interact with each other

1. Dockerfile should specify at least one cmd or entrypoint command
2, when using the container as an executable file, you should define EntryPoint
3. Cmd should be used as a way to define the default parameters of the EntryPoint command or execute the AD-HOC command in a container
4. CMD will be overwritten when a container with substitution parameters is run

The following table shows the commands that are performed on different entrypoint/cmd combinations:

No entrypoint entrypoint exec_entry p1_entry entrypoint ["Exec_entry", "P1_entry"]
No CMD Error,not allowed /bin/sh-c Exec_entry P1_entry
CMD ["Exec_cmd", "P1_cmd"] Exec_cmd P1_cmd /bin/sh-c exec_entry p1_entry exec_cmd p1_cmd
CMD ["P1_cmd", "P2_cmd"] P1_cmd P2_cmd /bin/sh-c exec_entry p1_entry p1_cmd p2_cmd
CMD Exec_cmd P1_cmd /bin/sh-c exec_ cmd p1_cmd /bin/sh-c exec_entry p1_entry/bin/sh-c exec_cmd p1_cmd
VOLUME
VOLUME ["/data"]

The volume command creates a mount point with the specified name and marks it as a reserved externally mounted volume from the local host or other container. The value can be a JSON array or a pure string with multiple parameters. USER

USER Daemon

The user instruction sets the username or UID used to run the image, and the user name of any run,cmd,entrypoint instruction in Dockerfile. Workdir

Workdir/path/to/worddir

The Workdir is used to set the working directory for the next run,cmd,entrypoint,copy and add commands in the Dockerfile file. If it does not exist, it will be created even if the subsequent dockerfile instructions are not used. creating a mirror from Dockerfile Making dockerfile Files

1. Create the Project Catalog

$ mkdir Mydockerbuilder

2. Enter the engineering catalogue and create Dockerfile

$ cd Mydockerbuilder && Touch Dockerfile

3, Write Dockerfile

$ vim Dockerfile from

docker/whaleasy:latest
RUN apt-get-y update && apt-get install-y fortunes
CMD /usr/games/fortune-a | Cowsay

Three lines of content are:

Specify base image, that is, create a new image based on Whaleasy:latest

Update the image and install the Fortunes reference program

Commands executed after mirroring is loaded

4. Create image

$ docker build-t Docker-whale.
Sending build context to Docker daemon 2.048 KB ...
snip
Removing intermediate container a8e6faa88df3
successfully built 7d9495d03763
the process of creating a mirror

Docker build-t docker-whale. command to make a mirror called Docker-whale using the Dockerfile file in the current directory. The information that appears during the production process is as follows:

First, Docker checks to make sure it has everything it needs to build.

Sending build context to Docker daemon 2.048 KB

Docker then loads the whalesay:latest image and, if not locally, Docker downloads the image.

Step 1:from docker/whalesay:latest
 ---> fb434121fc77

Next, Docker uses the Apt-get Package Manager to update the package and install the fortunes

Step 2:run apt-get-y update && apt-get install-y Fortunes---> Running in 27d224dfa5b2 Ign http://archive. ubuntu.com Trusty inrelease IGN http://archive.ubuntu.com Trusty-updates inrelease IGN http://archive.ubuntu.com
Trusty-security Inrelease hit http://archive.ubuntu.com trusty release.gpg ..... snip ... Get:15 http://archive.ubuntu.com trusty-security/restricted amd64 Packages [14.8 KB] Get:16 http://archive.ubuntu.com Trusty-security/universe AMD64 Packages [134 KB] Reading package lists ...---> EB06E47A01D2 Reading package lists ... B
Uilding Dependency Tree ...
Reading state information ... The following extra packages'll be Installed:fortune-mod fortunes-min Librecode0 suggested Packages:x11-utils BSDM Ainutils the following NEW packages'll be Installed:fortune-mod fortunes fortunes-min librecode0 0 upgraded, 4 newly
installed, 0 to remove and 3 not upgraded.
Need to get 1961 KB of archives. After this operation, 4817 KB of additional disk space would be Used.
Get:1 http://archive.ubuntu.com/ubuntu/trusty/main librecode0 amd64 3.6-21 [771 KB] ... snip ...
Setting up Fortunes (1:1.99.1-7) ... Processing triggers for Libc-bin (2.19-0ubuntu6.6) ...---> c81071adeeb5 removing Intermediate container 23aa52c1897c

Finally Docker finishes building and reports the results:

Step 3:cmd/usr/games/fortune-a | Cowsay
 ---> Running in a8e6faa88df3
 ---> 7d9495d03763
removing Intermediate container a8e6faa88df3
successfully built 7d9495d03763

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.