fast Python Dockerfile with uv

python
Author

Cody

Published

November 17, 2024

Fast, full-stack Python application with quick build times.


In this post, we’ll look at my Dockerfile:

# Dockerfile
FROM ghcr.io/astral-sh/uv:latest AS uv
FROM python:3.12-slim
# Install the required system packages
RUN apt-get update && apt-get install -y \
    git \
    ffmpeg \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*
# Set the environment variables
ENV PATH=/root/.local/bin:$PATH
# Set the working directory
WORKDIR /app
# Copy the files
COPY readme.md /app/readme.md
COPY pyproject.toml /app/pyproject.toml
COPY .git /app/.git
COPY src /app/src
# Install the Python packages
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=from=uv,source=/uv,target=./uv \
    ./uv pip install 'my-package @ .' --system --upgrade

This allow for a twelve-factor-style Python application deployed with Docker. I use a Docker compose YAML file with a backend server and GUI container, both running the same image with different CLI commands (e.g. my-package server and my-package gui) and mounting a ~/.my-package directory for secrets and persistent data.

My rough Python stack includes:

Of course, many other tools and Python packages are used along the way (and you can use whatever you like!), but this stack contained in a single Dockerfile allows deploying a single-node full-stack Python application with minimal build times locally, on a Raspberry Pi, and on a cloud VM with ease.

Some miscellaneous notes:

Combining this with a few justfile commands makes development and deployment very easy.

Back to top