Background information
Common issues in Docker image building
The image building feature of Container Registry uses a Dockerfile to build the final image of an application. During this process, you may encounter the following issues:
Writing a Dockerfile is difficult.
When you are familiar with using the powerful frameworks of programming languages, especially Java, to build applications, you may find it difficult to write Dockerfiles to build application images.
The final image may be large in size.
When you build an image, you may include the compilation, test, and packaging processes of the application in the same Dockerfile. Each command in the Dockerfile creates a layer of the image, which complicates the structure of the image and enlarges the image size.
The source code may be leaked.
You may package the source code of your application in the final image, which may lead to code leakage.
Benefits of multi-stage buildings
When you use multi-stage buildings in a Dockerfile to build images for applications that are developed by using compilation languages such as Java, you can obtain the following benefits:
The final image is built in a secure way.
In the first stage of image building, you must specify an appropriate base image. Then, you need to copy source code to the base image, download application dependencies, compile the source code, test the application, and package the application. In the second stage, you must specify another appropriate base image and copy runtime dependency files generated in the first stage to the base image. This way, the final image does not contain the source code.
The final image has fewer layers and a smaller size.
The final image contains only a base image and compiled artifacts. As a result, the final image consists of few layers and requires a small storage size.
The final image is built at a fast speed.
You can use building tools such as Docker and Buildkit to concurrently run multiple building processes, which accelerates the building of the image.