Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to make a Mirror in Dockerfile in Docker

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you how to make an image in Dockerfile in Docker, which is easy to understand and well-organized. I hope it can help you solve your doubts. Let's take you to study and learn this article "how to make an image in Dockerfile in Docker".

To create an docker image, you can either create an image based on the container or build an image based on dockerfile. It is important to note, however, that we are not really "creating" a new image, but rather building a new image based on an existing basic image, such as centos or ubuntu.

1. Based on container production

The federated file system (UnionFS) mounts the file system that provides the container, and any changes to the file system within the container are written to a new file layer, which is owned by the container that created it. We mirror-build the container that has made the changes. I use busybox as base image here, and we can think of busybox as a simplified linux system. Run a httpd program on busybox and make it into an image file.

1. Pull the image

~] # docker image pull busybox:latest # pulls... ~] # docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE busybox latest 59788edf1f3e 2 months ago 1.15MB from dockerhub by default

two。 Run Mirror

~] # docker container run-- name bbox-it busybox:latest # launch the image and log in interactively

3. Run httpd

Busybox has its own httpd program.

/ # httpd-hUsage: httpd [- ifv [v]] [- c CONFFILE] [- p [IP:] PORT] [- u USER [: GRP]] [- r REALM] [- h HOME] httpd-d/-e/-m STRING-i Inetd mode-f Don't daemonize-v [v] Verbose-p [ IP:] PORT Bind to IP:PORT (default *: 80)-u USER [: GRP] Set uid/gid after binding to port-r REALM Authentication Realm for Basic Authentication-h HOME Home directory (default.)-c FILE Configuration file (default {/ etc HOME} / httpd.conf)-m STRING MD5 crypt STRING-e STRING HTML encode STRING-d STRING URL decode STRING/ # mkdir / data/html # Home Directory / # echo "httpd server" > > / data/html/index.html # Test Page / # httpd-h / data/html # specify Home Directory Start the service

4. Mirror image production

Open a new console

~] # docker container commit-- help Usage: docker container commit [OPTIONS] CONTAINER [REPOSITORY [: TAG]] Options:-a,-author string Author (e.g., "John Hannibal Smith")-c,-- change list Apply Dockerfile instruction to the created image-m,-- message string Commit message-p -- pause Pause container during commit (default true) ~] # docker container commit-p bbox test/mybbox:v0.1 #-p when making an image The container pauses to prevent data from being written when making an image ~] # docker image ls test/mybbox v0.1 e07687dd8546 1 minutes ago 1.15MB

Note: if you want to change the version number or image name, you can use the docker tag command, but the modification will not overwrite the original image. A new image will be generated, similar to a hard link.

5. Change the startup command

When we run mybbox, we will find that although we have all the files, the httpd service is not running. This is because each image has an initial command started at run time. If we want to run a command when the image starts, we need to specify it when we make the image.

~] # docker image inspect-f {{.Config.Cmd}} test/mybbox:v0.1 [sh] # it can be seen that the mybbox image is still using the initial command of busybox. ~] # docker container commit-a "test"-c 'CMD ["/ bin/httpd,"-h / data/html "]'-p bbox test/mybbox:v0.2~] # docker image inspect-f {{.Config.Cmd}} test/mybbox:v0.2 [/ bin/sh-c [" / bin/httpd, "- h / data/html"]]

6. Push to warehouse

Once the image is created, you can push it to the warehouse. By default, you can push it to dockerhub. We can create an account in dockerhub and create a repository. Then log in to the local docker login, and then you can push the local image. It is important to note that when creating a warehouse on dockerhub, the namespace is test and the name of the warehouse is mybbox (for this experiment), it must be strictly consistent. Since I can't log on dockerhub here, I won't be able to demonstrate anymore.

7. Save the image to local

When the image is made, it can be saved locally for distribution, and there is no need to upload it to the warehouse.

~] # docker image save-o / tmp/mybbox.gz test/mybbox:v0.2 #-o specify the save directory, or multiple images can be saved together ~] # docker image load-I / tmp/mybbox.gz # can be imported when used. Making mirrors based on Dockerfile

In fact, we find that building an image based on a container is very inefficient when the configuration changes frequently or the image needs to be built repeatedly. So we need to use Dockerfile to quickly build the image. Dockerfile is a file that consists of instructions to build the image. The instructions are arranged from top to bottom by the Docker image builder and can be used to modify any information about the image.

Note:

The Dockerfile file needs to be placed in a directory that contains all the files that build the image, and you can create subdirectories.

