Layer-cached Dockerfile

The image is where dev ergonomics meets cluster reality. A good Dockerfile rebuilds fast when your code changes and rebuilds slow only when your dependencies change. Careful layer ordering is how you get there.

Dockerfile
dockerfile
FROM python:3.11-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

WORKDIR /app

RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

COPY pyproject.toml ./
RUN uv sync

COPY . .

ENV PYTHONUNBUFFERED=1
ENV PATH="/app/.venv/bin:$PATH"

EXPOSE 8000

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

pyproject.toml is copied and installed before the app code so Docker caches the dependency layer. Changes to main.py trigger a rebuild of only the last COPY layer. The uv binary is pulled from the official image, not downloaded at build time.

Ordering exercise: Order the Dockerfile layers for best cache behaviour

Loading practice…

Quiz: Quiz

Loading practice…