Skip to content

Migrating a Python project to uv: the uv.lock workflow

Adopt the uv lockfile workflow on a real project — import an existing requirements.txt or Poetry set, commit uv.lock, and reproduce the same resolved versions with uv sync --frozen on a laptop, in CI, and in a Docker image.

If you want one Python dependency set that is identical on your laptop, in CI, and inside your container image, the mechanism is two files and one flag: pyproject.toml holds the ranges you declare, uv.lock holds the exact versions the resolver picked, and uv sync --frozen installs the lockfile without ever asking the index again. The trap is that plain uv sync and plain uv run will quietly re-resolve and rewrite uv.lock when they think it is stale — which is helpful on a laptop and a reproducibility hole in a build. This guide walks a real requirements.txt or Poetry project onto uv and then locks down the three places where the resolved set has to match.

What you’ll accomplish

  • Turn an existing requirements.txt or Poetry dependency list into a pyproject.toml plus a committed uv.lock.
  • Separate runtime dependencies from a dev-only group so production installs stay lean.
  • Pin the Python interpreter version alongside the dependency set so both travel with the repo.
  • Add a CI step that fails the build when uv.lock no longer matches pyproject.toml.
  • Build a multi-stage Docker image whose dependency layer is cached and whose versions match the lockfile exactly.

Prerequisites

  • Python 3.9 or newer available on the host if you plan to use the system interpreter. uv can also download and manage its own interpreters (uv python install 3.12), so a very old distro Python is not a blocker.

  • uv installed. The standalone installer is the usual choice and lets you pin the version:

    curl -LsSf https://astral.sh/uv/0.8.4/install.sh | sh

    pipx install uv==0.8.4 works too, as do Homebrew (brew install uv) and a handful of distro packages. Avoid pip install uv into the same virtualenv you are about to manage with uv — it creates a chicken-and-egg problem when uv rebuilds that environment.

  • An existing project to migrate, with either requirements.txt files or a pyproject.toml written for Poetry, plus write access to the CI config and the Dockerfile.

  • An honest caveat: uv still moves fast and occasionally changes behaviour between minor releases. Pin the exact uv version in CI and in your image, upgrade it deliberately, and re-run uv lock when you do. Skim the release notes at the uv repository before a bump.

How it works

pyproject.toml is the declaration. Under [project] you list dependencies as ranges (django>=5.0,<6), plus a requires-python constraint. Nothing in that file names an exact version of a transitive dependency, so it cannot by itself describe a reproducible install.

uv.lock is the resolution. It records every package in the graph — direct and transitive — at one exact version, with content hashes and environment markers. It is a uv-internal format, not a requirements.txt, and it belongs in version control. Treat it the way you treat package-lock.json: generated, reviewed in diffs, never hand-edited.

The important design choice is that uv’s lock is universal. Instead of locking for the machine that ran the resolver, uv resolves across every platform and Python version allowed by requires-python and stores the alternatives with markers. That is why the same uv.lock produces a working install on your macOS laptop and inside a linux/amd64 image without re-resolving — and also why a very wide requires-python makes resolution harder, because a solution has to exist for every version in the range.

Installation is two-layered. uv keeps a global cache (~/.cache/uv on Linux, ~/Library/Caches/uv on macOS) holding unpacked wheels, and materialises the project environment at .venv in the project root by hardlinking out of that cache. That is why a second uv sync finishes in well under a second: nothing is downloaded and almost nothing is copied. It is also why .venv is disposable — delete it, run uv sync --frozen, and you get it back from the lockfile.

Flow from pyproject.toml declared ranges through uv lock to a committed uv.lock, then uv sync --frozen producing the same resolved package versions on a laptop, a CI runner, and a container image