In the Dockerfile file, the "#" sign begins with a comment, and each behavior is "INSTRUCTION arguments". It is customary to indicate keywords in uppercase (but not case-sensitive), followed by lowercase values.

The first line of each Dockerfile (except the comment line) must use the "FROM" keyword.

When we build the image in docker build, we will package and pass our specified context directory (that is, the directory where the Dockerfile is located) to the docker engine, and not all files in this context will be used in Dockerfile, which will make the directory transferred to the docker engine too large and affect the construction speed, so you can define the .docker file in this directory, write the unused file name to it, and support wildcards.

Minimize the number of layers of the mirror, each line of command in Dockerfile is one layer, too many layers affect the construction efficiency.

The commands in the Dockerfile file are executed line by line from top to bottom.

2.1 Dockerfile command

1.FROM: the FROM directive is the heaviest and must be the first non-comment line at the beginning of the Dockerfile file to specify the benchmark image for the image file construction process, and subsequent instructions run in the running environment provided by this benchmark image. In practice, the benchmark image can be any available image file. By default, docker build will look for the specified image file on the docker host, and if it does not exist, it will pull the required image file from the Docker Hub Registry. If the specified image file cannot be found, docker build will return an error message.

Syntax: FROM [:] FROM @: specified as the name of base image. The image is pulled from dockerhub by default. If you use other repositories, you can specify before the image;: the label of base image is optional. When omitted, it defaults to latest;eg: FROM busybox:latest.

2.MAINTAINER: used to allow the image maker to provide his / her details. Dockerfile does not limit the location where the MAINTAINER instruction can appear, but it is recommended that it be placed after the FROM instruction. It has been replaced by LABEL, but it can still be used.

Syntax: FROM [:] FROM @: specified as the name of base image. The image is pulled from dockerhub by default. If you use other repositories, you can specify before the image;: the label of base image is optional. When omitted, it defaults to latest;eg: FROM busybox:latest.

3.LABEL: the effect is the same as above, specifying multiple metadata

Syntax: LABEL = [=...] eg: LABEL name=test mail=test@163.com

4.COPY: used to copy files from the Docker host to the new image file created

Syntax: COPY... COPY [",..."]: the source file or directory to be copied supports the use of wildcards: destination path, that is, the file system path of the image being created; it is recommended to use an absolute path, otherwise, COPY specifies WORKDIR as its starting path; file replication guidelines: 1. Must be a path in the build context, not a file 2. 0 in its parent directory. If it is a directory, its internal files or subdirectories will be copied recursively, but the directory itself will not be copied 3. 5. If more than one is specified, or wildcards are used in, it must be a directory and must end with / 4. If it does not exist in advance, it will be created automatically, including its parent directory path eg: COPY index.html / data/web/ # finally renamed to web COPY src/ / data/web # src/* without a slash and copied to the / data/web directory COPY test1 test2 / data/web/ # multiple files must be added /

5.ADD: ADD directive is similar to COPY directive. ADD supports the use of TAR files and URL paths.

Syntax: ADD... ADD [",..."] operating guidelines: same as COPY instruction 1. If URL and does not end with /, the specified file will be downloaded and created directly as; if it ends with /, the file specified by the file name URL will be downloaded directly and saved as /. two。 If it is a compressed tar file on a local system, it will be expanded into a directory with a behavior similar to the "tar-x" command; however, tar files obtained through URL will not be automatically expanded; 3. If there are multiple, or if they use wildcards indirectly or directly, it must be a directory path that ends with /; if it does not end with /, it is considered a normal file and its contents will be written directly to the Eg: ADD http://nginx.org/download/nginx-1.14.2.tar.gz / data/ # nginx-1.14.2.tar.gz will be placed in the / data/ directory, and the ADD nginx-1.14.2.tar.gz / date # nginx-1.14.2 directory will be placed in the / data/ directory, which will be decompressed

6.WORKDIR: used to set the working directory for all RUN, CMD, ENTRYPOINT, COPY and ADD in Dockerfile, which takes effect from this definition workdir to the next definition, and also affects the directory when entering the container.

Syntax: WORKDIR Note: in the Dockerfile file, the WORKDIR instruction can appear multiple times, and its path can also be a relative path, but it is relative to the path specified by the previous WORKDIR directive. In addition, WORKDIR can also call the variable eg: WORKDIR / var/log WORKDIR $STATEPATH defined by ENV.

