Tips to reduce docker size
Last updated
Last updated
A Docker layer represents a set of files or changes that are stacked on top of each other to form a complete Docker image. Each layer is built from instructions in the Dockerfile, such as RUN
, COPY
, and ADD
. Each of these instructions creates a new layer in the Docker image.
In a Dockerfile, each FROM
, RUN
, and COPY
command creates a separate layer, increasing the overall size and build time of the image.
To reduce the size of a Docker image, execute multiple commands in a single RUN
or COPY
instruction to minimize the number of layers in the Dockerfile.
Instead of using separate instructions for each command, combine them together:
It manage to reduce by 2MB
The most obvious way to reduce the size of a Docker image is by using a smaller base image.
If you want to create an image for a Python application, consider using the python:3.9-slim
image instead of python:3.9
.
The size of python:3.9
is about 1.3 GB, while python:3.9-slim
is only about 1 GB.
You can further reduce the image size by using the Alpine version. Alpine images are specifically designed to run as containers and are very small. The python:3.9-alpine
image is only 49 MB.
When we run the apt install
command to install some packages, it installs some unnecessary recommended packages. Using the --no-install-recommends
flag can significantly reduce the image size.
After apt install, we can use this commands (rm -rf /var/lib/apt/lists/*
)to remove the package left in storage to reduce the image size
It reduce alot more this time.
If you do not want to copy certain files into the Docker image, then using a .dockerignore
file can save you some space.
There are some hidden files/folders in the build context that you can transfer to the image using the ADD
or COPY
commands, such as .git
, etc. Including a .dockerignore
file to reduce the size of the Docker image is a good practice.
Example of a .dockerignore
file.
In some cases, you make minor changes to your code and need to repeatedly build the image from the Dockerfile. In such cases, placing the COPY
command after the RUN
command will help reduce the image size, as Docker will be able to make better use of its caching capabilities in this scenario.
It will create a cache for the image with installed dependencies, and each time the code changes, Docker will use this cache to create the image. This will also reduce the Docker build time.
If you need to install some packages in a Docker image and you are downloading them from external sources, it is best to delete those packages after installation.
For example, if you want to install AWS CLI V2 from a zip file, remember to also delete the zip file after successful installation.
Can you compress this dockerfiles to make it smaller?
For python project what might be the files that might add it into .dockerignore
?
craft a sample .dockerignore
file.