Currently viewing the AI version
Switch to human version

uv Docker Production: AI-Optimized Technical Reference

Configuration - Critical Environment Variables

Required Docker Environment Variables:

ENV UV_LINK_MODE=copy \
    UV_COMPILE_BYTECODE=1 \
    UV_PYTHON_DOWNLOADS=never \
    UV_PYTHON=python3.12 \
    UV_PROJECT_ENVIRONMENT=/app \
    UV_CACHE_DIR=/tmp/uv-cache

Critical Failure Mode: UV_LINK_MODE=copy is mandatory - Docker filesystems don't support hard links, causing silent failures without this setting.

Performance Impact: UV_COMPILE_BYTECODE=1 provides noticeably faster startup times in production containers.

Performance Benchmarks

Metric pip + venv Poetry uv
First Build Time 8-12 minutes 6-10 minutes 2-4 minutes
Cached Build Time 3-5 minutes 2-4 minutes 15-45 seconds
Final Image Size 450-600 MB 500-700 MB 200-350 MB
Memory Usage (Build) 1-2 GB 1.5-3 GB 1-2 GB

Real-world Impact: Production builds reduced from 12+ minutes to 3 minutes with proper Docker layer caching.

Resource Requirements

Minimum Memory Limits:

  • Build containers: 2GB minimum (prevents OOM kills during parallel dependency resolution)
  • Production runtime: Standard Python memory requirements

Memory Spike Mitigation:

ENV UV_CONCURRENT_DOWNLOADS=1
ENV UV_RESOLUTION_MEMORY_LIMIT=1GB

Cache Performance Requirements:

  • Cache mount location must exist: --mount=type=cache,target=/root/.cache/uv
  • Cache mount reduces build time from 8 minutes to 2 minutes after first build

Critical Warnings - Production Failure Modes

Build Context Failures

Symptom: "COPY failed: no such file or directory"
Root Cause: uv.lock or pyproject.toml not in Docker build context
Solution: Move Dockerfile to project root OR configure .dockerignore correctly

Permission Denied Errors

Symptom: "PermissionError: [Errno 13] Permission denied" during uv sync
Root Causes:

  1. Build stage runs as root, runtime as non-root user
  2. System Python packages directory is read-only

Solutions:

  • Use COPY --chown=user:user /app /app for proper ownership
  • Set UV_PROJECT_ENVIRONMENT=/app for writable location

Memory-Related Build Failures

Symptom: OOMKilled during dependency installation
Root Cause: uv's parallel dependency resolution spikes memory usage in containerized environments
Frequency: Common in containers with memory limits under 2GB

Alpine Linux Compatibility Issues

Critical Warning: Don't use Alpine for Python applications
Impact: musl libc causes compatibility issues with many Python packages
Time Cost: Can require 3+ days debugging numpy imports and compilation issues
Alternative: Use debian-slim or ubuntu (50MB size difference is not worth compatibility problems)

Multi-Stage Build Pattern - Production Template

Dependency Installation Order (Critical for Caching):

  1. Copy ONLY uv.lock and pyproject.toml
  2. Run uv sync (this layer caches until lock file changes)
  3. Copy application source code

Failure Mode: If source code is copied first, every code change invalidates dependency cache.

# Stage 1: Dependencies only
FROM python:3.12-slim AS deps
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv

ENV UV_LINK_MODE=copy UV_COMPILE_BYTECODE=1 UV_PYTHON_DOWNLOADS=never

WORKDIR /app
RUN --mount=type=cache,target=/root/.cache \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-dev --no-install-project

# Stage 2: Application code
COPY . /src
WORKDIR /src
RUN --mount=type=cache,target=/root/.cache \
    uv sync --locked --no-dev --no-editable

# Stage 3: Production runtime
FROM python:3.12-slim
COPY --from=deps /app /app
ENV PATH=/app/bin:$PATH
USER 1001
WORKDIR /app

Common Production Failures - Troubleshooting Guide

"uv command not found" in runtime

Cause: uv copied to build stage but not runtime stage
Solution: Don't copy uv to runtime - only copy built virtual environment

"Package not found" for existing packages

