Why Your Docker Images Are So Big (And How to Fix It)
Systems & Signals
0:00 / 0:00
Why Your Docker Images Are So Big (And How to Fix It)
79 просмотров · 6 дней назад
Systems & Signals
19 подписчиков
79 просмотров · 6 дней назад
Our notes app is about fifty lines of Python. Its Docker image was over 200 MB. And it was still running Flask's development server, with a warning saying not to use it in production.
This episode fixes both.
First we find out where the size really comes from, and cut the image in half by changing one word. Then we switch to a real production server, uWSGI, and hit the problem that catches almost everyone: it needs a compiler, and installing one makes the image four times bigger.
The fix is a multi-stage build. You cook in one stage, the kitchen, and ship only the food in a second, small stage, the lunch box. We end up with a smaller image, a production server, and an app that no longer runs as root.
Explained with a kitchen and a lunch box, in plain simple language.
💻 THE MULTI-STAGE DOCKERFILE
Stage 1: the kitchen. It has the tools to build things.
FROM python:3.12-alpine AS kitchen
RUN apk add --no-cache build-base linux-headers
RUN python -m venv /venv
COPY requirements.txt .
RUN /venv/bin/pip install --no-cache-dir -r requirements.txt
Stage 2: the lunch box. Only what the app needs to run.
FROM python:3.12-alpine
COPY --from=kitchen /venv /venv
ENV PATH="/venv/bin:$PATH"
WORKDIR /app
COPY . .
USER nobody
EXPOSE 5000
CMD ["uwsgi", "--http", ":5000", "--module", "app:app", "--master", "--die-on-term"]
📉 MY RESULTS (DISK USAGE)
python:3.12-slim 227 MB
python:3.12-alpine 103 MB
alpine + compilers left inside 464 MB
multi-stage 109 MB
🧠 THE IDEA
Cook in the kitchen. Ship the lunch box.
Only the LAST stage becomes your image.
⚠️ WATCH OUT
1. AS kitchen and --from=kitchen must match exactly
2. uWSGI on alpine needs build-base AND linux-headers
3. Don't forget ENV PATH, or uwsgi is not found
4. Alpine isn't always the answer; slim plus multi-stage works too
(The Dockerfile, requirements and every command are in the pinned comment. The app itself is unchanged from episode 7.)
📚 THIS SERIES — "Docker, Step by Step"
1. Images vs Containers
2. Your first Dockerfile
3. Why your builds are slow (layers and caching)
4. Volumes — stop losing your data
5. Networks — two containers talking
6. Environment variables and secrets
7. Docker Compose — one command, whole app
8. Multi-stage builds — make images small ← you are here
9. Push your image to Docker Hub
10. Final project — everything together
🔔 Subscribe so you don't miss episode 9.
#docker #devops #dockertutorial #multistagebuild #python #beginners