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 build an image by Dockerfile

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how to build an image in Dockerfile". In daily operation, I believe many people have doubts about how to build an image in Dockerfile. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to build an image in Dockerfile". Next, please follow the editor to study!

The Dockerfile build image is based on the basic image. Dockerfile is a text file that contains some docker instructions written by the user, each of which builds a layer, so the content of each instruction is to describe how the layer should be built.

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 lsREPOSITORY TAG IMAGE ID CREATED SIZEbusybox latest 59788edf1f3e 2 months ago 1.15MB12345 from dockerhub by default

two。 Run Mirror

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

3. Run httpd busybox with the 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 service 123456789101112131415161718

4. Mirror production opens a new console

~] # docker container commit-- helpUsage: 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 The container pauses to prevent data from being written when making an image ~] # docker image lstest/mybbox v0.1 e07687dd8546 1 minutes ago 1.15MB1234567891011

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 there are all files, the httpd service is not running. This is because each image has an initial command started at runtime. 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"]] 123456

6. After the image is pushed to the warehouse, it can be pushed to the warehouse. By default, it is pushed to dockerhub. We can create our own account and warehouse in dockerhub, and then log in to the local docker login to 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 locally 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 it is 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:latest123456789.

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:MAINTAINER 's detail > s detail >: but any text message, but conventionally using the author's name and email address 1234

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

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

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 webCOPY src/ / data/web # src/* to the / data/web directory COPY test1 test2 / data/web/ # multiple files must be added / 123456789101112131415161718

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 / data/ directory, and ADD nginx-1.14.2.tar.gz / date # nginx-1.14.2 directory will be placed in / data/ directory, which will decompress 123456789101112131415

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/logWORKDIR $STATEPATH123456789 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 copies all previous files to the newly mounted volume after the volume mount is complete. Eg:VOLUME / data # cannot specify a host directory and is randomly mounted in / var/lib/docker/volumes/...12345678

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 directive can specify multiple ports 123456 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 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=N123456789101112131415 in the 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.

Insert a picture description here

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 command > RUN [",", "] Note: 1. In the first format, command > 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 you use the docker stop command to stop the container, 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 [" / bin/sh ","-c "," mkdir-p / data/hello "] 1234567891011121314 at build time

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 command > 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 method 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 ~] # 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 can be specified to modify 12345678910111213 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 command > ENTRYPOINT [",", "] Note: the command arguments passed in by the 1.docker run command override the contents of the CMD instruction and are 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"] # starts the sh process first, and the command specified by CMD is 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 passed as a parameter to the life defined by entrypoint ~] # docker container run-- name NAME-it-- rm-- entrypoint "/ bin/bash" IMAGE_NAME # entrypoint specified command can be added at docker run-- entrypoint command overridden by the command after 1234567891011121314

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

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

Syntax:HEALTHCHECK [OPTIONS] CMD commandOPTIONS:--interval: how often is detected. Default 30s--timeout: timeout, default 30s--start-period: how long after the container starts detection, default 30s--retries: number of retries: default 3 response codes: 0:success1:unhealthy2:reservedeg:HEALTHECK-- interval=5m-- timeout=30s CMD curl-f http://localhost/ | | exit 112345678910111213141516

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"] 12

It will cause a forced interruption of the business, which defaults to 10s. This command is rarely used.

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-onbuild3. Care should be taken in using ADD or COPY instructions in ONBUILD instructions, as the context of the new build process fails when the specified source file is missing. 1234562.2 simple example

The container runs nginx:

~] # mkdir myng~] # cd myng~] # cat Dockerfile#Dockerfile for my nginxFROM nginx:1.14-alpineLABEL 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=80ENV PORT=80COPY entrypoint.sh / bin/ADD index.html $DOC_ROOTEXPOSE ${PORT} / tcpENTRYPOINT ["/ 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.htmlhello world~] # cat entrypoint.sh # exec command means to replace the current process with the process to be executed, otherwise the program will run #! / bin/sh#cat > / etc/nginx/conf.d/www.conf $HOSTNAME as a child of sh Listen ${IP:-0.0.0.0}: ${PORT:-8080}; root ${DOC_ROOT:-/usr/share/nginx/html};} EOFexec "$@" ~] # chmod axix entrypoint.sh~] # docker image build. -t test/myweb:v0.1 # PATH to be the parent directory of the Dockerfile file 1234567891011121314151617181920212223242526282930313233343536373839404142

The container runs httpd:

~] # mkdir ap~] # cd ap~] # cat Dockerfile#Dockerfile for my httpdFROM centos:7LABEL maintainer= "chuan" ENV doc_root=/var/www/html\ listen_port=80\ server_name=localhostRUN yum makecache & &\ yum install-y httpd php php-mysql & &\ yum clean allADD phpinfo.php ${doc_root} ADD entrypoint.sh / bin/EXPOSE 80/tcpVOLUME ${doc_root} CMD ["/ usr/sbin/httpd" "- DFOREGROUND"] ENTRYPOINT ["/ bin/entrypoint.sh"] # cat phpinfo.php~] # cat entrypoint.shishpoint.SERVER_NAME=$ SERVER_NAME=$ {doc_root:-/var/www/html} cat > / etc/httpd/conf.d/myweb.conf $LISTEN_PORT$LISTEN_PORT > ServerName "$SERVER_NAME" DocumentRoot "$DOC_ROOT"$DOC_ROOT" > Options none AllowOverride none Require all granted EOFexec "$@" ~] # chmod axix entrypoint.sh~] # docker image build. -t test/myweb:v0.2~] # docker container run-- name myweb2-- rm-P test/myweb:v0.2, the study on "how to build an image in Dockerfile" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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