Last episode was about how to perform everyday tasks in our containers. In this episode, we’ll see alternatives so we can optimize our images.
The first tip to decrease the size of your image was already mentioned in the second episode of this series. Having a
.dockerignore file will help you control what files you don’t want in your image, and therefore it will help you decrease the size of it.
Using smaller base images
This is obvious, using smaller base images produce smaller images. In the example we’ve been constructing, we use
ruby:2.6, which is based on debian stretch. The size of this image is
870MB, and dependending on your app’s dependencies they can grow easily and double it. Fortunately, there are other lightweight alternatives such as
ruby:2.6-alpine3.9, based on alpine. The size of this image is only
There’s an excellent tool called dive that let’s you inspect your image, and therefore a way to shrink it!
FROM:latest is a lint/optimizer for your dockerfiles. Try it!
Minimize layers as much as you can
Instead of doing:
RUN apt-get update -qq RUN apt-get install -y build-essential RUN apt-get install -y curl
RUN apt-get update -qq && apt-get install -y build-essential curl
Each line in your dockerfile produces 1 layer. Each layer increases the image size a little. Try to combine layers as much as you can (without compromsing readability) like in the example above.
Tips around package managers
If you’re using
apt-get (instead of alpine’s
apk), you can add
--no-install-recommends to your
apt-get install command. The idea is that it will install necessary dependencies only (no recommended packages). You can also add
rm -rf /var/lib/apt/lists/* after installing your
apt-get dependencies (it’s even better if you do it in the same layer).
If you’re using
apk, you should use
--no-cache, to avoid storing the cache in your resulting image.
Try to keep up
In https://github.com/veggiemonk/awesome-docker you will find new tools/tips/tricks every now and then.
You should try to shrink your image as much as you can. It will help you when you’re trying to deploy your dockerized app to production.