Reducing the Size of the Image Using Multistage Builds

Learn to reduce the size of the final Docker image for the app.

So far, we have been building our Docker image by:

  • Using a standard Docker Go image as a base.

  • Downloading dependencies in it.

  • Building an executable.

  • Packaging all the above into a new Docker image.

That's a lot of packing! If we check the final size of this image using docker images, we'll find it to be about 1GB. And this is the size of just one image. Ideally, we would want to keep multiple versions of this image and there may be many apps. This would increase the storage required multifold. Think of the amount of storage and, inevitably, the money it's going to cost!

However, as always, Docker provides a solution to this in the form of multi-stage builds.

Multistage builds

As the name suggests, a multistage build allows us to use multiple images and a single Dockerfile to build the final Docker image for our app. You might be wondering why we need multiple images. Won't that just add to the size of the already large Docker image?

Well, no. Let's look at an example to understand this. First, let's list what is actually contributing to the size of the image.

  • Source code and dependencies

  • Base image

  • Executable

Of these, the third one is absolutely essential to running our Go app. Let's see if can optimize the other two with the help of multistage builds.

Removing source code from the image

We'll try to remove the source code by splitting our build process into two steps:

  1. Building the executable using the source code.

  2. Moving this executable to another image and discarding the first one.

The Dockerfile to do this would look something like this:

Get hands-on with 1200+ tech skills courses.