Skip to Content

Why split a Dockerfile into multiple stages?

Category: DevOps & Deployment

Answer

Multi-stage lets the final image carry ONLY the runtime files (compiled wheel, app code), not the build toolchain (gcc, headers, build tools). Smaller images mean faster pulls, smaller attack surface, and cheaper caching. The build stage uses a heavy base; the runtime stage uses a slim one.

Concrete examples from the fca project context

Example 1

Stage 1 (builder): install gcc, pip install into a venv folder.

Example 2

Stage 2 (runtime): COPY —from=builder the venv + app code, run as non-root USER appuser.

Example 3

Install CPU-only torch first (smaller), THEN requirements.txt (avoid the CUDA build).

Data flow / flow chart

builder: full toolchain -> /install
runtime: slim base + COPY --from=builder /install + app code
  Image size: ~1.2 GB -> ~400 MB

Takeaway

Multi-stage saves GB of image size and dozens of CVEs. Make it the default.