Step-by-step

  1. Confirm which uv you are running. Version skew between your laptop and CI is the most common source of unexpected lockfile churn.

    uv --version
    uv 0.8.4

    If that prints an older version than what CI uses, upgrade before you generate the lock — a newer uv can write lockfile fields an older uv refuses to read.

  2. Start fresh, or adopt in place. For a brand-new project, uv init scaffolds pyproject.toml, a .python-version file, a README.md, and a source stub:

    uv init --python 3.12 billing-api
    Initialized project `billing-api` at `/home/deploy/billing-api`

    For an existing repository you almost never want the scaffold. Run uv init inside the directory only if there is no pyproject.toml yet, and add --bare if you want the metadata without the sample files. If a Poetry-era pyproject.toml already exists, leave it in place and go to the next step instead — uv reads standard [project] metadata, so a Poetry 2.x project that already uses [project] needs almost nothing beyond a new lock and a build-backend entry.

  3. Import an existing requirements.txt. uv add accepts a requirements file and writes each entry into [project.dependencies], resolving as it goes:

    uv add -r requirements.txt
    Resolved 48 packages in 812ms
    Prepared 46 packages in 3.21s
    Installed 46 packages in 121ms
     + asgiref==3.9.1
     + django==5.2.4
     + gunicorn==23.0.0
     + httpx==0.28.1
     + psycopg==3.2.9

    Two judgement calls here. If your requirements.txt was fully pinned (django==5.1.2), those hard pins land in pyproject.toml and you lose patch updates — relax them to ranges by hand afterwards. And if the file was generated by pip-compile, import requirements.in instead, since that is the declared set and the compiled file is the resolved one; the same split is covered in pinning with pip-tools and hashes.

    For a Poetry project, read the versions out of [tool.poetry.dependencies] and add them explicitly, translating Poetry’s caret syntax as you go — ^5.0 means >=5.0,<6:

    uv add 'django>=5.0,<6' 'httpx>=0.27' 'psycopg[binary]>=3.2' gunicorn
    Resolved 48 packages in 46ms
    Audited 46 packages in 0.19ms
  4. Put test and lint tools in a dev group. These belong in the lockfile but must never reach the runtime image:

    uv add --dev pytest pytest-django ruff mypy
    Resolved 61 packages in 340ms
    Installed 13 packages in 88ms
     + mypy==1.17.0
     + pytest==8.4.1
     + pytest-django==4.11.1
     + ruff==0.12.5

    Check pyproject.toml afterwards — you should see a [dependency-groups] table with a dev list. That is the standard group mechanism, and uv sync --no-dev is what excludes it later.

  5. Lock, and read the diff. uv lock writes uv.lock from pyproject.toml without touching .venv:

    uv lock
    git diff --stat uv.lock
    Resolved 61 packages in 128ms
     uv.lock | 1247 ++++++++++++++++++++++++++++++++++

    Open the file once so it stops being mysterious. Each package is a [[package]] block with name, version, a source, a dependencies list, and wheels/sdist entries carrying hash = "sha256:...". To move a single package later, use uv lock --upgrade-package httpx; to re-resolve everything, uv lock --upgrade. Both produce a reviewable diff, which is the whole point of committing the file.

  6. Understand the difference between uv sync and uv sync --frozen. On a laptop, plain sync is what you want: it re-locks if pyproject.toml changed, then makes .venv match.

    uv sync
    Resolved 61 packages in 3ms
    Audited 59 packages in 0.21ms

    In any automated context, use --frozen. It installs from uv.lock as-is and never re-resolves, so a dependency published five minutes ago cannot change what you deploy:

    rm -rf .venv && uv sync --frozen
    Using CPython 3.12.9
    Creating virtual environment at: .venv
    Prepared 59 packages in 1.42s
    Installed 59 packages in 94ms

    There is a middle option, --locked, which errors out if the lockfile is out of date rather than silently using it. Checking the lock in a dedicated step and using --frozen for the install gives the clearest failure messages.

  7. Run everything through uv run. It resolves the project environment for you, so nobody has to remember to activate .venv:

    uv run --frozen pytest -q
    ......................................                          [100%]
    38 passed in 4.12s

    Without --frozen (or --no-sync), uv run will sync first and may update the lockfile. That is convenient interactively and wrong in CI, so make the flag part of the CI command.

  8. Pin the interpreter next to the dependencies. A lockfile that assumes 3.12 and a runner that supplies 3.11 is a reproducibility gap wearing a disguise:

    uv python pin 3.12
    cat .python-version
    Pinned `.python-version` to `3.12`
    3.12

    Commit .python-version. From then on uv sync and uv run select 3.12, downloading a managed CPython if the host has none. Keep requires-python = ">=3.12" in pyproject.toml consistent with it — the pin selects an interpreter, the constraint bounds the resolution.

  9. Fail CI when the lockfile is stale. This is the single most valuable step in the whole migration. uv lock --check verifies that uv.lock is what pyproject.toml would produce, and exits non-zero otherwise:

    uv lock --check
    error: The lockfile at `uv.lock` needs to be updated, but `--check` was provided. To update the lockfile, run `uv lock`.

    A GitHub Actions job that pins uv, checks the lock, installs frozen, and runs tests:

    jobs:
      test:
        runs-on: ubuntu-24.04
        steps:
          - uses: actions/checkout@v4
          - uses: astral-sh/setup-uv@v6
            with:
              version: "0.8.4"
              enable-cache: true
          - run: uv lock --check
          - run: uv sync --frozen --all-extras
          - run: uv run --frozen pytest -q
    Run uv lock --check
    Resolved 61 packages in 96ms

    If you would rather not depend on the action, curl -LsSf https://astral.sh/uv/0.8.4/install.sh | sh in a plain run: step does the same job with the version equally pinned.

  10. Build the image in two stages. Copy only pyproject.toml and uv.lock first so the dependency layer is cached and does not rebuild every time application code changes:

    FROM python:3.12-slim-bookworm AS builder
    COPY --from=ghcr.io/astral-sh/uv:0.8.4 /uv /bin/uv
    ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
    WORKDIR /app
    COPY pyproject.toml uv.lock ./
    RUN --mount=type=cache,target=/root/.cache/uv \
        uv sync --frozen --no-dev --no-install-project
    COPY . .
    RUN --mount=type=cache,target=/root/.cache/uv \
        uv sync --frozen --no-dev
    
    FROM python:3.12-slim-bookworm
    WORKDIR /app
    COPY --from=builder /app /app
    ENV PATH="/app/.venv/bin:$PATH"
    CMD ["gunicorn", "billing.wsgi:application", "--bind", "0.0.0.0:8000"]
    #9 [builder 5/7] RUN uv sync --frozen --no-dev --no-install-project
    #9 0.312 Using CPython 3.12.9 interpreter at: /usr/local/bin/python3.12
    #9 0.318 Creating virtual environment at: .venv
    #9 2.104 Installed 46 packages in 218ms
    #9 DONE 2.3s

    Three details earn their keep. --no-install-project in the first sync installs dependencies only, so editing your own source does not invalidate the layer. UV_LINK_MODE=copy stops uv warning that it cannot hardlink across the cache mount. UV_PYTHON_DOWNLOADS=never makes the build fail loudly if the base image’s interpreter does not satisfy requires-python, instead of pulling a second Python into the image.

