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.txtor Poetry dependency list into apyproject.tomlplus a committeduv.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.lockno longer matchespyproject.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 | shpipx install uv==0.8.4works too, as do Homebrew (brew install uv) and a handful of distro packages. Avoidpip install uvinto 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.txtfiles or apyproject.tomlwritten 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 lockwhen 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.
Step-by-step
-
Confirm which uv you are running. Version skew between your laptop and CI is the most common source of unexpected lockfile churn.
uv --versionuv 0.8.4If 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.
-
Start fresh, or adopt in place. For a brand-new project,
uv initscaffoldspyproject.toml, a.python-versionfile, aREADME.md, and a source stub:uv init --python 3.12 billing-apiInitialized project `billing-api` at `/home/deploy/billing-api`For an existing repository you almost never want the scaffold. Run
uv initinside the directory only if there is nopyproject.tomlyet, and add--bareif you want the metadata without the sample files. If a Poetry-erapyproject.tomlalready 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. -
Import an existing requirements.txt.
uv addaccepts a requirements file and writes each entry into[project.dependencies], resolving as it goes:uv add -r requirements.txtResolved 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.9Two judgement calls here. If your
requirements.txtwas fully pinned (django==5.1.2), those hard pins land inpyproject.tomland you lose patch updates — relax them to ranges by hand afterwards. And if the file was generated bypip-compile, importrequirements.ininstead, 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.0means>=5.0,<6:uv add 'django>=5.0,<6' 'httpx>=0.27' 'psycopg[binary]>=3.2' gunicornResolved 48 packages in 46ms Audited 46 packages in 0.19ms -
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 mypyResolved 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.5Check
pyproject.tomlafterwards — you should see a[dependency-groups]table with adevlist. That is the standard group mechanism, anduv sync --no-devis what excludes it later. -
Lock, and read the diff.
uv lockwritesuv.lockfrompyproject.tomlwithout touching.venv:uv lock git diff --stat uv.lockResolved 61 packages in 128ms uv.lock | 1247 ++++++++++++++++++++++++++++++++++Open the file once so it stops being mysterious. Each package is a
[[package]]block withname,version, asource, adependencieslist, andwheels/sdistentries carryinghash = "sha256:...". To move a single package later, useuv 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. -
Understand the difference between
uv syncanduv sync --frozen. On a laptop, plain sync is what you want: it re-locks ifpyproject.tomlchanged, then makes.venvmatch.uv syncResolved 61 packages in 3ms Audited 59 packages in 0.21msIn any automated context, use
--frozen. It installs fromuv.lockas-is and never re-resolves, so a dependency published five minutes ago cannot change what you deploy:rm -rf .venv && uv sync --frozenUsing CPython 3.12.9 Creating virtual environment at: .venv Prepared 59 packages in 1.42s Installed 59 packages in 94msThere 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--frozenfor the install gives the clearest failure messages. -
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.12sWithout
--frozen(or--no-sync),uv runwill sync first and may update the lockfile. That is convenient interactively and wrong in CI, so make the flag part of the CI command. -
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-versionPinned `.python-version` to `3.12` 3.12Commit
.python-version. From then onuv syncanduv runselect 3.12, downloading a managed CPython if the host has none. Keeprequires-python = ">=3.12"inpyproject.tomlconsistent with it — the pin selects an interpreter, the constraint bounds the resolution. -
Fail CI when the lockfile is stale. This is the single most valuable step in the whole migration.
uv lock --checkverifies thatuv.lockis whatpyproject.tomlwould produce, and exits non-zero otherwise:uv lock --checkerror: 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 -qRun uv lock --check Resolved 61 packages in 96msIf you would rather not depend on the action,
curl -LsSf https://astral.sh/uv/0.8.4/install.sh | shin a plainrun:step does the same job with the version equally pinned. -
Build the image in two stages. Copy only
pyproject.tomlanduv.lockfirst 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.3sThree details earn their keep.
--no-install-projectin the first sync installs dependencies only, so editing your own source does not invalidate the layer.UV_LINK_MODE=copystops uv warning that it cannot hardlink across the cache mount.UV_PYTHON_DOWNLOADS=nevermakes the build fail loudly if the base image’s interpreter does not satisfyrequires-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
-
--frozeninstalls an old set, or--lockederrors out after apyproject.tomledit. Somebody changed a declared range without re-locking. Runuv lock, commit the result, and add theuv lock --checkstep from step 9 so the next occurrence is caught in the pull request rather than in a deploy. A stale lock plus--frozenis 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
Xmatches” and the range looks fine. Usuallyrequires-pythonis too wide. If you declare>=3.9but 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-slimdoes not ship. Either install it in the builder stage —apt-get install -y --no-install-recommends build-essential libpq-devbefore the sync — or switch to a variant that publishes wheels (psycopg[binary]instead ofpsycopg). Keep the tooling in the builder stage only, so the runtime image stays small. -
The copied
.venvfails at runtime with a missing shared object or a bad interpreter path. A virtualenv contains absolute paths and platform-specific binaries. Copying.venvfrom a builder into a runtime stage works only when both stages use the same base image, the same architecture, and the same/apppath. Building on an arm64 laptop for an amd64 host without--platform linux/amd64is the usual cause. When in doubt, runuv sync --frozen --no-devin 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". Settingprerelease = "allow"under[tool.uv]for the whole project means every futureuv lockmay 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.