Causes:

  • Private PyPI authentication not configured in container
  • Corporate proxy/SSL certificate issues
  • Network timeout in restrictive environments

Solutions:

ENV REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
ENV UV_HTTP_TIMEOUT=300
ENV UV_EXTRA_INDEX_URL=https://your-private-pypi.com/simple/

Build Cache Not Working

Symptom: Rebuilds all dependencies on every code change
Root Cause: Incorrect layer ordering in Dockerfile
Impact: Increases build time from 45 seconds to 3+ minutes

Container Size Bloat (2GB+ images)

Causes:

  • Build tools included in runtime image
  • Copying unnecessary files (.git, pycache)
  • Not using multi-stage builds properly

Solutions:

  • Use .dockerignore to exclude development files
  • Runtime stage should only include Python runtime and dependencies
  • Multi-stage builds can reduce image size by 70-90%

Security Configuration

Non-root Execution Pattern:

RUN groupadd -r appuser && useradd -r -g appuser appuser
COPY --from=build --chown=appuser:appuser /app /app
USER appuser

Secret Management (Private Repositories):

RUN --mount=type=secret,id=pip_index_url \
    UV_EXTRA_INDEX_URL=$(cat /run/secrets/pip_index_url) \
    uv sync --locked

Critical Security Warning: Never put authentication tokens directly in Dockerfile - they persist in image layers permanently.

CI/CD Integration Requirements

Cache Strategy for GitHub Actions:

cache-from: type=gha
cache-to: type=gha,mode=max

Container Testing (Essential):

  • Always test container actually starts and imports work
  • Include smoke tests to catch 90% of container issues before deployment
  • Monitor cold start times and memory usage patterns

Build Dependencies for CI:

RUN apt-get update && apt-get install -y \
    build-essential \
    python3.X-dev \
    libffi-dev \
    libssl-dev

Monitoring and Operational Intelligence

Expected Container Metrics:

  • Production containers: ~200MB (if significantly larger, build tools included in runtime)
  • Cold start time: Noticeably faster with UV_COMPILE_BYTECODE=1
  • Memory usage: Lower than pip equivalents due to better dependency resolution

Disk Space Management:

  • uv cache can grow large in production environments
  • Monitor and periodically clean /tmp/uv-cache
  • Corporate networks may require increased timeout settings

Health Check Pattern:

HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import your_app; print('OK')" || exit 1

Decision Support Information

When to Use uv in Docker:

  • Build time reduction from 12+ minutes to 3 minutes justifies adoption
  • Deterministic dependency resolution improves Docker layer caching effectiveness
  • Worth migration cost despite initial configuration complexity

Trade-offs:

  • Benefit: Significantly faster builds and smaller images
  • Cost: Initial learning curve for Docker-specific configuration
  • Hidden Cost: Debugging containerization issues requires understanding uv-specific behaviors

Migration Difficulty: Easier than Poetry containerization, harder than simple pip requirements.txt

Prerequisites:

  • Understanding of multi-stage Docker builds
  • Knowledge of Docker layer caching strategies
  • Experience with Python virtual environments in containers

Useful Links for Further Investigation

Docker and Container Resources

