Reducing Docker Image size

Reducing Docker Image size

ยท

2 min read

๐Ÿค” Understanding the Problem

In the world of microservices, most of the production is standing on containers. Docker Images are made to bring unity among the developers despite the platform and environment. But obtaining this at cost of memory and speed is not acceptable.

  • Bulkier images take time to get pulled.

  • Increased time to spin up a container using it.

  • It increases the load on the image registry used.

  • With upgrades, it increases and becomes harder to check for vulnerabilities

Let's see an example. Below is the Dockerfile for a simple Calculator program in golang.

Let's check the size of docker image using "docker images" command and this is the size of image

(isme tmuhara ghar chala jaaenga)

๐Ÿ‹ How to reduce Docker Image Size?

  1. Multistage Build

    The idea is to use two different stages in the image. One is to build the binary and the next is to simply use it. In my case, I applied a multistage build pattern. Made a binary on the build stage and used it to run the container.

  2. Use Distroless images

    What is a Distroless image? "Distroless" images contain only your application and its runtime dependencies. They do not contain package managers, shells or any other programs you would expect to find in a standard Linux distribution. Since they are not exposed to OS or any other vulnerabilites which provide security too.

Applying these 2 steps the dockerfile would look something like this for the same calculator program.

In the first part we just build the binary and it doesn't contain any "CMD", "ENTRYPOINT". In the later stage first we use a distroless image which is "scratch" for golang application and running the app from the binary created in first step. You can find the distroless images for different languages here Distroless image Github Repo.

Let's check the size now ๐Ÿ˜ฑ

There are few other steps you can apply to reduce the size even more...

  • Include a .dockerignore file.

  • Reduce unnecessary dependencies.

  • Caching layers to reuse

References

ย