Member-only story
5 easy-to-implement tricks to trim down your Docker image size
Minimize your docker image (plus one bonus)
In this short article we’ll go through 5 tricks (and one bonus) on how to trim down the size of docker images. In doing so we learn more about how Docker builds images and how to use base images. Let’s code!
Before we start: We’re using a lot of terminal commands. Check out this article if you are unfamiliar.
1. Bundling layers
The size of a Docker image is the sum of it’s layers. Since each layer has a little bit of overhead we can make a small but very easy improvement by reducing the number of layers.
Just change:
FROM python:3.9-slim
RUN apt-get update -y
RUN apt-get install some_package
RUN apt-get install some_other_package
To:
FROM python:3.9-slim
RUN apt-get update -y && apt install -y \
package_one \
package_two
I’ve tested this with some packages used for building and listed them below. As you can see we save about 10MB by bundling the layers. Although this is not a huge size reduction, but it’s pretty impressive since it’s such a small effort.
# packages:
git, cmake, build-essential, jq, liblua5.2-dev, libboost-all-dev, libprotobuf-dev, libtbb-dev, libstxxl-dev, libbz2-d
2. Avoid installation of unnecessary packages
If you’re installing packages with apt-get add the --no-install-recommends
tag. This avoids the installation of packages that are recommended but no required alongside a package that you are installing. This is what it looks like:
FROM python:3.9-slim
RUN apt-get update -y && apt install -y --no-install-recommends \
package_one \
package_two
By adding this single flag we save about 40MB. Again, this is not a lot in the whole scheme of things but quite significant since we merely add a single flag.