CloudOps Hub
🐍 Slim Multi-Stage Pattern

Production Dockerfile for Python (FastAPI / Flask)

Multi-stage build separating C-extension compilers (gcc, musl) from the final slim runtime image, resulting in sub-100MB Python containers.

Dockerfile Python 3.12 Slim
# 1. Builder stage with compilation toolchain
FROM python:3.12-slim AS builder

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt

# 2. Lightweight runtime stage
FROM python:3.12-slim AS runner

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PATH=/root/.local/bin:$PATH

# Copy pre-compiled wheels/packages from builder
COPY --from=builder /root/.local /root/.local
COPY . .

EXPOSE 8000

CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Why this pattern is superior

  • No Build Tools in Production: build-essential and compiler tools remain in the discardable builder stage, reducing attack surface.
  • PYTHONUNBUFFERED=1: Forces stdout and stderr to stream instantly to container logs without waiting for buffer flushes.
  • PYTHONDONTWRITEBYTECODE=1: Prevents Python from writing .pyc cache files to disk inside the container.