LinkDescription
uv Docker GuideThis official guide from uv provides comprehensive documentation on how to effectively containerize your uv projects using Docker, covering best practices and setup.
uv Environment VariablesA comprehensive reference detailing all available environment variables for uv, providing complete configuration options for various operational settings and behaviors.
uv Project ConfigurationDocumentation outlining the recommended project structure and best practices for managing uv projects, including how to configure dependencies and settings.
uv Lock FilesAn essential guide to understanding uv's dependency resolution mechanism and the role of lock files in ensuring consistent and reproducible builds across environments.
Hynek's Production Docker GuideHynek's insightful guide offers real-world production patterns and practical troubleshooting tips for deploying uv applications within Docker containers, based on extensive experience.
uv Docker Examples RepositoryThis GitHub repository provides a complete, ready-to-use production Docker setup for uv, including a practical FastAPI example to demonstrate integration and deployment.
Django + uv Setup DiscussionA community discussion thread on GitHub exploring various integration patterns and best practices for setting up Django projects with uv, offering diverse perspectives.
Docker BuildKit DocumentationOfficial documentation for Docker BuildKit, detailing advanced build features, efficient cache mounts, and other optimizations to accelerate and improve container image creation.
Multi-stage Build Best PracticesDocker's official guidance on implementing multi-stage builds, a crucial best practice for creating smaller, more secure, and efficient container images for production.
Dockerfile Linter (hadolint)The hadolint tool is a static analysis linter for Dockerfiles, designed to help developers enforce best practices and identify common issues in their Docker configurations.
Container Structure TestsA tool from GoogleContainerTools for validating the structure and contents of container images, ensuring they meet specified requirements and configurations before deployment.
uv GitHub Issues - Docker LabelA filtered view of uv's GitHub issues, specifically showing discussions and solutions related to Docker-specific problems, offering insights into common challenges.
Docker Logs and Debugging GuideDocker's official guide covering the fundamentals of container logging and debugging, providing essential techniques and tools for diagnosing issues within your Dockerized applications.
Python in Docker Best PracticesA comprehensive resource detailing best practices for running Python applications efficiently and securely within Docker containers, covering performance, size, and security.
Alpine Linux Issues with PythonAn article explaining the common issues and challenges encountered when using Alpine Linux as a base image for Python applications in Docker, and how to mitigate them.
GitHub Actions Docker BuildxThe official GitHub Action for building and pushing Docker images using Buildx, enabling multi-platform builds and advanced caching within your CI/CD pipelines.
GitLab CI Docker IntegrationDocumentation on integrating Docker into GitLab CI/CD pipelines, providing guidance on how to build, test, and deploy containerized applications using GitLab's features.
Jenkins Docker PipelineOfficial Jenkins documentation detailing various container integration patterns for Jenkins Pipelines, including how to leverage Docker for building and running jobs effectively.
uv in GitHub ActionsOfficial guidance from uv on integrating it into GitHub Actions workflows, providing steps and examples for efficient CI/CD setups for your Python projects.
Docker Stats and MonitoringDocumentation on using Docker's built-in `docker stats` command and other tools for monitoring container resource usage, including CPU, memory, and network I/O.
Prometheus Container MonitoringA guide to setting up Prometheus for production-grade container monitoring, specifically using cAdvisor to collect and visualize metrics from your Docker containers.
Container Image ScanningDocumentation on Docker Scout, a tool for scanning container images for security vulnerabilities and providing insights into their composition and potential risks.
Python Application PerformanceA collection of articles and resources focused on Python-specific performance optimization techniques, offering practical advice for making your Python applications faster and more efficient.
Docker Security Best PracticesThe OWASP Docker Security Cheat Sheet provides a comprehensive guide to best practices for securing Docker containers and applications, mitigating common vulnerabilities.
Distroless Python ImagesGoogleContainerTools' Distroless images offer minimal, secure base images for containerized applications, significantly reducing attack surface by including only necessary runtime dependencies.
Container Runtime SecurityDocumentation on Kubernetes Pod Security Standards, outlining best practices and policies for ensuring robust runtime security for containers deployed within a Kubernetes cluster.
Secret Management in ContainersDocker's official documentation on secure secret management within containers, providing methods and best practices for handling sensitive information like API keys and passwords.

Related Tools & Recommendations

review
Recommended

I've Been Testing uv vs pip vs Poetry - Here's What Actually Happens

TL;DR: uv is fast as fuck, Poetry's great for packages, pip still sucks

uv
/review/uv-vs-pip-vs-poetry/performance-analysis
100%
integration
Recommended

GitHub Actions + Docker + ECS: Stop SSH-ing Into Servers Like It's 2015

Deploy your app without losing your mind or your weekend

GitHub Actions
/integration/github-actions-docker-aws-ecs/ci-cd-pipeline-automation
96%
compare
Recommended

Uv vs Pip vs Poetry vs Pipenv - Which One Won't Make You Hate Your Life

I spent 6 months dealing with all four of these tools. Here's which ones actually work.

Uv
/compare/uv-pip-poetry-pipenv/performance-comparison
95%
tool
Recommended

pyenv-virtualenv - Stops Python Environment Hell

