Microsoft Dev Blogs

Dockerizing UV

thumbnail

Best Practices for Dockerizing UV

A multi-stage Docker build is recommended for UV to optimize the Dockerization process. Here are key strategies to follow:

  1. Use Multi-stage Builds: Divide the build process into stages. In the first stage, install UV and Python dependencies. In the final stage, copy only the necessary artifacts.

  2. Leverage Primary Dependency Files: Copy core dependency files (e.g., pyproject.toml, uv.lock) into the image for efficient layer caching and dependency management.

  3. Minimize Final Image Size: Use a slim Python base image in the final stage, copying only essential components like the virtual environment and app code.

Example Dockerfile Configuration

# Base Stage
FROM python:3.9 as base
RUN pip install uv

# Development Stage
FROM base as development
COPY sync_script.sh /
RUN /sync_script.sh

# Release Stage
FROM base as release
RUN pip install -r requirements.txt

# Service Stage
FROM python:3.9-slim
COPY --from=release /usr/local/lib/python3.9/site-packages/ /usr/local/lib/python3.9/site-packages/
COPY --from=release /app /app

Common Challenges and Solutions

  • "No virtual environment found" error: Create a virtual environment in the container before installing dependencies or use the -B flag to bypass.
  • Virtual environment activation in the container: Update environment variables like PATH to ensure the virtual environment's paths are active at runtime.

By implementing these best practices, you can effectively Dockerize UV and overcome common challenges for containerized projects.