Docker Multi-Stage builds
Optimizing your Docker images with multi-stage builds
Docker images are often larger than they need to be and it’s a good idea to always aim for smaller images by avoiding the installation of unnecessary packages. There are a lot of ways to make them smaller. This post is about using a multi-stage build for that purpose.
According to the single concern principle containers should be designed to run a single isolated process that addresses a single concern. Containers should consume only the resources required for running packaged applications.
It’s good practice to always use the multi-stage builds to create more compact Docker images when you need to build artifacts and then run your application. Let’s take a look at how much disk space we can save by utilizing multi-stage builds and comparing it with building images in one stage.
As an example, we’ll use a simple web app written in Go.
Let’s build a Docker image in one stage and see its size:
docker build -t webapp .
docker images | grep webapp
webapp latest 64a1652ca001 321MB
In this case, we use a single-stage build, and therefore the size of the final Docker image is 321 MB which is way too big considering how little this application is doing.
We can substantially reduce the size of a Docker image using a multi-stage build approach. Let’s rewrite our Dockerfile and rebuild the same application :
docker build -t webapp-multi-stage .
docker images | grep webapp-multi-stage
webapp-multi-stage latest 1edee18acf3 11.7MB
The final image is only 11.7 MB in size. How did we manage to scale down the image so drastically? In the “builder” stage we compiled and built the application, and then copied the compiled result to the final stage using the
--fromflag that copies content from other images.
The multi-stage build approach works well for applications that require a lot of dependencies to build artifacts but don’t require those dependencies to run compiled artifacts. Building an artifact in one stage, and running the binary in the second stage results in more minimal final images.