Interview Prep/Docker/Build Performance & CI

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.

All Docker questions Roadmap: Docker & containers

More on Build Performance & CI