Python Dockerfile with UV

In the evolving world of Python tooling, UV by Astral is quickly emerging as a game-changer for dependency management.
It’s a fast, Rust-based replacement for pip, virtualenv, and pip-tools—all rolled into one. If you’ve ever been frustrated with the performance or complexity of managing Python environments, UV might be exactly what you’ve been waiting for.
Unlike traditional tools, UV:
- Resolves and installs dependencies blazingly fast.
- Eliminates the need for a separate virtual environment tool.
- Supports lockfiles (uv.lock) for reproducible builds.
- Is fully compatible with pyproject.toml, which is becoming the standard in Python projects.
While the official UV docs provide a minimal Docker setup, I found that in practice it falls a bit short.
After some research (and a fair bit of trial and error), here’s how I’m structuring my Dockerfile to make the most of UV in a robust, production-ready way.
The Dockerfile
dockerfile
Copied!
>FROM python:3.12-slim-bookworm AS builder
>RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates
>ADD https://astral.sh/uv/0.5.31/install.sh /uv-installer.sh
>RUN sh /uv-installer.sh && rm /uv-installer.sh
>ENV PATH="/root/.local/bin/:$PATH"
>ENV UV_COMPILE_BYTECODE=1
>ENV UV_LINK_MODE=copy
>WORKDIR /app
>COPY pyproject.toml uv.lock ./
>RUN uv sync --frozen --no-install-project
># Run arbitrary Python with UV
>RUN uv run python -c "import logging; logging.basicConfig(level=logging.INFO); logging.info('Hello, world')"
>FROM python:3.12-slim-bookworm AS runtime
>WORKDIR /app
># Copy the environment that UV created in the builder stage
>COPY --from=builder /app/.venv /app/.venv
>ENV PATH="/app/.venv/bin:$PATH"
>ENV PYTHONPATH="/app/src:${PYTHONPATH}"
>
Full-stack JavaScript developer working across NestJS, React, and Angular, with Python in the mix when a project calls for it. He keeps an eye on new technologies as they emerge, bringing that curiosity into how he builds and ships products.