Docker in development: Episode 4
The last episode was about how to perform everyday tasks in our containers. In this episode, we will see alternatives so we can optimize our images.
.dockerignore
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 produces 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 depending 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 50.9MB
. Amazing!
Dive!
There’s an excellent tool called Dive that lets you inspect your image, and therefore a way to shrink it!
FROM:latest
FROM:latest is a linter/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
Do:
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 compromising 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 awesome-docker, you will find new tools, tips, and tricks.
Conclusion
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.