Key takeaways:
Multistage Docker builds reduce image size by keeping only necessary files.
They improve security by limiting access to build dependencies.
These builds simplify image management by grouping related steps.
A typical multistage Dockerfile builds and compiles in one stage, then copies only required files to a smaller runtime image.
Multistage build
To reduce the size of a Docker image, we have a feature enabling multistage build in Docker. This allows us to break down the build process of an image into multiple stages and only include the necessary files and dependencies in the final image.
In a multistage build, we define multiple stages in our Dockerfile. Each stage can have its build instructions, including installing dependencies, compiling code, and creating the application artifact. The final stage will then copy the application artifact from the previous stage and finalize the image with the files and configurations required for the Dockerfile—each for the application to run correctly. It’s more about setting up the runtime environment than installing new packages.
How does multistage build work?
A Dockerfile with multistage builds typically involves defining multiple FROM
statements, each marking a new stage in the build process. Here’s how it works in detail:
Build stage: The first stage involves setting up a temporary environment where the application’s dependencies are installed and the application is compiled or built. For example, you might use a full development environment with tools like compilers or package managers.
Runtime stage: The second stage is focused on the runtime environment. It copies only the necessary files from the first stage, excluding build tools or temporary files that aren’t needed in the production environment. This significantly reduces the size of the final image.
Final image: The final image contains only the minimal files required to run the application, such as the compiled binary or executable and configuration files, but it excludes development tools.
Advantages
There are a few advantages to using such docker files, which are as follows:
This technique is useful in reducing the size of the final image by eliminating the need to include all of the build dependencies in the image, ultimately saving space on our disk and improving our containers’ performance.
The dependencies can be installed in an intermediate stage and copied into the final image. This can also be used to improve the security of our images, as it can make it more difficult for attackers to find vulnerabilities in the build process.
Multistage builds can make it easier to manage our Docker images, as we can group related build steps. This can make it easier to track changes to our images and find the source of any problem.
Building multistage docker
Here is an example of a multistage Dockerfile which will build a simple web app: