Software Development

Why is my image size so large and what are the best ways to optimize multi-stage builds?

GA Asked by Gary Coleman · 10-06-2025
0 upvotes 8,958 views 0 comments
The question

My Python application image is over 1GB! How can I reduce the footprint of my images? I’ve heard about multi-stage builds but I’m not sure how to copy only the necessary artifacts from the build stage to the final production image. Is Alpine always the best base?

3 answers

0
SA
Answered on 14-06-2025

Large images are a common bottleneck in CI/CD pipelines. To optimize your footprint, multi-stage builds are essential. You should use a "build" stage with all your compilers and dependencies, and then a "final" stage using a minimal base like python:3.9-slim or alpine. Use the COPY --from=build command to pull only the compiled binaries or installed site-packages. In my experience, while Alpine is tiny, it can lead to compatibility issues with certain C-extensions in Python. I often find that "slim" Debian-based images provide a better balance between size and stability. Reducing the number of RUN commands by chaining them with && also helps merge layers and keeps the overall image size down.

0
JE
Answered on 16-06-2025

Have you tried using a tool like 'dive' to inspect your layers and see exactly which step is adding the most weight to your image?

DO 18-06-2025

I haven't heard of 'dive' yet, Jeffrey! That sounds like a lifesaver. I suspect my pip install step is the culprit, as it pulls in a lot of cached files that I don't actually need in production. Does 'dive' show the file changes per layer in images, or just the total size added by each command in the Dockerfile?

0
CY
Answered on 20-06-2025

Try cleaning up the apt cache or pip cache within the same RUN command. It’s a simple trick that can shave off hundreds of megabytes from your final image.

GA 21-06-2025

Cleaning the cache is a pro tip. It’s one of those small things that makes a massive difference when you're scaling up your deployments.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session