Home Fast python package installs with uv in Docker
Post
Cancel

Fast python package installs with uv in Docker

There is a new, faster alternative to pip installs called uv from the team at Astral behind ruff. It is a drop-in replacement for pip that is designed to be faster and more reliable. I’ve been using it in my Dockerfiles and it has been working well. Here is how you can use it in your Dockerfiles.

To get it really working well in Docker we want to cache the packages that we download from pypi so we don’t have to download them everytime we re-build the container. There are a couple of steps in this process that aren’t that well documented as uv is updated so I’ll show you how to do it here.

Want to accelerate your analysis with Polars? Join over 2,000 learners on my highly-rated Up & Running with Polars course

Here’s the dockerfile that I use to install packages with uv in Docker.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Use a multi-stage build to first get uv
FROM ghcr.io/astral-sh/uv:0.2.12 as uv
# Choose your python version here
FROM python:3.10.1-slim-buster
# Create a virtual environment with uv inside the container
RUN --mount=from=uv,source=/uv,target=./uv \
    ./uv venv /opt/venv
# We need to set this environment variable so that uv knows where
# the virtual environment is to install packages
ENV VIRTUAL_ENV=/opt/venv
# Make sure that the virtual environment is in the PATH so
# we can use the binaries of packages that we install such as pip
# without needing to activate the virtual environment explicitly
ENV PATH="/opt/venv/bin:$PATH"

# Copy the requirements file into the container
COPY requirements.txt .
# Install the packages with uv using --mount=type=cache to cache the downloaded packages
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=from=uv,source=/uv,target=./uv \
    ./uv pip install  -r requirements.txt

Ensure that you pin your version of uv as breaking changes do occur!

One important point - if you

When you run python inside the container you should not need to active the virtual environment because we have added the virtual environment to the PATH. If you are running the container interactively and want to use pip then ensure you add pip to your requirements file so that it is installed in the virtual environment.

Next steps

Want to know more about Polars for high performance data science? Then you can:

This post is licensed under CC BY 4.0 by the author.