similar to pyenv-virtualenv

pyenv-virtualenv
/tool/pyenv-virtualenv/overview
73%
tool
Recommended

Kubeflow Pipelines - When You Need ML on Kubernetes and Hate Yourself

Turns your Python ML code into YAML nightmares, but at least containers don't conflict anymore. Kubernetes expertise required or you're fucked.

Kubeflow Pipelines
/tool/kubeflow-pipelines/workflow-orchestration
59%
tool
Recommended

Poetry - Python Dependency Manager That Doesn't Suck

competes with Poetry

Poetry
/tool/poetry/overview
54%
tool
Recommended

Python Dependency Hell - Now With Extra Steps

pip installs random shit, virtualenv breaks randomly, requirements.txt lies to you. Pipenv combines all three tools into one slower tool.

Pipenv
/tool/pipenv/overview
54%
alternatives
Recommended

Docker Alternatives That Won't Break Your Budget

Docker got expensive as hell. Here's how to escape without breaking everything.

Docker
/alternatives/docker/budget-friendly-alternatives
49%
integration
Recommended

GitOps Integration Hell: Docker + Kubernetes + ArgoCD + Prometheus

How to Wire Together the Modern DevOps Stack Without Losing Your Sanity

docker
/integration/docker-kubernetes-argocd-prometheus/gitops-workflow-integration
49%
compare
Recommended

I Tested 5 Container Security Scanners in CI/CD - Here's What Actually Works

Trivy, Docker Scout, Snyk Container, Grype, and Clair - which one won't make you want to quit DevOps

docker
/compare/docker-security/cicd-integration/docker-security-cicd-integration
49%
tool
Recommended

GitHub Actions Marketplace - Where CI/CD Actually Gets Easier

integrates with GitHub Actions Marketplace

GitHub Actions Marketplace
/tool/github-actions-marketplace/overview
49%
alternatives
Recommended

GitHub Actions Alternatives That Don't Suck

integrates with GitHub Actions

GitHub Actions
/alternatives/github-actions/use-case-driven-selection
49%
news
Popular choice

Google Pixel 10 Phones Launch with Triple Cameras and Tensor G5

Google unveils 10th-generation Pixel lineup including Pro XL model and foldable, hitting retail stores August 28 - August 23, 2025

General Technology News
/news/2025-08-23/google-pixel-10-launch
47%
news
Popular choice

Dutch Axelera AI Seeks €150M+ as Europe Bets on Chip Sovereignty

Axelera AI - Edge AI Processing Solutions

GitHub Copilot
/news/2025-08-23/axelera-ai-funding
45%
tool
Recommended

GitLab CI/CD - The Platform That Does Everything (Usually)

CI/CD, security scanning, and project management in one place - when it works, it's great

GitLab CI/CD
/tool/gitlab-ci-cd/overview
45%
tool
Recommended

JupyterLab Debugging Guide - Fix the Shit That Always Breaks

When your kernels die and your notebooks won't cooperate, here's what actually works

JupyterLab
/tool/jupyter-lab/debugging-guide
45%
tool
Recommended

JupyterLab Team Collaboration: Why It Breaks and How to Actually Fix It

integrates with JupyterLab

JupyterLab
/tool/jupyter-lab/team-collaboration-deployment
45%
tool
Recommended

JupyterLab Extension Development - Build Extensions That Don't Suck

Stop wrestling with broken tools and build something that actually works for your workflow

JupyterLab
/tool/jupyter-lab/extension-development-guide
45%
alternatives
Recommended

Lambda Alternatives That Won't Bankrupt You

integrates with AWS Lambda

AWS Lambda
/alternatives/aws-lambda/cost-performance-breakdown
45%
troubleshoot
Recommended

Stop Your Lambda Functions From Sucking: A Guide to Not Getting Paged at 3am

Because nothing ruins your weekend like Java functions taking 8 seconds to respond while your CEO refreshes the dashboard wondering why the API is broken. Here'

AWS Lambda
/troubleshoot/aws-lambda-cold-start-performance/cold-start-optimization-guide
45%

Recommendations combine user behavior, content similarity, research intelligence, and SEO optimization