SLIM Docker Images


Ever wondered why your single-app Docker container grows to 400 MB?

A Docker container image is essentially piled-up files to be instantiated later as a running container. Docker utilises the Union File System (UnionFS) design, in which files are grouped together in layers. Each layer may contain one or more files, and every layer is positioned on top of the previous layer.

When Docker creates a container for an image, it uses all the image’s layers in a read-only format, adding a thin read-write layer on top of them. This thin read-write layer is what allows us to modify files in a running Docker container.

The maximum number of layers an image can have is 127, provided your underlying storage driver supports it. Let’s see that with a sample Dockerfile.

If we build image and & inspect it with dive, we will get an image efficiency score of “34%” which signifies that there is quite a lot of space wasted in our image. This results in longer image fetch times, additional consumed bandwidth, and slower start-up times.

How can we get rid of this wasted space?

Commands merge

By merging commands, we essentially create a single layer out of the result of this single long command. Since no intermediate layers exist where files are added and later removed in another layer, the final layer will not use any space for such ghost files. Let’s see that by modifying the above Dockerfile.

Now if we build image and & inspect it with dive, we will get an image efficiency score of “100%”.

Squashing the image

An alternative approach to commands merge, especially when using someone else’s Dockerfile that you don’t want or can’t modify, is to build your image with Docker’s squash command.

Unless you’re on a very old Docker version (<1.13), Docker allows us to squash all our layers into a single layer, effectively removing all ghost resources. We can still use the original, unchanged Dockerfile with the many individual commands, but this time we execute the build passing the –squash option:

docker build –squash .

The resulting image is, again, 100% optimised. Link:

Roshit Rajan


More on Roshit Rajan.

Related Posts

Your email address will not be published. Required fields are marked *