Python with uv
Best practices for Dockerfile for Python with uv
🐳 Annotated Dockerfile for Python with uv:
🔍 Why these are best practices
✅ Slim Base Images (python:3.12-slim-bookworm)
- Minimizes image size, enhancing security and reducing container startup time.
- Debian Bookworm provides modern dependencies with stable long-term support.
✅ Using uv (Ultra-fast Python package manager)
- Faster and more efficient than traditional pip.
- Built-in dependency caching significantly improves build speeds.
- Ensures reproducible builds through lock files (uv.lock), avoiding dependency drift.
✅ Multi-stage Builds
- Keeps final image minimal by excluding build-time artifacts (e.g., cache files, temporary dependencies).
- Reduces production container size, resulting in lower resource usage and faster deployments.
✅ Dependency and Source Separation
- Copying dependency-related files separately allows Docker to reuse cached layers effectively.
- Changes in source code don’t trigger unnecessary reinstallations of unchanged dependencies.
✅ Mounting Cache (--mount=type=cache)
- Dramatically reduces build time in CI/CD environments by reusing cached downloads and installed packages.
✅ Environment Variables
- UV_COMPILE_BYTECODE=1 compiles bytecode, which optimizes startup times in production.
- UV_LINK_MODE=copy isolates dependencies clearly, simplifying management and ensuring immutability.
🚀 Additional best practices to consider
Run as a Non-root User
For enhanced security, switch to a non-root user in your production container.
Add Health Checks
Integrate Docker’s built-in health monitoring to enable auto-recovery mechanisms.
Use .dockerignore file
Avoid accidentally copying unwanted files (e.g., logs, .git, test folders):
Explicit Resource Limits
Set CPU and memory limits explicitly when running containers (via Kubernetes, Docker Compose, or runtime flags).
Example (Docker Compose):
By following these annotations and additional best practices, you’ll achieve containers that are fast to build, secure, easy to maintain, and optimized for production environments.
Last updated on