DEV Community

Cover image for Reducing Docker Container Size
Sharon Fitzpatrick
Sharon Fitzpatrick

Posted on

1

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.

Resources

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

DevOps Directive's video on Docker Multistage Builds

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay