Multi-Stage Builds for Smaller Images
What You'll Learn
You'll learn how to use multi-stage Dockerfiles to dramatically reduce your AI application's image size by separating build-time dependencies from runtime requirements.
The Problem with Single-Stage Builds
When you write a Dockerfile for an AI application (as covered in "Writing Dockerfiles for Python AI Apps"), you often need compilation tools, build libraries, and development headers to install packages like transformers or torch. These build dependencies can add gigabytes to your final image, even though they're only needed during installation—not when your application actually runs.
How Multi-Stage Builds Work
Think of multi-stage builds like packing for a trip: you need tools to assemble your luggage, but you don't pack the tools themselves. Similarly, multi-stage Dockerfiles use multiple FROM statements—one stage installs everything, and a final stage copies only what's needed to run.
The Pattern
# Stage 1: Build stage (includes heavy build tools)
FROM python:3.10 AS builder
WORKDIR /build
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# Stage 2: Runtime stage (lean and minimal)
FROM python:3.10-slim
WORKDIR /app
# Copy only installed packages, not build tools
COPY --from=builder /root/.local /root/.local
COPY app.py .
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app.py"]
The builder stage contains all compilation dependencies, but the final image uses python:3.10-slim and copies only the installed Python packages—not gcc, make, or other build tools.
Benefits for AI Applications
- Smaller images: Reduce size from 5GB+ to under 2GB
- Faster deployments: Less data to transfer and load
- Reduced attack surface: Fewer binaries mean fewer vulnerabilities
- Lower storage costs: Especially important when managing model files
Key Takeaway: Multi-stage builds separate build-time from runtime, keeping your final AI container lean by discarding unnecessary build dependencies while preserving all functionality.