How do you structure a Python Dockerfile for the best caching and size?
IntermediateProductionBuild Performance & CI
Answer
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS base
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
COPY . .
USER 10001
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]
Heavy compiled deps: build wheels in a builder stage and copy /wheels, or use uv with --mount=type=cache,target=/root/.cache/uv.
More on Build Performance & CI
How do you make Docker builds fast in CI where runners are ephemeral?BeginnerWhat are the cache backends in buildx?BeginnerWhy does `inline` cache often disappoint?AdvancedHow do you structure a Node.js production image?IntermediateHow do you build a small Java image?BeginnerHow do you build a Go image under 15 MB?Beginner