How to create a minimal working Docker image?
Each time I build Docker images, I aim to reduce their size. I want to find a way to create the most compact images possible..
I try to reduce the image size with commands like:
RUN apt-get purge -y wget RUN rm -r some-build-dir RUN apt-get purge -y some-package
Adding cleanup commands to the Dockerfile reduces the image size only slightly. For example, after removing wget and some temporary files, the image only shrank from 1.9 GB to 1.85 GB.
Are there any ready-made scripts for removing unnecessary packages?.
Answers
Oliver Williams
6 months ago
Rating
Thank you! I didn’t expect to see so many options. I’ll try them out.
Andreas Svensson
6 months ago
Rating
Consider using Docker Slim for automatic Docker image optimization. Docker Slim analyzes your images, identifying and removing unnecessary components, making the images smaller and more secure without manual adjustments.
Additionally, to minimize the image size, you can use the experimental Docker Squashing feature. Squashing combines all layers into a single layer, reducing redundancy and overall size.
Kasper Kristensen
6 months ago
Rating
You can use a .dockerignore file to exclude unnecessary files and directories from the build context. This prevents copying unnecessary files into the Docker image, thereby reducing its size.
Thomas Verhoeven
7 months ago
Rating
You can use multi-stage builds. This allows you to build the application in one stage and transfer only the needed artifacts to a lightweight final image. This helps exclude unnecessary files and dependencies from the final image.
Example:
Erik Pedersen
7 months ago
Rating
One approach to reducing the image size is to use a minimal base image, like Alpine, which is significantly smaller than standard images. You can also combine steps within a single RUN command to avoid creating extra layers that retain deleted files.
Example:
This will keep only the necessary files in one layer, reducing the overall size of the image.