Small container images offer the following benefits:
To reduce container image sizes, it’s important to understand that container images are composed of multiple layers ( think of them as intermediate images) which form the final image.
At build time, each Dockerfile instruction creates an extra layer.
FROM ubuntu # 4 layers (base image)
MAINTAINER adolfo@orangemonk.net # 1 layer
RUN mkdir -p /app/bin # 1 layer
RUN apt-get install -y wget # 1 layer
So, generally speaking, reducing image size is the art of reducing the number of layers.
Base images are container images that do not have a parent. Container images usually have their own root filesystem with
an operating system installed. Typically, you will create a new image using a base image that contains an operating system. Consider the following when selecting a base image:
Irrespective of where the Dockerfile
is located, all recursive contents of files and directories in the current directory are sent to the Docker daemon as the build context.
Inadvertently including files that are not necessary for building an image results in a larger build context and larger image size.
Use multi-stage builds, to only copy the artifacts you need into the final image.
Tools and debug information can be added to intermediate build stages without increasing the size of the final image.
Avoid installing extra or unnecessary packages. This will reduce complexity, dependencies, build times and image sizes.
For example, don't include a text editor in a database image.
RUN
, COPY
, ADD
instructions create layers and increase the size of image.
To reduce the number of layers and the image size, don't use ADD
to download packages from URLs. Use curl
or wget and d
elete the files you no longer need after they’ve been extracted.
Example:
RUN mkdir -p /usr/src/ether \
&& curl -SL http://vacuum.com/huge.tar.xz \
| tar -xJC /usr/src/ether \
&& make -C /usr/src/ether all
A new container layer is created for every new instruction in the Dockerfile. Commands that are chained together become part of the same image layer.
To provide a good understanding of the content of each layer, group related operations together so that they become part of a single layer.
Take for example:
RUN dnf install -y --setopt=tsflags=nodocs \
httpd vim && \
systemctl enable httpd && \
dnf clean all
Each command associated with the installation and configuration of httpd is grouped and creates a single layer. Grouping operations this way reduces the number of layers and contributes to the legibility of the instructions.