Reduce Docker image size

Geekette
3 min readApr 12, 2021
Reduce Docker image size

We will talk about how to reduce Docker's image size.

This is our Dockerfile

The first thing that anyone will notice that we use RUN twice which mean two distinguished layers and also we used COPY twice but before this let’s see the size of the image

Docker image size

as we see here is 1.5GB 😧 for a simple node app.

First trick

let’s put the two commands after RUN in the same line with && and same for COPY command

This will not change the size SURPRISE! before in older docker version it could help but not anymore the second statement of RUN as the first Dockerfile show will share the cache of the first RUN , but we can keep it for more clear Dockerfile, personally i keep each statement in a line is better especially if you have a lot of dependencies to install

A good trick also when installing a new package is to use -no-install-recommends which means avoid installing recommended packages and it helps really sometimes when the package to install offer a huge recommended packages

So the first trick is not really a trick 😅

Second trick

So here we have two steps BUILD and RUN but the image will serve only the build which means a reduced size, if we take a look we can see this

Docker images size

here we have two images the final one ( for our container)which is slightly smaller 1.43GB and another one that was dedicated to the BUILD COMPILE ( name it what you want)

Third trick

I keep this to the end because it is the key for a smaller size of docker images

PEOPLE! choose carefully your base image, what I mean is to choose a light FROM image.

in the first Dockerfile, we used a node:13 image with a size of 943MB so from the first line we have actually “load” almost 1GB

Dockerfile based on alpine image

but here i used Alpine image which is a small and secure Linux image based on musl libc and busybox, image’s size decreased to more than half

Docker image size with alpine

In the end, What I also recommend is to not install debugger tools such as curl or vim as I did.. and also take care of your .dockerignore 😉 and maybe take a look at https://github.com/GoogleContainerTools/distroless

A good tool that I recommend also to lint and optimize your Dockerfile is https://www.fromlatest.io and another tool to look deep inside of your docker image: dive

Dive tool

Peace from Tunisia ✌️

Excuse my English 😛

--

--

Geekette

Manal lamine just a simple human ( you can call me geekette )