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

The method of customizing Image in Dockerfile

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article introduces the relevant knowledge of "Dockerfile customized image method". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The customization of the image is actually customizing the configuration and files added by each layer. We can write the commands to modify, install, build and operate each layer into a script, which is called Dockerfile.

Dockerfile is a text file that contains instructions, each of which builds a layer, so the content of each instruction is to describe how the layer should be constructed.

FROM specifies the base image

The so-called custom image must be based on an image and be customized on it. The basic image must be specified, and FROM is the specified basic image, so FROM is a necessary instruction in a Dockerfile and must be the first instruction.

There are many high-quality official images on docker hub, and there are service images that can be used directly, such as nginx, redis, mysql, tomcat, etc. You can customize the image based on one that best meets our ultimate goal.

If the image of the corresponding service is not found, the official image also provides some more basic operating system images, such as ubuntu, debian, centos, alpine and so on. The software libraries of these operating systems provide us with more room for expansion.

In addition to selecting an existing mirror as the base mirror, Docker also has a special mirror called scratch. This image is a virtual concept, does not actually exist, it represents a blank image

FROM scratch

If you use scratch-based mirroring, it means that you are not based on any mirrors, and the following instructions will exist as the first layer of the mirrors.

For statically compiled programs under Linux, there is no need for an operating system to provide runtime support, and all the necessary libraries are already in the executable, so direct FROM scratch will make the image smaller. Many applications developed in the Goto language use this way to create images, which is one of the reasons why some people think that Go is a particularly suitable language for container microservice architecture.

RUN executes command

The RUN instruction is used to execute command-line commands. Because of the power of the command line, the RUN instruction is one of the most commonly used instructions when customizing images. There are two formats:

/ / shell format RUN

/ / example RUN echo 'Hello, Dockerboards' / usr/share/nginx/html/index.html

/ / exec format RUN ["executable file", "parameter 1", "parameter 2"]

/ / example RUN tar-zxf redis.tar.gz-C / usr/src/redis-- strip-components=1RUN make-C / usr/src/redisRUN make-C / usr/src/redis install

Build an image

Above we customized the nginx image using Dockerfile, and now that we understand the contents of Dockerfile, let's build this image. Execute in the same directory as the Dockerfile file:

Docker build-t nginx:v3. / / notice that there is the last one. Represents the current directory

From the output of the command, we can clearly see the construction process of the image. In step 2, the RUN directive starts a container, executes the required command, and finally commits the container, and then deletes the container used.

COPY copy Fil

Format

COPY...

COPY [",..." [destination path]]

The COPY directive copies the file / directory in the build context directory to the location in the mirror of the new layer. For example:

COPY package.json / usr/src/app/

It can be multiple, or even wildcards, such as:

COPY hom* / mydir/COPY hom?.txt / mydir/

ADD more advanced copy files

The format and nature of the ADD instruction and COPY are basically the same. But some work has been added to COPY, such as a URL, in which case the Docker engine will try to download the linked file.

Docker's official Dockerfile best practices document requires that you use COPY whenever possible, because the semantics of COPY are clear, just copying files, while ADD contains more complex functions and its behavior is not necessarily clear. The most suitable situations for using ADD are those that need to be decompressed automatically. So when choosing between the COPY and ADD instructions, you can follow the principle that all file copies use the COPY instruction, and use ADD only where automatic decompression is required.

CMD Container start Command

Shell format: CMD

Exec format: CMD ["executable", "parameter 1", "parameter 2",...]

Parameter list format: CMD ["Parameter 1", "Parameter 2",...]. After the ENTRYPOINT instruction is specified, specify the specific parameters with CMD

The format of the CMD command is similar to that of RUN, but there are also two formats:

Docker is either a virtual machine or a container is a process. Since it is a process, you need to specify the program and parameters to run when you start the container. The CMD directive is used to specify the default container main process startup command.

ENTRYPOINT entry point

The purpose of ENTRYPOINT, like CMD, is to start the program and parameters in the specified container. ENTRYPOINT can also be replaced at run time, but it is slightly more cumbersome than CMD and needs to be specified by the parameter entrypoint of docker run. When ENTRYPOINT is specified, the meaning of CMD changes. Instead of running its command directly, it passes the contents of CMD as parameters to the ENTRYPOINT instruction. In other words, when the command is actually executed, it becomes:

"

ENV sets environment variables

ENV

ENV = =

There are two formats:

This instruction is very simple, it is just to set the environment variable, whether it is other instructions later, such as RUN, or the runtime application, you can directly use the environment variable defined here.

ENV VERSION=1.0 DEBUG=ON NAME= "Happy Feet" $VERSION # uses environment variables

The following directives can support environment variable expansion: ADD, COPY, ENV, EXPOSE, LABEL, USER, WORKDIR, VOLUME, STOPSIGNAL, ONBUILD.

ARG construction parameters

ARG [=]

Format:

The build parameters have the same effect as ENV, setting environment variables. The difference is that the build environment variables set by ARG will not exist when the container runs in the future. But don't use ARG to save information like passwords, because docker history can still see all the values.

