Local development
Complete guide for using pycontainer-build locally during development, including installation, building images, testing, and troubleshooting.
Dependency staging uses a mapped release, explicit base image PYTHON_LIBC,
or effective package metadata from verified official tag-only base layers.
Codename-less automatic/default Python images remain supported when that
evidence is valid. Missing or unsupported evidence fails before pip; then use
--base-image python:3.11-slim-bookworm (or a mapped release for your Python
version) or provide supported base metadata. No libc floor is guessed.
📦 Installation
Section titled “📦 Installation”From Source (Development)
Section titled “From Source (Development)”The recommended way for local development:
# Clone the repositorygit clone https://github.com/spboyer/pycontainer-build.gitcd pycontainer-build
# Create the project environment with locked development toolsuv sync --locked --group test --group buildThis installs the core package in editable mode with locked test and build tools. The core package itself continues to declare no runtime dependencies. Activate the environment for the CLI examples below:
source .venv/bin/activateVerify Installation
Section titled “Verify Installation”# Check that the command is availableuv run --locked --group test --group build pycontainer --help
# Verify the Python API worksuv run --locked --group test --group build python -c "from pycontainer.builder import ImageBuilder; print('Import successful')"🏗️ Building Container Images Locally
Section titled “🏗️ Building Container Images Locally”Basic Build
Section titled “Basic Build”# Build from the current directorypycontainer build --tag myapp:latest
# Build from a specific directorypycontainer build --tag myapp:latest --context /path/to/project
# Build with verbose outputpycontainer build --tag myapp:latest --verboseOutput Location
Section titled “Output Location”By default, images are created at:
<context-path>/dist/image/├── index.json # OCI index (manifest list)├── oci-layout # Version marker├── blobs/sha256/│ ├── <manifest-digest> # Manifest blob│ ├── <config-digest> # Config blob│ ├── <base-layer-digests> # Base image layers (if using --base-image)│ └── <app-layer-digest> # Application layer (tar)└── refs/tags/ └── myapp:latest # Tag referenceWith Base Image & Dependencies
Section titled “With Base Image & Dependencies”# Select a mapped release for dependency stagingpycontainer build \ --tag myapp:latest \ --base-image python:3.11-slim-bookworm \ --include-deps
# Or explicitly specify a base imagepycontainer build \ --tag myapp:latest \ --base-image python:3.12-slim-bookworm \ --include-deps
# Build for different platform (e.g., amd64 from ARM Mac)pycontainer build \ --tag myapp:amd64 \ --base-image python:3.11-slim-bookworm \ --platform linux/amd64 \ --include-deps
# Build for ARM64 (e.g., for AWS Graviton instances)pycontainer build \ --tag myapp:arm64 \ --base-image python:3.11-slim-bookworm \ --platform linux/arm64 \ --include-deps
# This will:# 1. Pull python:3.11-slim-bookworm layers from registry# 2. Package your app files# 3. Include pip-installed dependencies# 4. Combine everything into a complete imageGrouping Locked Dependencies
Section titled “Grouping Locked Dependencies”The single dependency layer is the default. To opt in for a target-selected
uv.lock, assign distribution names explicitly:
pycontainer build --tag myapp:latest --include-deps \ --dependency-layer-strategy explicit \ --stable-dependency numpy --frequent-dependency my-packageAlternatively, use --dependency-layer-strategy history with an optional
--dependency-history-ref REF. The build reports the resolved commit and
classification evidence. Explicit --stable-dependency and
--frequent-dependency options override history; otherwise, absent or changed
target versions are frequent. Each historical lock graph is evaluated with the
target’s markers and selected dependency extras; an unsupported or ambiguous
target graph fails explicitly. History requires Git, a tracked clean lock, a
complete non-shallow/non-partial repository, and at least two distinct lock
snapshots. Ungrouped or shared transitives are frequent in explicit mode.
Only uv.lock is supported for grouping. Requirements, virtualenvs and other
lock formats fail explicitly; they remain available with the default single
layer. A complete group-cache hit avoids pip and package-index requests. A
changed lock stages and verifies the full selection again; an unchanged group
can reuse its cached layer when the full manifest roots are unchanged.
--strip-type-stubs removes typing-only files before grouping, and --squash
can flatten the resulting layers. See the README for TOML
settings and ownership limitations.
Conda Projects
Section titled “Conda Projects”Conda staging is unsupported. Detection checks names only: environment.yml,
environment.yaml, conda-lock.yml, and conda-meta/ directories anywhere in
the selected build context. It does not parse YAML, run Conda, or inspect the
active host environment. Ordinary directories are checked independently of
application include paths; excluded tests, fixtures, generated output/cache
directories, and explicitly excluded descendants do not trigger it.
Conventional virtualenv directories and linked Conda prefixes are checked.
Directory links are otherwise traversed only when selected as application
include roots, matching application file selection.
With --include-deps, detected Conda inputs without a supported selected lock
or pip requirements file raise an explicit error before pulling the base image,
also in dry-run. An explicitly selected or auto-detected supported lock takes
precedence over a virtualenv; otherwise a pip requirements file takes
precedence. A warning explains that Conda inputs are ignored.
--requirements remains relative to the context and can select an exported
file excluded from the application layer. Selecting a Conda YAML file as pip
requirements, including via a file link, is rejected rather than passed to pip.
Selected source paths inside a host Conda prefix are omitted; with
--include-deps they also produce a Conda diagnostic unless the marker is
excluded. Selected lockfiles and requirements inside a host prefix are rejected.
Export the pip-compatible portion from your Conda environment, then build from your application source directory:
python -m pip freeze > requirements.txtpython -m pycontainer.cli build --tag myapp:latest --include-deps --requirements requirements.txtReview the export: remove host-local paths and ensure requirements resolve to
target-compatible wheels. pip freeze is not a conversion of Conda-only
packages or native/system libraries; provide those in a compatible base image.
No YAML resolution or full Conda staging is implemented; that work is tracked
in #187.
Without --include-deps, a source project containing Conda descriptors still
builds application-only, without dependency warnings or installation. Nested
host Conda prefixes (directories containing conda-meta/) are always omitted
from application and virtualenv dependency selection, including explicit
includes and --no-default-excludes. A context that is itself a host Conda
prefix or is inside one is rejected: choose a source-only context instead of
the environment directory. This protects against copying host binaries, not a
guarantee that an application-only image has all dependencies needed to run.
Preview Before Building
Section titled “Preview Before Building”# Dry-run mode - see what will be built without creating filespycontainer build --tag myapp:latest --dry-run --verboseThis shows:
- Detected entry point
- Files that will be included
- Base image layers (if applicable)
- Final image configuration
🧪 Testing Your Builds
Section titled “🧪 Testing Your Builds”Important:
pycontainercreates OCI-compliant image layouts indist/image/. These are not directly runnable by Docker without importing. See the options below for testing your built images.
Option 1: Use Skopeo (Recommended for OCI Layouts)
Section titled “Option 1: Use Skopeo (Recommended for OCI Layouts)”Skopeo is the proper tool for working with OCI image layouts and can copy them directly to Docker:
# Install skopeo# macOS:brew install skopeo
# Ubuntu/Debian:sudo apt-get install skopeo
# Fedora/RHEL:sudo dnf install skopeo
# 1. Build the image with pycontainerpycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-deps
# 2. Copy the OCI layout to Docker daemonskopeo copy oci:dist/image docker-daemon:myapp:latest
# 3. Run the containerdocker run -p 8000:8000 myapp:latest
# Alternative: Copy to a registryskopeo copy oci:dist/image docker://localhost:5000/myapp:latestOption 2: Use Podman (Native OCI Support)
Section titled “Option 2: Use Podman (Native OCI Support)”Podman natively supports OCI layouts without conversion:
# Install Podman# macOS:brew install podmanpodman machine initpodman machine start
# Ubuntu/Debian:sudo apt-get install podman
# Fedora/RHEL (included by default):sudo dnf install podman
# 1. Build with pycontainerpycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-deps
# 2. Run directly from the OCI layoutpodman run --rm -p 8000:8000 oci:dist/image:myapp
# Or import into Podman's local storageskopeo copy oci:dist/image containers-storage:localhost/myapp:latestpodman run -p 8000:8000 localhost/myapp:latestOption 3: Use Docker with Manual Import
Section titled “Option 3: Use Docker with Manual Import”If you only have Docker and can’t install skopeo:
# 1. Build the image with pycontainerpycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-deps
# 2. Create a tar archive and import (less efficient)tar -C dist/image -czf - . | docker import - myapp:latest
# Note: This creates a single-layer image and loses metadata# For proper testing, use skopeo (Option 1) instead
# 3. Run the containerdocker run -p 8000:8000 myapp:latestOption 2: Use Podman
Section titled “Option 2: Use Podman”# Build with pycontainerpycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-deps
# Import into Podmanpodman load -i <(tar -C dist/image -cf - .)
# Run with Podmanpodman run -p 8000:8000 myapp:latestOption 4: Push to Local Registry
Section titled “Option 4: Push to Local Registry”Run a local registry for testing across tools:
# Start a local registry (Docker or Podman required)docker run -d -p 5000:5000 --name registry registry:2# ORpodman run -d -p 5000:5000 --name registry docker.io/library/registry:2
# Build and push to local registrypycontainer build \ --tag localhost:5000/myapp:latest \ --base-image python:3.11-slim-bookworm \ --include-deps \ --push
# Pull and run from local registrydocker pull localhost:5000/myapp:latestdocker run -p 8000:8000 localhost:5000/myapp:latest
# Or with Podman:podman pull localhost:5000/myapp:latestpodman run -p 8000:8000 localhost:5000/myapp:latest
# Clean up when donedocker stop registry && docker rm registry# ORpodman stop registry && podman rm registryOption 5: Test Without Containers
Section titled “Option 5: Test Without Containers”For pure Python testing (no container runtime needed):
# Just run your app directly with Pythoncd /path/to/your/apppip install -r requirements.txtpython -m app # or uvicorn app.main:app, etc.🐳 Understanding OCI vs Docker Images
Section titled “🐳 Understanding OCI vs Docker Images”Key Concept: pycontainer creates OCI image layouts, not Docker-specific images.
| Format | What is it? | Tools that understand it |
|---|---|---|
| OCI Layout | Standard directory structure (dist/image/) |
Podman, skopeo, buildah, containerd |
| Docker Image | Docker daemon’s internal format | Docker only |
| Docker Archive | Tar file with Docker-specific metadata | Docker only |
| OCI Tarball | Tar file with OCI layout | Most tools |
Why this matters:
- Docker requires importing/converting OCI layouts before use
- Podman can use OCI layouts directly
- Skopeo is the bridge between OCI and Docker formats
Best practices:
- Local testing: Use Podman or skopeo for native OCI support
- CI/CD: Push to a registry; most tools pull from registries seamlessly
- Production: Always use registries (GHCR, ACR, Docker Hub, etc.)
🔧 Development Workflow
Section titled “🔧 Development Workflow”Typical Local Development Flow
Section titled “Typical Local Development Flow”# 1. Make code changes to pycontainer-buildvim src/pycontainer/builder.py
# 2. Test with a sample projectcd examples/fastapi-apppycontainer build --tag test:latest --verbose --dry-run
# 3. Build a real imagepycontainer build --tag test:latest --base-image python:3.11-slim-bookworm --include-deps
# 4. Test the imagedocker load -i <(tar -C dist/image -cf - .)docker run -p 8000:8000 test:latestcurl http://localhost:8000
# 5. Iterate - changes to pycontainer source are live (editable install)Quick Iteration with Examples
Section titled “Quick Iteration with Examples”The examples/ directory contains ready-to-use test projects:
# FastAPI examplecd examples/fastapi-apppycontainer build --tag fastapi-test:latest --base-image python:3.11-slim-bookworm --include-deps --verbose
# Test the output structuretree dist/image
# Inspect the manifestcat dist/image/index.json | jq .🎯 Common Local Use Cases
Section titled “🎯 Common Local Use Cases”Python matrix configuration and publication
Section titled “Python matrix configuration and publication”python -m pycontainer.cli build --python-version 3.11,3.12 --default-python-version 3.12 --tag myapp:v1.2.3 --latest --semver-tags --output dist\matrix --dry-runCLI --python-version overrides TOML python_versions (a list of minor-version
strings). --default-python-version overrides default_python_version; when
omitted, the first version receives unsuffixed aliases. --output overrides
output_dir. Each layout is isolated under <output_dir>/pyX.Y, with no
top-level index combining Python versions. The whole output parent is excluded
from application inputs, including sibling version layouts.
[build]tag = "myapp:v1.2.3"python_versions = ["3.11", "3.12"]default_python_version = "3.12"output_dir = "dist/matrix"platform = "linux/amd64,linux/arm64"latest_tag = truesemver_tags = true
[build.python_matrix]"3.11" = "oci:fixtures/python-eleven""3.12" = "registry.example/team/python:twelve"An unpinned official minor tag such as python:3.11-slim can supply the matrix
automatically by rewriting its minor and retaining -slim. All other bases
require the explicit version map. The pulled base metadata, not an application
environment override, must establish the requested PYTHON_VERSION for each
platform; custom bases also provide PYTHON_IMPLEMENTATION=CPython.
With --include-deps, each minor and platform resolves its own lockfile
markers and hash-pinned wheels. Lock staging needs a full base
PYTHON_VERSION such as 3.11.9 and a matching wheel for each selected
package. Digest-pinned and local bases need explicit Python and libc metadata.
Signing, provenance attestation, and build --validate are not supported for
matrices. Unsigned provenance with single dependency layers is written
separately for each version; validate each resulting layout separately with
pycontainer validate image. Grouped dependency layers with provenance are
rejected for matrices. pycontainer preview also requires a single-version
configuration rather than a matrix.
Explicit tags are suffixed -py3.11/-py3.12; unsuffixed tags and generated
semver/latest aliases belong only to the default version. Adding --push
builds and integrity-verifies all layouts first, prepares all remote blobs and
manifests/indexes by digest, then publishes version tags followed by aliases.
Root and per-version output locks are held during the build and verification,
then reacquired for verification and publication.
Failures stop immediately with confirmed/failed/unknown/unattempted operation
reporting, even with --no-progress. Remote tag updates are non-atomic:
previous updates or untagged uploaded content may remain. Ambiguous writes
are unknown, never assumed unchanged. There is no rollback, deletion or
retry-overwrite, which could destroy a concurrent writer’s update.
For Python API callers, ImageBuilder.push(registry_url="mirror.example/team/app:v9")
changes the destination repository and primary tag, returning that normalized
reference. Matrix version tags use v9-pyX.Y; the unsuffixed v9 belongs to
the default version. Configured additional tags and generated aliases are
retained at the destination, as in non-matrix pushes, without regenerating
semver aliases from the override. Local layout tags remain unchanged. Invalid
generated tags or version/alias collisions fail before any remote publication.
Python matrices reject vulnerability scanning and Git-derived tags
(tag_from_git) at configuration and again before build or publication;
set an explicit tag or build each Python version separately.
Hermetic tests do not establish real per-version/per-architecture startup.
Declared build arguments expand once before matrix layouts are derived. Each child preserves literal dollar expressions and the parent’s diagnostic redaction and cache context; version suffixes are applied to the resolved tags.
Use Case 1: Testing Config Changes
Section titled “Use Case 1: Testing Config Changes”# Create a test config filecat > pycontainer.toml << EOF[build]base_image = "python:3.11-slim"workdir = "/app"include_deps = true
[build.env]DEBUG = "true"PORT = "8000"
[build.labels]maintainer = "you@example.com"version = "dev"EOF
# Build with the configpycontainer build --tag myapp:dev --config pycontainer.toml --verbose
# Verify the config was appliedjq '.config' dist/image/blobs/sha256/<config-digest>Use Case 2: Testing Entry Point Detection
Section titled “Use Case 2: Testing Entry Point Detection”# See what entry point is detectedpycontainer build --tag myapp:latest --dry-run --verbose | grep -i "entry"
# Override with explicit entry pointcat > pycontainer.toml << 'EOF'[build]entrypoint = ["python", "-m", "myapp.cli"]EOFpycontainer build --tag myapp:latest --config pycontainer.tomlUse Case 3: Testing SBOM Generation
Section titled “Use Case 3: Testing SBOM Generation”# Generate SPDX SBOMpycontainer build --tag myapp:latest --sbom spdx --verbose
# Check the SBOM was createdls -lh dist/image/sbom.json
# View the SBOMcat dist/image/sbom.json | jq '.packages[].name'Use Case 4: Testing Framework Auto-Detection
Section titled “Use Case 4: Testing Framework Auto-Detection”# FastAPI projectcd examples/fastapi-apppycontainer build --tag test:latest --dry-run --verbose# Should show: "Detected framework: fastapi"
# Flask project (create test)mkdir test-flask && cd test-flaskcat > app.py << 'EOF'from flask import Flaskapp = Flask(__name__)
@app.route('/')def hello(): return 'Hello from Flask!'EOF
echo '[project]\nname="flask-test"\nversion="0.1.0"' > pyproject.toml
pycontainer build --tag flask-test:latest --dry-run --verbose# Should show: "Detected framework: flask"For Celery, Jupyter, Streamlit, and Gradio detection, including precedence, ambiguous entrypoints, and Jupyter authentication, see Framework detection.
Use Case 5: Testing Cache Behavior
Section titled “Use Case 5: Testing Cache Behavior”# First build (cold cache)time pycontainer build --tag myapp:v1 --base-image python:3.11-slim-bookworm --include-deps
# Second build (warm cache - should be faster)time pycontainer build --tag myapp:v2 --base-image python:3.11-slim-bookworm --include-deps
# Check cached blobsls -lh ~/.pycontainer/cache/blobs/sha256/
# Force rebuild without cachepycontainer build --tag myapp:v3 --base-image python:3.11-slim-bookworm --include-deps --no-cacheUse Case 6: Cross-Platform Builds
Section titled “Use Case 6: Cross-Platform Builds”# Build for AMD64 from your ARM Macpycontainer build \ --tag myapp:amd64 \ --platform linux/amd64 \ --base-image python:3.11-slim-bookworm \ --include-deps \ --verbose
# Verify the platform in the image configMANIFEST_DIGEST=$(jq -r '.manifests[0].digest' dist/image/index.json | cut -d: -f2)CONFIG_DIGEST=$(jq -r '.config.digest' dist/image/blobs/sha256/$MANIFEST_DIGEST | cut -d: -f2)jq '.architecture, .os' dist/image/blobs/sha256/$CONFIG_DIGEST# Output: "amd64" "linux"
# Build for ARM64 (AWS Graviton, Raspberry Pi, etc.)pycontainer build \ --tag myapp:arm64 \ --platform linux/arm64 \ --base-image python:3.11-slim-bookworm \ --include-deps
# Build one OCI image index for both platforms and push it under one tagpycontainer build \ --tag ghcr.io/user/myapp:v1 \ --platform linux/amd64,linux/arm64 \ --push
# Add 32-bit ARM (exact arm/v7 variant). With --include-deps, every# requirement needs an armv7l wheel; there is no source-build fallback.pycontainer build \ --tag ghcr.io/user/myapp:v1 \ --platform linux/amd64,linux/arm64,linux/arm/v7 \ --push🔍 Inspecting Built Images
Section titled “🔍 Inspecting Built Images”View Image Manifest
Section titled “View Image Manifest”# Pretty-print the indexjq '.' dist/image/index.json
# Find the manifest digestMANIFEST_DIGEST=$(jq -r '.manifests[0].digest' dist/image/index.json | cut -d: -f2)
# View the manifestjq '.' dist/image/blobs/sha256/$MANIFEST_DIGESTView Image Config
Section titled “View Image Config”# Get config digest from manifestCONFIG_DIGEST=$(jq -r '.config.digest' dist/image/blobs/sha256/$MANIFEST_DIGEST | cut -d: -f2)
# View the configjq '.' dist/image/blobs/sha256/$CONFIG_DIGESTExtract a Layer
Section titled “Extract a Layer”# Get layer digestLAYER_DIGEST=$(jq -r '.layers[0].digest' dist/image/blobs/sha256/$MANIFEST_DIGEST | cut -d: -f2)
# Extract to temporary directorymkdir -p /tmp/layertar -xzf dist/image/blobs/sha256/$LAYER_DIGEST -C /tmp/layer
# View contentstree /tmp/layerCompare With Docker Images
Section titled “Compare With Docker Images”# Build with pycontainerpycontainer build --tag myapp:pycontainer --base-image python:3.11-slim-bookworm --include-deps
# Build equivalent with Dockercat > Dockerfile << EOFFROM python:3.11-slimWORKDIR /appCOPY . .RUN pip install -r requirements.txtCMD ["python", "-m", "app"]EOFdocker build -t myapp:docker .
# Compare sizesdu -sh dist/imagedocker images myapp:docker --format "{{.Size}}"
# Compare manifestsdocker save myapp:docker -o docker-image.tartar -xf docker-image.tarcat manifest.json | jq .🛠️ Debugging & Troubleshooting
Section titled “🛠️ Debugging & Troubleshooting”Enable Verbose Output
Section titled “Enable Verbose Output”# See detailed build progresspycontainer build --tag myapp:latest --verbose
# Outputs:# - Project detection results# - File paths being included# - Layer creation progress# - Registry push details (if --push)# - Cache hits/missesCommon Issues & Solutions
Section titled “Common Issues & Solutions”Issue: “No entry point detected”
Section titled “Issue: “No entry point detected””Solution: Explicitly specify the entrypoint in pycontainer.toml:
[build]entrypoint = ["python", "-m", "myapp"]Then run pycontainer build --tag myapp:latest --config pycontainer.toml.
Issue: “Base image pull failed”
Section titled “Issue: “Base image pull failed””Solution: Check registry authentication:
# For Docker Hubdocker login
# For GHCRecho $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin
# For ACRaz acr login --name myregistry
# Then buildpycontainer build --tag myapp:latest --base-image python:3.11-slimFor offline or air-gapped builds, load the base image from disk instead of a registry; no credentials or daemon are used:
skopeo copy docker://python:3.11-slim oci:./base:3.11-slim # or: docker save python:3.11-slim -o python.tarpycontainer build --tag myapp:latest --base-image oci:./base:3.11-slimpycontainer build --tag myapp:latest --base-image docker-archive:./python.tar:python:3.11-slimFor --include-deps, the local image config must explicitly declare
PYTHON_IMPLEMENTATION=CPython, PYTHON_VERSION, and a supported
PYTHON_LIBC, even when its tag claims an official Python image.
See Local base images for selection rules,
verification, and limitations.
Issue: “Dependencies not found in image”
Section titled “Issue: “Dependencies not found in image””Solution: Ensure --include-deps and dependencies are installed:
# Install dependencies firstpip install -r requirements.txt
# Then build with --include-depspycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-depsIssue: “Permission denied writing to dist/”
Section titled “Issue: “Permission denied writing to dist/””Solution: Check write permissions:
# Check permissionsls -ld dist/
# Fix permissionschmod -R u+w dist/
# Or use a different output directorypycontainer build --tag myapp:latest --output /tmp/myimageIssue: “Cache is stale or corrupted”
Section titled “Issue: “Cache is stale or corrupted””Solution: Clear cache and rebuild:
# Remove cacherm -rf ~/.pycontainer/cache
# Rebuildpycontainer build --tag myapp:latest --no-cacheDebug with Python API
Section titled “Debug with Python API”For deeper debugging, use the Python API:
from pycontainer.config import BuildConfigfrom pycontainer.builder import ImageBuilderimport logging
# Enable debug logginglogging.basicConfig(level=logging.DEBUG)
# Create configconfig = BuildConfig( tag="myapp:debug", context_dir=".", base_image="python:3.11-slim", include_deps=True, verbose=True)
# Build and catch exceptionstry: builder = ImageBuilder(config) builder.build()except Exception as e: print(f"Build failed: {e}") import traceback traceback.print_exc()Measuring Grouped Builds
Section titled “Measuring Grouped Builds”The synthetic benchmark uses local hashed wheels, a loopback package index and a loopback registry. Run it from the repository root:
python benchmarks\run_build_benchmarks.py --grouped-only --repetitions 3 --files 1000 --file-bytes 1024 --output grouped-benchmark.jsonEach cold sample starts with empty local and registry caches. Warm, app-change
and frequent-dependency-change samples each start from a copy of the same
baseline cache and registry blobs. The JSON includes layer digests and sizes,
cache hits, installer and package-index requests, registry HEAD/PUT counts,
received blob bytes, build and layer-upload times, process peak RSS and Python
tracemalloc peak. The operating-system page cache is not controlled; the RSS
measurement is taken after the build, before registry push, and excludes pip
child processes. Upload measurements exclude config, manifest and protocol
bytes. The base image is synthetic: no external registry transfer or container
startup is measured. These observations are not end-to-end performance
claims or timing gates.
📊 Performance Tips
Section titled “📊 Performance Tips”Optimize Build Speed
Section titled “Optimize Build Speed”# 1. Use cache (enabled by default)pycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-deps
# 2. Use smaller base imagespycontainer build --tag myapp:latest --base-image python:3.11-alpine3.20 --include-deps
# 3. Include only necessary filespycontainer build \ --tag myapp:latest \ --include src/ \ --include pyproject.toml \ --include requirements.txtReduce Image Size
Section titled “Reduce Image Size”# Use distroless for smaller imagespycontainer build --tag myapp:latest --base-image gcr.io/distroless/python3-debian11
# Or use Alpinepycontainer build --tag myapp:latest --base-image python:3.11-alpine
# Don't include unnecessary dependenciespip install --no-dev -r requirements.txtpycontainer build --tag myapp:latest --base-image python:3.11-slim-bookworm --include-deps🔗 Integration with Local Tools
Section titled “🔗 Integration with Local Tools”Using with VS Code
Section titled “Using with VS Code”# 1. Install the VS Code extensioncode --install-extension ms-python.pycontainer
# 2. Open your project in VS Codecode /path/to/project
# 3. Use Command Palette (Cmd+Shift+P):# - "pycontainer: Build Container Image"# - "pycontainer: Build and Push Container Image"Using with Poetry
Section titled “Using with Poetry”Follow the Poetry plugin guide to install from this repository checkout.
# Build containercd /path/to/poetry/projectpoetry build-container --tag myapp:latest
# Configuration via pyproject.toml[tool.pycontainer]base_image = "python:3.11-slim"include_deps = truepush = falseUsing with Hatch
Section titled “Using with Hatch”Follow the Hatch plugin guide to install from this repository checkout.
# Build (creates both wheel and container)cd /path/to/hatch/projecthatch build
# Configuration via pyproject.toml[tool.hatch.build.hooks.pycontainer]base_image = "python:3.11-slim"include_deps = true📝 Example Projects
Section titled “📝 Example Projects”Try these ready-made examples:
FastAPI Application
Section titled “FastAPI Application”cd examples/fastapi-app
# Quick buildpycontainer build --tag fastapi-demo:latest --base-image python:3.11-slim-bookworm --include-deps --verbose
# Test locallydocker load -i <(tar -C dist/image -cf - .)docker run -p 8000:8000 fastapi-demo:latestcurl http://localhost:8000Minimal Test App
Section titled “Minimal Test App”# Create a minimal testmkdir minimal-test && cd minimal-test
cat > app.py << 'EOF'print("Hello from pycontainer!")EOF
cat > pyproject.toml << 'EOF'[project]name = "minimal-test"version = "0.1.0"EOF
# Buildpycontainer build --tag minimal:latest --verbose
# Inspecttree dist/image🚀 Next Steps
Section titled “🚀 Next Steps”- Deploy to Azure: See Azure Developer CLI Guide
- Set up CI/CD: See GitHub Actions Guide
- Explore Plugins: Check plugins/
- Read Architecture: See images and dependencies
💡 Tips & Best Practices
Section titled “💡 Tips & Best Practices”- Always use
--verboseduring development to understand what’s happening - Use
--dry-runto preview builds before creating artifacts - Test with multiple base images (slim, alpine, distroless) to find the best fit
- Keep
pycontainer.tomlin your project for consistent builds - Use cache for faster iterations (don’t disable unless debugging cache issues)
- Version your images with meaningful tags (not just
latest) - Generate SBOMs for security compliance (
--sbom spdx) - Use reproducible builds for consistent outputs (
--reproducible, enabled by default)
🆘 Getting Help
Section titled “🆘 Getting Help”- GitHub Issues: spboyer/pycontainer-build
- Documentation: See other files in docs/
- Examples: Check examples/
- Architecture: Read images and dependencies
Happy building! 🐍🐳