Validate it works

Prove reproducibility on a clone that has never seen your caches or your .venv:

git clone git@github.com:example/billing-api.git /tmp/verify && cd /tmp/verify
uv sync --frozen
uv pip list | head -8
Using CPython 3.12.9
Creating virtual environment at: .venv
Installed 59 packages in 1.83s
Package        Version
-------------- -------
asgiref        3.9.1
django         5.2.4
gunicorn       23.0.0
httpx          0.28.1
mypy           1.17.0

Then confirm the interpreter and a representative version from inside the environment:

uv run --frozen python -c "import sys, django; print(sys.version.split()[0], django.__version__)"
3.12.9 5.2.4

Now run the same check inside the built image and compare the output character for character:

docker build -t billing-api:verify .
docker run --rm billing-api:verify python -c "import sys, django; print(sys.version.split()[0], django.__version__)"
3.12.9 5.2.4

For a fuller comparison, uv export --frozen --no-hashes --no-dev prints the resolved runtime set as requirements lines. Run it on the laptop, then get the equivalent list out of the container and diff the two — an empty diff is the end state you were after. Note that the image above installs no pip into .venv, so pip freeze there would report the base image’s system packages instead of your environment; read the installed set from the metadata directly:

docker run --rm billing-api:verify python -c \
  "from importlib.metadata import distributions; \
   print('\n'.join(sorted(f'{d.metadata[\"Name\"]}=={d.version}' for d in distributions())))"
