Member-only story
Using multi-stage builds to make your docker image 10x smaller
Clean up your Docker images by leaving behind unnecessary tools
In this short article we build an image in multiple stages to significantly reduce the size of our docker image. In the end we’ll have an image that does the exact same thing but is almost 10 times smaller in size! The way we do this is by leaving behind tools we use for building the image.
First we’ll create a Dockerfile for building the image in the “regular” way. Then we upgrade this file, making use of an extra stage, leaving behind our unnecessary artifacts. Lastly we’ll optimize further by experimenting with different docker images. Let’s see how much fat we can trim off; Let’s code!
Before we start
We’re using a lot of terminal commands. Check out this article if you are unfamiliar.
Setup
Imagine we are building an app that needs geographical data. Open StreetMap provides this geodata for us: via geofabrik.de
we can download geodata per country in the .osm.pbf
format. Next we can use a tool called Osmium
to merge these files together. Imagine we only need this merged file to feed to our app.
In summary: we only need to use curl
(for downloading) and osmium
(for merging) once: when we obtain the merged file we don’t need these tools anymore. In a two-stage build we download these tools in the first stage, use them there and then only take the result (the merged file) to the next stage, leaving behind the tools.
Before we see the two-stage build let’s look at the “normal” way.
1. A normal build
In this part we’ll build our image in the simplest way. We keep in mind some small tricks to minimize our image as detailed in this article, though. Here’s the dockerfile:
FROM ubuntu:20.04# BUNDLE LAYERS
RUN apt-get update -y && apt install -y --no-install-recommends \
curl \
osmium-tool \
&& rm -rf /var/lib/apt/lists/*RUN mkdir /osmfiles \
&& mkdir /merged \
&& curl https://download.geofabrik.de/europe/monaco-latest.osm.pbf -o /osmfiles/monaco.osm.pbf \
&& curl…