7.VOLUME: used to create a mount point directory in image to mount volumes on Docker host or other containers, but it should be noted that this option can only create container-managed volumes, that is, mount a directory randomly on the host machine, but cannot specify a directory to mount.

Syntax: VOLUME VOLUME ["] Note: if there are previous files under the mount point directory path, the docker run command will copy all previous files to the newly mounted volume after the volume mount is complete. Eg: VOLUME / data # cannot specify the host directory, and it is randomly mounted in / var/lib/docker/volumes/...

8.EXPOSE: used to open the specified port for the container to listen to to communicate with the outside world, but the port binding of the host cannot be specified, and even if EXPOSE is defined in Dockerfile, you must manually add the-P option when starting the container to take effect.

Syntax: EXPOSE [/] [[/]...] Used to specify the transport layer protocol, which can be either tcp or udp. By default, the TCP protocol eg: EXPOSE 11211/udp 11211/tcp # EXPOSE instruction can specify more than one port at a time

9.ENV: used to define the required environment variables for the image and can be called by other instructions that follow in the Dockerfile file (such as ENV, ADD, COPY, etc.) in the format of $variable_name or ${variable_name}.

Syntax: ENV or ENV =. Note: 1. In the first format, all subsequent content is treated as part of it, so only one variable can be set at a time; 2. The second format can be used to set multiple variables at a time, each of which is a key-value pair of "=". If spaces are included, they can be escaped with a backslash (\) or identified by quotation marks; in addition, the backslash can also be used for line continuation; 3. When defining multiple variables, it is recommended to use the second method, so that the-e parameter can be used to specify the environment variable when completing all functions 4.docker run in the same layer, and the same environment variable will override the value eg: ENV name=zhang\ age=15\ sex=N in Dockerfile.

10.ARG: this parameter is somewhat similar to ENV, both specify variable values, but when using ENV, if you want to dynamically pass variable values, you can only pass them in docker run, while ARG can dynamically pass parameter values through-build-arg during the docker build process. In addition, the value of ENV is retained in the mirrored environment variable, but the value of ARG is not saved. So if you want to change the value of a variable during build mirroring, it is recommended to use ARG

The usage is the same as above. The following figure illustrates the construction process. RUN and CMD instructions are described below.

11.RUN: used to specify a command to run during docker build, which can be any command that exists in the underlying image, as shown in the following figure.

Syntax: RUN RUN [",", "] Note: 1. In the first format, it is usually a shell command and runs as "/ bin/sh-c", which means that the process does not have a PID of 1 in the container and cannot receive a Unix signal, so when the container is stopped with the docker stop command, the process does not receive a SIGTERM signal; that is, a sh process is started before running the command, and then the command is run. two。 The argument in the second syntax format is an array of JSON format, where the command to be run is followed by the option or argument passed to the command; however, the command specified in this format is not initiated with "/ bin/sh-c", so common shell operations such as variable substitution and wildcard (?, *, etc.) substitution will not run However, if the command to be run depends on this shell feature, you can replace it with a similar format: RUN ["/ bin/bash", "- c", "", "] eg: RUN ls / data # will execute the" ls / data "command RUN at build time [" / bin/sh ","-c "," mkdir-p / data/hello "]

12.CMD: similar to the RUN directive, the CMD directive can also be used to run any command or application, but the two run at different points in time. The RUN directive runs during the image file construction process (docker build), while the CMD directive runs when a new image file built based on Dockerfile starts a container (docker run). The primary purpose of the CMD directive is to specify the default program to run for the started container, and after it finishes running. The container will also be terminated However, the command specified by CMD can be overridden by the command line option of docker run, and there can be multiple CMD instructions in Dockerfile, but only the last one will take effect.

Syntax: CMD CMD [","] CMD [","] Note: the meaning of the first two syntax formats is the same as RUN. The first usage will start the sh process first, but after executing the command, the sh process will exit and be replaced by the command process. The third is used to provide default parameters for the ENTRYPOINT instruction. Eg: CMD / bin/httpd-f-h $DOC_ROOT # it can be seen below that the sh command is pre-shipped before running the command ~] # docker image inspect-f}} test [/ bin/sh-c / bin/httpd-f-h $DOC_ROOT] ~] # docker container run-- name NAME-it-- rm IMAGE_NAME / bin/bash # CMD specified command can be modified at docker run

13.ENTRYPOINT: a function similar to the CMD instruction, which is used to specify the default running program for the container, thus making the container look like a separate executable program. Unlike CMD, the program started by ENTRYPOINT is not overridden by the parameters specified by the docker run command line, and these command line parameters are passed as arguments to the program specified by ENTRYPOINT. However, the argument to the-- entrypoint option of the docker run command overrides the program specified by the ENTRYPOINT directive.

Syntax: ENTRYPOINT ENTRYPOINT [",", "] Note: the command argument passed in by the 1.docker run command overrides the contents of the CMD instruction and is appended to the ENTRYPOINT command as its last argument. Multiple ENTRYPOINT directives can also exist in the 2.Dockerfile file, but only the last one will take effect. Eg: CMD ["/ bin/ls", "/ etc"] ENTRYPOINT ["/ bin/bash", "- c"] # will start the sh process first, and the command specified by CMD will be passed as a parameter to / bin/bash-c ~] # docker container run-- name NAME-it-- rm IMAGE_NAME / bin/bash # when using entrypoint The command dynamically specified during docker run will be overridden by the command passed as a parameter to the entrypoint definition ~] # docker container run-- name NAME-it-- rm-- entrypoint "/ bin/bash" IMAGE_NAME # entrypoint specified by the command that can be added at docker run-- entrypoint

14.USER: used to specify the user name or UID when running image or any program specified by the RUN, CMD, or ENTRYPOINT instructions in Dockerfile. By default, container runs as the root user.

Syntax: USER | Note: note: it can be any number, but in practice it must be a valid UID for a user in / etc/passwd, otherwise the docker run command will fail.

15.HEALTHCHECK: check the health status of the container.

Syntax: HEALTHCHECK [OPTIONS] CMD commandOPTIONS:-- interval: how often is detected. Default is 30s-- timeout: timeout period. Default is 30s-- start-period: how long after the container starts testing. Default 30s-- retries: number of retries: default 3 response codes: 0:success 1:unhealthy 2:reserved eg: HEALTHECK-- interval=5m-- timeout=30s CMD curl-f http://localhost/ | | exit 1

16.SHELL: when using commands such as RUN, CMD, etc., some formats start a sh process before running the command. The default is / bin/sh, but sometimes we need to change the default SHELL.

Syntax: SHELL ["executable", "parameters"]

17.STOPSIGAL: the default stop-signal is SIGTERM. When docker stop, the signal is sent to the process with PID 1 in the container. Through-- stop-signal, you can set the signal you need. The main purpose is to allow the application in the container to do something first after receiving the signal to achieve the smooth exit of the container. If no processing is done, the container will be forced to exit after a period of time. It will cause a forced interruption of the business, which defaults to 10s. This command is rarely used.

18.ONBUILD: used to define a trigger in Dockerfile, Dockerfile is used in the build image file, which can also be used as a base imag

Another Dockerfile is used as an argument to the FROM instruction to build a new image file, and when the FROM instruction in the later Dockerfile is executed during the build process, it will "trigger" the trigger defined by the ONBUILD instruction in the Dockerfile file of its base image. Simply put, this command is triggered only when someone recreates the image based on your image.

Syntax: ONBUILD Note: 1. Although any instruction can be registered as a trigger instruction, ONBUILD does not nest itself and does not trigger FROM and MAINTAINER instructions 2. Images built with Dockerfile containing ONBUILD instructions should use special tags, such as ruby:2.0-onbuild 3. 0. Care should be taken in using ADD or COPY instructions in ONBUILD instructions, as the context of the new build process fails 2.2simple example if the specified source file is missing.

The container runs nginx:

~] # mkdir myng~] # cd myng~] # cat Dockerfile # Dockerfile for my nginx FROM nginx:1.14-alpine LABEL maintainer= "chuan" ENV DOC_ROOT= "/ data/web/html/" # ARG parameters are not written to the environment variables of the container, so in this environment, PORT will not be passed to the variables in the configuration ENV # ARG PORT=80 ENV PORT=80 COPY entrypoint.sh / bin/ ADD index.html $DOC_ROOT EXPOSE ${PORT} / tcp ENTRYPOINT ["/ bin/entrypoint.sh"] CMD ["/ usr/sbin/nginx", "- g", "daemon off" should be used here "] HEALTHCHECK-- interval=10s-- start-period=10s CMD wget-O-- Q http://${IP:-0.0.0.0}:${PORT:-80}/index.html~]# cat index.html hello world~] # cat entrypoint.sh # exec command indicates that the current process is replaced by the process to be executed Otherwise, this program will run #! / bin/sh # cat > / etc/nginx/conf.d/www.conf as a child of sh

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report