uv in a Multi-Stage Build Must Use the Image's Python or the Copied venv Breaks
A virtual environment doesn't contain Python; it contains symlinks to the interpreter that created it. In a multi-stage Dockerfile, if uv downloads its own managed Python in the builder stage (under /root/.local/share/uv/python/), the .venv points there. The runtime stage copies only /app, so the links dangle and the container dies at start with a misleading "no such file or directory" for a file that is right there.
The Failure
exec /app/.venv/bin/uvicorn: no such file or directory
/app/.venv/bin/uvicorn exists; its first line points to /app/.venv/bin/python, a symlink to an interpreter that was never copied into the final image. The kernel reports the missing interpreter as the script being missing.
The Fix: Only the System Python
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:0.5 /uv /bin/uv
ENV UV_PYTHON_PREFERENCE=only-system
WORKDIR /app
COPY pyproject.toml uv.lock .python-version ./
RUN uv sync --frozen --no-dev
FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /app /app
CMD ["/app/.venv/bin/uvicorn", "main:app", "--host", "0.0.0.0"]
With UV_PYTHON_PREFERENCE=only-system uv never downloads an interpreter; the venv links to /usr/local/bin/python, which exists at the same path in both stages because both use the same base image.
Same Symptom, Second Cause
A host .venv copied into the image by COPY . . (built for macOS, or with host paths) produces the same error. Exclude .venv, caches and local databases in .dockerignore, as described in Docker Build Context Isolation and Bind-Mount Masking. If a remote server already has a polluted .venv in the build folder, delete it and rebuild with --no-cache.
References
- Docker and Container Security MOC - hub for Docker notes.
- Start a FastAPI Project with uv - the project layout being containerised.
- uv documentation: Using uv in Docker - multi-stage builds and managed Python.
- uv documentation: Environment variables -
UV_PYTHON_PREFERENCE.
Review cards
Flashcard Why does exec /app/.venv/bin/uvicorn: no such file or directory appear when the file exists?
Its interpreter, .venv/bin/python, is a symlink to a Python that wasn't copied into the final image. The kernel reports the missing interpreter as the script being missing.
Quiz Which of the following is a correct way to ensure the virtual environment links to the system's Python interpreter in a multi-stage Dockerfile?
- Set
UV_PYTHON_PREFERENCE=only-systemin the builder stage. - Download a managed Python interpreter in the builder stage.
- Copy the entire virtual environment from the builder stage to the runtime stage.
- Use a different base image in the runtime stage.
Setting UV_PYTHON_PREFERENCE=only-system ensures that the virtual environment links to the system's Python interpreter, which is the same in both stages.