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
Thank you! I didn’t expect to see so many options. I’ll try them out.
Andreas Svensson
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
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
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:
# Build stageFROM debian:11 as builder
RUN apt-get update && apt-get install -y some-package wget
&& wget http://example.com/big-source-code.tar.gz
&& tar xzvf big-source-code.tar.gz
&& do-some-compilation
# Final image stage
FROM debian:11-slim
COPY --from=builder /path/to/app /app
CMD ["/app"]
Erik Pedersen
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:
RUN apt-get update&& apt-get install -y some-package wget
&& mkdir some-build-dir
&& wget http://example.com/big-source-code.tar.gz
&& tar xzvf big-source-code.tar.gz
&& do-some-compilation
&& apt-get purge -y wget
&& rm -rf some-build-dir
&& apt-get purge -y some-package
This will keep only the necessary files in one layer, reducing the overall size of the image.