The ARG instruction in Dockerfile is to define the parameter name and define its default value. This default value can be overridden with-- build-arg = in the build command docker build.

VOLUME defines Anonymous Volume

Format:

VOLUME [",",...]

VOLUME

When the container is running, we should try to keep the container storage layer from writing operations. For applications where database classes need to save dynamic data, the database files should be saved in volumes (volume). In order to prevent users from forgetting to mount the directories saved by dynamic files as volumes, in Dockerfile, we can specify some directories to be mounted as anonymous volumes in advance, so that if the user does not specify to mount them at run time, Its application can also run normally without writing a large amount of data to the container storage layer.

VOLUMEN / data

EXPOSE declaration port

Help mirror consumers understand the daemon port of this mirror service to facilitate the configuration of mapping

When random ports are mapped at runtime, that is, docker run-P, the ports of EXPOSE are automatically randomly mapped.

The format is EXPOSE [,...]

The EXPOSE directive declares that the runtime container provides a service port, which is just a declaration that the service on this port will not be opened by the application at runtime because of this declaration.

There are two benefits to using EXPOSE for declaration in Dockerfile:

WORKDIR specifies the working directory

In shell, two consecutive lines are the same process execution environment, so the memory state modified by the previous command will directly affect the latter command.

In Dockerfile, the execution environments of these two lines of RUN commands are fundamentally different, and they are two completely different containers. This is the error caused by a lack of understanding of Dockerfile's concept of building tiered storage. Each RUN starts a container, executes commands, and then commits changes to the storage layer files. The execution of the first layer of RUN cd / app is just a change in the working directory of the current process, a change in memory, and the result does not cause any file changes. When you get to the second layer, you start a brand new container, which has nothing to do with the container in the first layer, so it is naturally impossible to inherit the memory changes in the previous layer.

So if you need to change the location of the working directory for future layers, you should use the WORKDIR directive.

Format is WORKDIR

You can use the WORKDIR instruction to specify the working directory (or current directory). Later, the current directory of each layer will be changed to the specified directory. If the directory does not exist, WORKDIR will help you set up the directory.

I mentioned earlier that some common mistakes made by beginners are to equate Dockerfile with shell scripts. This misunderstanding may also lead to errors such as the following:

RUN cd / appRUN echo "hello" > world.txt

If you run the Dockerfile as a build image, you will find that the / app/world.txt file cannot be found.

USER specifies the current user

Format: USER

USER instructions are similar to WORKDIR in that they change the state of the environment and affect subsequent layers. WORKDIR is to change the working directory, and USER is to change the identity of the layer to execute commands such as RUN,CMD and ENTRYPOINT.

Of course, like WORKDIR, USER only helps you switch to a specified user, which must be established in advance, otherwise it cannot be switched.

RUN groupadd-r redis & & useradd-r-g redis redisUSER redisRUN ["redis-server"]

HEALTHCHECK health check

-- the interval between two health checks in interval=:. Default is 30 seconds.

-- the timeout of the timeout=: health check command. If this event is exceeded, this health check will be considered a failure. The default is 30 seconds.

-- retries=: after a specified number of consecutive failures, the container status is regarded as unhealthy, with a default of 3 times.

Format:

# set the command to check the health status of the container HEALTHCHECK [option] CMD # if the basic image has a health check instruction, you can block its health check instruction HEALTHCHECK NONE

The HEALTHCHECK instruction, which tells Docker how to determine whether the state of the container is normal, is a new instruction introduced by Docker 1.12. Specify a line of command through this instruction, and use this command to judge whether the service state of the container main process is normal or not, so as to reflect the actual state of the container.

After the HEALTHCHECK instruction is specified in a mirror, the container is started with it. The initial state will be starting. After the health check is successful, it will become healthy. If it fails a certain number of times in a row, it will become unhealthy.

HEALTHCHECK supports the following options:

To help troubleshoot, the output of the health check command (including the stdout level stderr) is saved in the health state and can be viewed through docker inspect.

ONBUILD makes wedding clothes for others.

Format: ONBUILD

ONBUILD is a special instruction, followed by other instructions, such as RUN,COPY, etc., which are not executed when the current image is built, but only when it is based on the current image to build the next level of image.

Other instructions in Dockerfile are prepared to customize the current image, but ONBUILD is prepared to help others customize themselves.

Docker save and docker load

Docker also provides docker save and docker load commands to save the image as a tar file, transfer it to another location, and load it in. This is the practice when there is no Docker Registry, and it is no longer recommended. Image migration should directly use Docker Registry, whether using Docker Hub directly or private Registry in private network.

For example: save the nginx image:

Docker save nginx | gzip > nginx-latest.tar.gz

Then we copy the nginx-latest.tar.gz file to another machine and load the image again:

Docker load-I nginx-latest.tar.gz

This is the end of the content of "Dockerfile customized Image method". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Internet Technology

Wechat

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

12
Report