asgiref==3.9.1
django==5.2.4
gunicorn==23.0.0
httpx==0.28.1
psycopg==3.2.9

uv tree --frozen then shows why a given transitive version was chosen.

Troubleshooting

  • --frozen installs an old set, or --locked errors out after a pyproject.toml edit. Somebody changed a declared range without re-locking. Run uv lock, commit the result, and add the uv lock --check step from step 9 so the next occurrence is caught in the pull request rather than in a deploy. A stale lock plus --frozen is not an error condition — that is exactly what the flag promises — so the check step is the only thing that surfaces it.

  • Resolution fails with “no version of X matches” and the range looks fine. Usually requires-python is too wide. If you declare >=3.9 but a transitive dependency dropped 3.9 in its latest release, uv must find a version satisfying every Python in your range, and the only candidates left may be years old. Narrow the floor to what you actually deploy (requires-python = ">=3.12"), re-lock, and the conflict typically vanishes. Read the resolver’s output bottom-up — the last lines name the package pair that could not be reconciled.

  • A package has no wheel for your platform and the container build dies in a compiler. Source-only distributions need build tooling that python:3.12-slim does not ship. Either install it in the builder stage — apt-get install -y --no-install-recommends build-essential libpq-dev before the sync — or switch to a variant that publishes wheels (psycopg[binary] instead of psycopg). Keep the tooling in the builder stage only, so the runtime image stays small.

  • The copied .venv fails at runtime with a missing shared object or a bad interpreter path. A virtualenv contains absolute paths and platform-specific binaries. Copying .venv from a builder into a runtime stage works only when both stages use the same base image, the same architecture, and the same /app path. Building on an arm64 laptop for an amd64 host without --platform linux/amd64 is the usual cause. When in doubt, run uv sync --frozen --no-dev in the final stage instead of copying, and accept the slightly larger image.

  • A dependency only resolves against a pre-release. By default uv ignores pre-releases unless a constraint explicitly asks for one. If a package you need has only a release candidate, opt in narrowly rather than globally: uv add --prerelease allow "some-sdk>=2.0.0rc1". Setting prerelease = "allow" under [tool.uv] for the whole project means every future uv lock may pull release candidates for packages you never intended, so scope it to the one dependency and leave a comment saying when it can be removed.

When this is the wrong approach

A working Poetry or pip-tools pipeline that nobody complains about is not a problem waiting for uv. Migration costs a day of lockfile review plus retraining every contributor’s muscle memory, and the payback is mostly CI minutes. If your dependency install is not on the critical path of your build time, spend the day elsewhere — the trade-offs between the tools are laid out in Poetry, PDM, or uv.

Scientific and machine-learning stacks that live on conda or mamba are a poor fit. uv resolves Python distributions from PyPI-style indexes; it does not manage the non-Python libraries (CUDA, MKL, GDAL) that conda channels exist to provide. Mixing the two produces an environment neither tool fully understands.

Organisations pinned to an internal index with unusual authentication may hit friction. uv supports index URLs, credentials in the URL, netrc, and keyring, but a bespoke token-refresh scheme or a proxy that rewrites metadata can require work to accommodate. Test uv lock against the real index before committing to the migration, not after.

Finally, the tooling churn is real. uv changes faster than pip or Poetry, and a team that cannot absorb an occasional “upgrade uv and re-lock” chore is better served by something duller. If you do adopt it, pin the version everywhere, treat uv.lock as reviewable output, and read the uv documentation when a release note mentions the resolver.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.