DEV Community 👩‍💻👨‍💻

Cover image for Reducing Docker Container Size
Sharon Fitzpatrick
Sharon Fitzpatrick

Posted on

Reducing Docker Container Size

Two Ways to reduce the size of a docker container

  1. Reduce the size of the layer
  2. Reduce the number of layers

But what is a layer?

A layer is a change applied to an image. Every command you specify ( FROM , RUN , COPY , etc.) in your Dockerfile causes the previous image to change, thus creating a new layer.

Alt Text

Fig.1 - Dockerfile Layer credit: Agent of Change's YouTube

Multistage Builds

The best way to reduce the number of layers is to use a Multistage build. This turns our Docker build into 2 stages. The first stage to be built will be the exe file and the second stage will be an image using that exe file.

The following code shows how to make a multistage Docker.

Alt Text

Fig.2 - Dockerfile Multistage Code Example: Agent of Change's YouTube

Each FROM creates a new stage. The first stage is tagged as ''builder" by the code

FROM golang 1.7.3 AS builder

command. The code afterwards complies the code and all its dependencies together with the RUN command.

The second FROM creates a new stage from the lightweight alpine container and then copies the complied code from the "builder" stage we created previously. The container will be much smaller because the second stage doesn't have to create the complied code; instead it can use the code from the first stage.

Credit for all screenshots posted here are from the amazing YouTube channel Agent of Change. This post is just meant to summarize information taken from his video. Please go check it out and it is linked under Resources.


Agent of Change's video on Docker Layers and Multistage Builds

DevOps Directive's video on Docker Multistage Builds

Top comments (0)

🌚 Life is too short to browse without dark mode