Configuration
Auto-Detection (Zero Config)
Section titled “Auto-Detection (Zero Config)”By default, pycontainer auto-detects:
- Base image: Python version from
requires-pythoninpyproject.toml(e.g.,>=3.11→python:3.11-slim) - Entry point: A detected framework, then a supported project script module or
python -m app. A configuredcmdwithout anentrypointkeeps the base image’sEntrypoint; explicitentrypoint = []andcmd = []clear the corresponding base values. - Include paths:
src/,app/,package/, root Python files, and project metadata; notebook files are included when Jupyter is declared - Working directory:
/app/ - Architecture:
amd64/linux
Framework detection documents commands, precedence, ambiguous projects, explicit overrides, and Jupyter authentication. Detection priority is FastAPI, Flask, Django, Streamlit, Gradio, Jupyter, then Celery; Celery defaults to a worker with no exposed ports. Detection does not install dependencies or execute application code. For a root image user, the generated Jupyter command permits root; prefer a non-root user.
Explicit Configuration
Section titled “Explicit Configuration”# Full configuration with all optionspycontainer build \ --tag myapp:v1.2.3 \ --context /my/project \ --base-image python:3.11-slim-bookworm \ --include-deps \ --workdir /app \ --env KEY=value \ --env ANOTHER=value \ --platform linux/amd64 \ --sbom cyclonedx \ --config pycontainer.toml \ --verbose \ --push \ --no-cache
# Build for ARM64 (e.g., for AWS Graviton, Apple Silicon containers)pycontainer build \ --tag myapp:arm64 \ --platform linux/arm64 \ --pushBase Image & Dependencies:
-
--base-image IMAGE— Base image to build on (auto-detected fromrequires-pythonif not specified, e.g.,python:3.11-slim). Local, daemon-free sources are also accepted; see Local base images. -
--include-deps— Stage importable dependencies from a lockfile or requirements file as target-compatible binary wheels, or copy a verified pure-Python venv. Requirements files, including generated lock selections, are limited to 1 MiB; staging is limited to 300 seconds, 512 MiB, and 100,000 files; supported targets arelinux/amd64,linux/arm64andlinux/arm/v7with CPython (linux/arm/v7usesarmv7lwheel tags;linux/armwithout thev7variant is rejected). A venv must match the target Python minor version and contain only pure-Python packages. Dependencies are placed under<workdir>/.python, added toPYTHONPATH, and their console entrypoints are added toPATH; the Python interpreter running pycontainer must havepipavailable. Source distributions and cross-compilation are not supported. Pip runs without the host’sPYTHONPATH, and pip configuration cannot disable targetRequires-Pythonchecks. Generated Linux console scripts use UTF-8 and LF line endings on every host, including Windows, and retain executable mode in the dependency layer. Copied application files are not normalized. Custom base images must setPYTHON_IMPLEMENTATION=CPython,PYTHON_VERSION, andPYTHON_LIBC=glibc-2.N(N 17-99) orPYTHON_LIBC=musl-1.N(N 1-99) in their image config so wheel tags can be validated. pip receives tags through the selected libc bound, newest first:manylinux_2_Ndown tomanylinux_2_17plus themanylinux2014alias for glibc, ormusllinux_1_Ndown tomusllinux_1_1for musl. Officialpythontag-only registry pulls derive libc from the resolved tag (alpinetags use musl, others glibc). A codename token in such a tag raises the libc version to a conservative bound for that release:Tag codename Target libc jessie/stretch/busterglibc 2.17 / 2.19 / 2.24 bullseye/bookworm/trixieglibc 2.28 / 2.31 / 2.36 alpine3.0-alpine3.12musl 1.1 alpine3.13-alpine3.24musl 1.2 Each row is pinned to immutable sources (content-addressed Debian snapshots, official image declarations and Alpine
aportscommits) in docs/libc-codename-mappings.md. These bounds may reject wheels that a newer image could actually run.Codename-less tags such as
python:3.11-slimorpython:3.11-alpine, and unmapped releases, cannot establish a libc floor from their names: officialpython:3.8.0-alpineuses musl 1.1 andpython:3.4-wheezyuses glibc 2.13, so the previousmusllinux_1_2/manylinux2014fallbacks were unsafe. For verified official tag-only pulls, the builder instead reads the effectivelibc6/muslpackage record from digest-checked base layers. It applies whiteouts and rejects missing, linked, ambiguous, unsupported or wrong-architecture records. A foreign-database root link such as Debian’slib -> usr/libis allowed only when its redirected database has no conflicting evidence; other foreign links and links on the active database path fail closed. Inspection is bounded (8 MiB metadata, 2 GiB decoded bytes and 100,000 members per layer, 300 seconds overall) and never extracts base files. Thus the CLI’s automatic selection,BuildConfig’spython:3.11-slimdefault, and Aspire’spython:3.12-slim --include-depsinvocation remain supported when the pulled image supplies valid package evidence. If evidence is unavailable, explicitly select a mapped release, for example--base-image python:3.11-slim-bookworm, or provide supported libc metadata in the base image config. Application--envvalues are not base metadata. InferredPYTHON_LIBCis confined to a staging config copy, not added to the final image environment. No distribution is silently substituted. When both a codename andPYTHON_LIBCare present they must name the same family, and the lower version wins. All digest references, includingpython:3.11-slim@sha256:..., require supportedPYTHON_LIBCmetadata: the digest is fetched without verifying that it matches any supplied tag. Local image names/annotations also cannot establish libc. Adding a tag to a digest does not make it safe; use an image config with supported metadata or a tag-only registry pull. Unsupported metadata always fails, as does metadata conflicting with a verified tag-only pull. Digest and unverified local sources also require explicitPYTHON_IMPLEMENTATION=CPythonandPYTHON_VERSION; claimed names do not establish the Python ABI. These metadata checks apply to lockfile, requirements and virtualenv staging alike.Environment markers in the requirements file and in transitive
Requires-Distmetadata are evaluated for the target (linux, the target machine, CPython and the base image’s Python version), not the build host. Markers onplatform_releaseorplatform_version, and onpython_full_versionorimplementation_versionwhen the base image does not declare a fullPYTHON_VERSION, cannot be known in advance and fail the build. A virtualenv cannot be re-resolved, so its closure is verified for each target instead. Requirements-file and pyproject roots and installedRequires-Distmetadata are checked for missing packages, version mismatches, and requested extras;Requires-Pythonand requirements constraint files are also checked. Every installed.dist-infoneeds validMETADATAwith a supportedMetadata-Version. Direct URLs, egg distributions, unknown markers, and patch-dependentRequires-Pythonwithout a fullPYTHON_VERSIONfail. Virtualenvs do not record selected extras or groups. An extra or group counts as not requested only when it is missing a requirement that the venv’s creator host provably would have installed. Only facts the venv establishes are used: CPython, the venv’s Python minor version when known, and the OS family from the layout (lib/pythonX.Y/site-packageswith a POSIXpyvenv.cfghomeis non-Windows; MSYS2 CPython is Windows with that layout;Lib/site-packagesis Windows). Markers on any other host value, such asplatform_machineor a specific non-Windowssys_platform, are unknown rather than assumed, so a requirement likefast; extra == "speed" and platform_machine != "armv7l"cannot rule the extra out. Otherwise, if its target requirements are not satisfied, verification fails rather than guessing; install the extra into the venv or use a requirements file instead. Direct URL installation metadata is rejected because it can contain credentials. Host-only packages remain in the image, and loose modules without package metadata are copied unverified.setup.py,setup.cfg,Pipfile, file-based dynamic dependencies, and Poetry, PDM, Hatch, setuptools or Flit tables mentioning host markers fail, as do unreadable dynamic dependencies. Unmarked declarations in those unparsed sources are not verified. Use a requirements file when a virtualenv cannot be verified.Private indexes can authenticate through
PIP_INDEX_URL, a pip config file,.netrc, keyring (PIP_KEYRING_PROVIDER=importorsubprocess) or${VAR}placeholders in the requirements file, including in URL paths. Literal credentials in requirements files (URL userinfo, secret-like query values and recognized URL path tokens) are rejected, and host pip settings that could change target selection (for examplePIP_PLATFORMorPIP_NO_BINARY) are ignored; see Private package indexes. -
--requirements FILE— Install this requirements file ([build] requirements-file). A requirements file that is not fully pinned with==versions and--hashvalues logs a warning that the dependency layer is not reproducible; generate one withpip-compile --generate-hashesor use a lockfile. -
--lockfile FILE— Stage dependencies frompoetry.lock,Pipfile.lock,pdm.lock, oruv.lock([build] lockfile).--no-lockfile(use-lockfile = false) ignores auto-detected lockfiles. -
--extra NAME— Also stage the project’sNAMEoptional-dependency extra fromuv.lock([build] root-extras = ["NAME"]). Repeat it to select several extras; CLI values replace the TOML list, and--no-extrasclears it. Requires--include-deps. See root extras. -
--strip-type-stubs— Opt in ([build] strip-type-stubs = true) to drop typing-only files from the dependency layer. Off by default; the default layer is unchanged. It deletes every staged*.pyifile and removes stub-only distributions (canonical namestypes-*or*-stubs) with their.dist-info, rewrites each affectedRECORD, and leaves them out of the SBOM. A stub-named distribution is removed only if itsRECORDlists nothing but.pyi,py.typed,*-stubs/METADATA.tomland its own metadata; one that also ships runtime code (for exampledjango-stubswith its mypy plugin) is kept, minus its.pyifiles. Files also listed by a retained distribution are preserved. A malformedRECORD, a stub distribution without aRECORD, or anyRECORDpath outside site-packages fails the build before anything is changed. The only outside entries accepted are virtualenv launchers in retained distributions, including stub-named packages with runtime files (../../Scripts/<name>or../../../bin/<name>, not.pyi); they are never deleted and stay byte-identical in the rewrittenRECORD. Identical inputs still give identical layer digests. Leave it off if a dependency reads.pyifiles at runtime; there are no per-package exceptions. -
Conda: name-only detection recognizes
environment.yml,environment.yaml,conda-lock.yml, andconda-meta/directories in the context. With--include-deps, Conda-only inputs fail explicitly (also in dry-run); a selected lockfile or pip requirements file is used with a warning that Conda inputs and Conda-only packages are ignored. Without--include-deps, ordinary Conda projects still build application-only images. Host Conda prefixes are never copied, even with explicit includes or--no-default-excludes; a context inside a Conda prefix requires a source-only context instead. See the export workaround. Full Conda staging is deferred to #187.
Image signing: --sign --sign-provider cosign|notation requires --push
and an independently configured signer. The registry must accept publication
by digest. The image manifest, or the top-level multi-platform image index, is
verified, signed, and its signature verified by the same provider and trust
configuration (--sign-verify-key, or the keyless certificate identity and
issuer, or a strict Notation trust policy) before tags are written. See the
signing guide for keys, OIDC, verification, limitations
and real-registry test prerequisites.
Provenance: --provenance writes dist/image/provenance.intoto.json;
--provenance-require-complete fails before tags are written if any evidence
is unavailable; --attest-provenance (with cosign signing) attaches and
verifies it before tags move. pycontainer verify-provenance checks it later.
See the provenance guide for the trust model.
Lockfiles: With --include-deps, the dependency source is chosen in this
order: --lockfile, then --requirements, then a single lockfile at the
context root, then a venv, then requirements.txt. Explicit --lockfile and
--requirements are mutually exclusive. More than one root lockfile is an
error until you choose one. No locking tool is needed at build time, and none
is added as a dependency:
- The lock is checked against its manifest (
pyproject.tomlorPipfile): Poetry and PDM content hashes, the Pipfile hash, or uv’s recorded requirements. A stale lock fails; runpoetry lock,pipenv lock,pdm lock, oruv lockand rebuild. - Root and recorded transitive markers are evaluated for each target image,
not the build host, so platform and Python forks select the container’s
dependencies. The base image must expose a full
PYTHON_VERSION=X.Y.Z. - The exact locked versions and their recorded hashes are installed with
pip --no-deps --require-hashesas target wheels and included in the SBOM. Pip does not resolve transitive dependencies in this mode: the lock must record the complete target graph and a matching wheel hash for each target.
The build context must be writable: temporary .pycontainer-lockfile-*
directories hold generated requirements, are excluded from images, and are
removed after staging.
The lockfile’s project manifest must resolve inside the build context. Symlinks to files within the context are supported; dangling or external links are rejected. Path checks do not protect against concurrent filesystem changes.
--dry-run checks lockfile selection and locally verifiable freshness
without pulling the base image. Target markers (including uv marker
freshness), Python compatibility and wheel availability are checked during
the build, not the dry run. For history grouping, the dry run also checks
Git evidence; target-specific group assignments are made during the build.
Only the default/main dependencies are staged by default; dev groups and
project extras are not. Supported formats: Poetry lock-version 2.1+, Pipenv pipfile-spec 6,
PDM lock_version 4 with inherit_metadata (Python-only targets), and uv lock
version 1 for a single project. Git, path, URL, and editable packages, uv
workspaces, sources, overrides and constraints, and PDM find_links fail with
an explicit error rather than falling back to an unconstrained install.
PDM locks with the static_urls strategy install each selected package only
from a target-compatible wheel at its recorded URL (#59, partial support).
Every file entry must record exactly a url and hash; each URL must be
plain HTTPS whose last path segment is the artifact filename, with no
credentials, ${VARIABLE} placeholders, query or fragment. The builder picks
the most specific wheel for the target’s tags, downloads it without following
redirects or trying any other source, verifies the locked hash in host temp
space and installs it by name and version from that private wheelhouse with
--isolated --no-deps --require-hashes --no-index. PIP_* settings, pip
config files and other indexes cannot substitute an artifact. HTTP(S) proxy
environment variables are honored for the download because TLS and the
hash still verify the bytes. Unsupported and rejected:
authenticated or signed URLs, redirects, packages that record only sdists
(source builds), package-level url (direct references), url entries without
the static_urls strategy, and mixed locks that combine url and file
entries. These checks also apply to inactive groups. Diagnostics never echo a
URL. Static locks bypass the dependency-layer cache (see below). Only synthetic
static locks have been tested; no real PDM-generated static fixture or
container runtime evidence exists for this path yet.
uv root extras: --extra NAME (or [build] root-extras) adds the
project’s own [project.optional-dependencies] extras to a uv.lock
selection. Names are canonicalized per PEP 685 (Web_API selects web-api),
deduplicated and sorted. The selected extras’ locked edges are followed for
each target image, evaluating root and transitive markers (including
extra == ... markers) for that target, and their manifest requirements are
added to the post-install metadata verification roots. The dependency-cache
key includes the selected extras; builds without extras keep their existing
keys. The following fail explicitly instead of installing a broader or
narrower set:
- extras with Poetry, Pipenv or PDM locks, or with a requirements-file,
virtualenv or
requirements.txtsource (checked before the base image is pulled, including in--dry-run); - an unknown extra (the error lists the declared extras), dynamic
optional-dependencies, or two declared extras that canonicalize to the same name; - a stale lock, or a lock in which a selected extra’s own root edges do not lock a matching version (and the requested dependency extras) of each of that extra’s requirements for the target. A matching package reached only through another dependency or another extra does not satisfy it.
Extras of dependencies are taken from the lock as recorded. Dependency groups,
--all-extras, build isolation (#22)
and native compilation are not part of this option.
PDM and uv projects with dynamic dependencies are unsupported. Poetry dynamic
dependencies must be declared in tool.poetry.dependencies.
Poetry’s Python and dependency ranges support PEP 440 constraints, exact
versions, wildcards, and single caret or tilde constraints; other
Poetry-specific combinations are rejected. Applicable Poetry root and
recorded transitive dependencies, including requested extras, must be present
at compatible locked versions. uv extras without recorded dependencies are
treated as empty, consistent with uv.
Pipenv roots and PDM roots and recorded edges must be present at compatible
locked versions. For all four formats, staged wheel dependency metadata is
checked for target-compatible transitive versions, markers and requested
extras before creating a layer. Each wheel needs valid metadata in its matching
.dist-info directory, limited to 1 MiB. This cannot detect dependencies
omitted from the wheels’ own metadata.
uv registry URLs must match the current [[tool.uv.index]] declarations
or the implicit PyPI index; settings from uv.toml and legacy index options
are not supported. Limited-resolution uv locks are accepted only when their
recorded supported markers match the configured environments after supported
normalization and include the target; unverifiable marker equivalence and
unknown target marker values fail explicitly. Normalization supports
python_version >= 'X.Y' and python_version < 'X.Y' bounds; other
unrecognized equivalences are rejected even if they are logically equal.
Each package is installed only from the index its lock records, one pip run
per index with --isolated and every PIP_* variable and pip config file
ignored, so PIP_INDEX_URL, pip.conf, --find-links wheelhouses or another
index serving the same hash cannot substitute an artifact. Per-package sources
come from uv source.registry, Poetry source (none means PyPI, which must
then be an enabled Poetry source) and Pipenv index (unset means Pipenv’s
first source; install_search_all_sources fails closed). PDM records no per-package index, so a PDM lock is accepted
only with a single effective index (PyPI or one source named pypi), and
pdm.toml [pypi] settings are rejected. User or global PDM index settings
(pdm config pypi.url, PDM_PYPI_URL) are not recorded in the lock and
cannot be detected; such a lock is installed from PyPI, where its hashes must
still match. To build through a PyPI mirror,
relock against the mirror so the lock records it. The recorded index is
trusted for the files its pages link to (PyPI serves them from
files.pythonhosted.org), and hashes verify the bytes. Recorded indexes must
use HTTPS; plain HTTP is accepted only for loopback hosts, because pip may
send netrc credentials. Index credentials must
be ${VARIABLE} placeholders in the URL’s credentials or query values (never
its host or path, which fix the source) over HTTPS, or netrc, never literal
secrets; proxy and CA bundle variables such as
HTTPS_PROXY and SSL_CERT_FILE still apply. Plain requirements files keep
normal pip behavior, including your pip configuration.
Grouped dependency layers (experimental): The default remains one
dependency layer. With --include-deps, select explicit or history to
partition the target-selected uv.lock installation into stable and frequent
layers, followed by the application layer:
pycontainer build --include-deps --dependency-layer-strategy explicit \ --stable-dependency numpy --frequent-dependency my-package[build]include-deps = truedependency-layer-strategy = "explicit"stable-dependencies = ["numpy"]frequent-dependencies = ["my-package"]CLI assignments are repeatable and replace the corresponding TOML list.
Names are Python distribution names, normalized for comparison. In explicit
mode, unassigned packages, including shared transitive dependencies, belong to
the frequent group. Each installed distribution belongs to exactly one group.
Explicit assignments override history. A group with no packages produces no
layer.
The history strategy examines up to 20 first-parent commits that changed
uv.lock; --dependency-history-ref REF selects a commit or ref instead of
HEAD. It prints the resolved commit, evidence, and assignment reasons.
For each historical snapshot, the uv lock graph is evaluated for the target
environment, including markers and requested dependency extras. Packages with
changed or missing target versions are frequent; consistently present,
unchanged versions are stable. A snapshot that cannot identify a valid target
graph fails explicitly. Git must be available, the lock must be tracked and
unmodified without assume-unchanged or skip-worktree flags, the repository
must not be shallow or partial, and at least two distinct lock snapshots must
be available. Missing evidence is an error, not an inferred classification.
Grouping currently supports only uv.lock: Poetry, Pipenv, PDM, plain
requirements, and virtualenv sources are rejected rather than silently grouped.
The single-layer mode still supports those sources as described above. Grouping
installs the selected graph once, verifies distribution file ownership, and
rejects collisions or unowned files. The application cannot overwrite the
reserved <workdir>/.python directory. Namespace packages, console scripts,
metadata and SBOM inventory remain part of the selected installation.
A complete verified group-cache hit skips pip and package-index requests.
The cache keys include the full manifest roots and extras, target environment,
and type-stub setting; credentialed, query-bearing, and proxy sources remain
explicit cache misses. When the lock changes, the full selection is staged and
its wheel closure is verified again. An unchanged group may reuse its cached
layer when the full roots are unchanged, and an unchanged layer digest can
still reuse a registry blob. --strip-type-stubs applies before grouping, and
--squash can flatten the grouped and application layers, at the cost of
layer-level reuse. Grouping does not add build-time/dev dependency or
project-extra selection (#25).
Local base images
Section titled “Local base images”--base-image (and base_image in [build]) can read a base image from disk
without a registry, credentials, or a Docker daemon:
# OCI image layout (for example `skopeo copy docker://python:3.11-slim oci:base:3.11-slim`)pycontainer build --tag app:v1 --base-image oci:./base:3.11-slimpycontainer build --tag app:v1 --base-image oci:./base@sha256:<manifest-digest>
# A previous pycontainer output is itself an OCI layoutpycontainer build --tag app:v2 --base-image oci:./dist/image:app:v1 --output ./dist/v2
# Uncompressed `docker save` archive (legacy and Docker 25+ formats)pycontainer build --tag app:v1 --base-image docker-archive:./python.tar:python:3.11-slimoci:<path>[:<ref>]selects an index entry whoseorg.opencontainers.image.ref.nameorio.containerd.image.nameannotation exactly matches<ref>(or@sha256:<digest>). For a single-entry index, either annotation on the index itself can also identify the entry. The reference may be omitted when the layout holds one image, or a set of images that all carry platform metadata. Nested image indexes use the same exact OS/architecture/variant selection as registry pulls.docker-archive:<path>[:<repo-tag>]selects amanifest.jsonentry byRepoTags, normalized like registry references (python:3.11-slimmatchesdocker.io/library/python:3.11-slim). The tag may be omitted when the archive holds one image.- The path ends at the first
:after an optional Windows drive prefix, so paths containing:are not supported. Relative paths resolve against the current directory, and the source must not overlap--output. - Every blob is checked against its digest and size, and every base layer is
checked against its config
rootfs.diff_ids(tar,tar+gzip;tar+zstdneeds Python 3.14+). Unknown layer media types, layers labeled as plaintarwhose bytes are compressed or not a tar stream, unsafe or duplicate archive members, sparse members, symlinked OCI layout blobs, archive links that escape the archive, and more than 100,000 members, 1,000 layers or 16 MiB of metadata are rejected. Each OCI index, including nested indexes, is limited to 1,000 entries. Layers are limited to 64 GiB (including decompressed content); Docker archive member sizes are checked before any selected image blobs are staged. - Compressed outer archives (
docker save | gzip) andoci-archive:tarballs are not supported; extract or decompress them first. - OCI annotations and Docker archive tags do not establish an image’s Python
ABI or libc. For
--include-deps, local images must setPYTHON_IMPLEMENTATION=CPython,PYTHON_VERSION, and eitherPYTHON_LIBC=glibc-2.N(N 17-99) orPYTHON_LIBC=musl-1.N(N 1-99) in their image config, even if their name claims to be an official Python image. These settings are not required when dependency staging is disabled.
Inspecting images
Section titled “Inspecting images”pycontainer inspect reads a local OCI layout or docker save archive without
a registry, credentials, or a Docker daemon and reports what each layer adds,
changes, and removes:
pycontainer inspect dist/image # pycontainer outputpycontainer inspect oci:./base:3.11-slim --files # every layer's entriespycontainer inspect oci:./base --platform linux/arm64 --layer 3pycontainer inspect docker-archive:./app.tar --diff 2 5 # compare filesystem statespycontainer inspect dist/image --json # machine-readable reportThe report lists each layer’s compressed and uncompressed size, member count and
added/modified/deleted paths, the final filesystem totals, and observations:
content shadowed by later deletions or replacements, duplicate files, Python
bytecode, pip and APT caches, VCS metadata, and the largest files. Observation
sizes are uncompressed tar-header sizes, not measured registry or disk savings.
Inspection verifies every layer’s DiffID and fails with an explicit error,
never a partial report, on unsafe paths, entries beneath symlinks, malformed or
mislabeled layers, or an ambiguous multi-platform index without --platform.
It does not start the image; use the opt-in runtime check for that. See
Image inspection.
Previewing a build
Section titled “Previewing a build”pycontainer preview compares the image a build would produce with an
existing image, without building, caching, or running anything. Name the
baseline explicitly; local baselines are read offline, and a registry image
requires the docker:// prefix:
pycontainer preview --baseline dist/image # last local buildpycontainer preview --baseline docker-archive:./app.tar:app:v1 --jsonpycontainer preview --baseline docker://ghcr.io/me/app:v1 --base-image python:3.12-slimIt accepts planning flags from build, including --config, --build-arg,
--base-image, --context, --include, --exclude, --include-deps,
--squash, and a single --platform; see pycontainer preview --help.
Python-version matrix configurations require a separate single-version
configuration for previewing each image.
The report compares the base, dependency and application components, files,
and image settings. Anything the evidence cannot establish is unknown,
never unchanged, and environment values are redacted. Squashed dependency
layers, mirrored registry bases, and bases with required trust policies cannot
be determined. File changes without exact provenance are marked inferred.
Baseline and project reads are size-bounded; see Build preview
for provenance, redaction and accuracy limits.
Base image trust
Section titled “Base image trust”Registry signature verification is opt-in. Configure
[build.base_image_trust] to require Cosign or the supported strict Notation
subset for one exact repository. Verification is bound to the resolved digest
before base-image config or layer downloads; a required policy rejects local
OCI and Docker archives. A dry run validates the policy’s shape but does not
verify an image. The Notation subset supports single-signer COSE_Sign1 and
flattened JWS. Signature discovery uses pycontainer’s registry credentials;
verifiers receive only an isolated local layout and never registry
credentials. Unsupported signature forms fail closed. No hosted private
registry or registry-hosted post-expiry signature has been exercised.
See Base image trust for configuration, verifier and trust-material setup, limitations, and opt-in real-provider checks.
Context Selection:
--include PATH— Include a context-root-relative file or directory; repeat to select multiple paths instead of automatic discovery--exclude PATH— Exclude a context-root-relative path or glob; repeat to add exclusions- Default exclusions prune VCS metadata, virtual environments, generated output/cache directories, and test/fixture files and directories before scanning
--no-default-excludesdisables those defaults; use it only when those files are intentionally part of the image
The same options are available in [build] as include-paths, exclude-paths,
and exclude-defaults. Include paths are relative to the build context and
overlapping paths are deduplicated. For example:
[build]include-paths = ["src", "pyproject.toml"]exclude-paths = ["src/generated", "fixtures/**"]exclude-defaults = trueContext traversal never follows directory symlinks or Windows junctions. A
linked include root (including auto-detected src, app or a virtualenv)
fails the build; nested directory links are skipped. A selected file symlink
must use a relative target that resolves to an existing file inside the
context and that is itself selected (exclusions win); it is stored as a link
with / separators. A target may climb with leading .. components, but not
above the context root, and may not use .. after descending into a directory.
Absolute, dangling, cyclic, out-of-context and unselected-target file links
fail the build. A context directory that is itself a symlink is still
supported. These checks are not a defense against the context changing during
a build, and they do not cover explicitly named inputs such as requirements or
manifest files.
Caching Options:
--no-cache— Disable layer caching, force full rebuild--cache-dir PATH— Custom cache directory (default:~/.pycontainer/cache)
Local Build History:
pycontainer build --record-historypycontainer history listpycontainer history clearHistory is disabled by default. It records only a random run ID, UTC start
time, outcome, and timings, never build configuration or error text. Use
--history-dir PATH to select a directory outside the build context and OCI
output; specifying a directory alone does not enable recording. For a build
configured with record-history = true, --no-record-history disables it.
See the build history guide for retention, privacy,
error handling, and custom-directory inspection.
Production Features:
--config FILE— Load settings frompycontainer.toml--label KEY=VALUE— Set an image-config label; repeat to add labels--manifest-annotation KEY=VALUE— Set an image-manifest annotation; repeat to add annotations--index-annotation KEY=VALUE— Set a local layout-index annotation; repeat to add annotations--release-notes FILE— Embed a UTF-8 release notes file (at most 8 KiB after line endings become LF) in theio.github.spboyer.pycontainer.release-noteslabel;--release-notes-label KEYselects another key--sbom [FORMAT]— Generate an SBOM (defaults tospdx; acceptsspdxorcyclonedx)--platform PLATFORM— Target platform (os/architecture[/variant], e.g.,linux/arm64orlinux/arm/v7), or a comma-separated subset oflinux/amd64,linux/arm64,linux/arm/v7to build an OCI image index. Windows targets (anywindows/...case or architecture) are rejected; see Current Limitations--stop-signal SIGNAL— ImageStopSignal, as a canonical Linux name such asSIGTERM,SIGINTorSIGRTMIN+3--volume PATH— Declare an image volume (repeatable; absolute Linux path)--image-user USER[:GROUP]— ImageUser(see Process identity);--image-user ""inherits the base value.--userremains an abbreviation of the registry--usernameoption--verbose/-v— Detailed build progress--dry-run— Preview build without creating artifacts--no-reproducible— Disable deterministic builds--analyze-layers— Writelayer-analysis.jsonwith per-layer sizes, repeated content and predicted squash savings--squash— Opt in to merging the layers pycontainer creates (dependencies and application) into one layer; base-image layers are never squashed
The default layout is unchanged unless --squash is given. Squashing
preserves overlay semantics (whiteouts, opaque directories, links, metadata)
or fails explicitly, but it usually saves little space for pycontainer’s own
layers and gives up layer-level cache reuse between the dependency and
application layers. See Layer analysis and squashing
before enabling it.
Labels inherit from the base image; their precedence is CLI, configuration
file, detected framework, then base image. Manifest and index annotations are
separate from labels and are not inherited from the base. For a single-image
build, index annotations are in the local index.json; registry pushes publish
the image manifest, not that layout index. Metadata is visible to image
consumers and registries: do not put secrets in labels or annotations.
See metadata configuration and integration details.
Registry Transport (see docs/REGISTRY_PUSH.md):
--insecure-registry HOST[:PORT]— Use plain HTTP for exactly this registry (repeatable;[build] insecure-registries = [...]). Each build that uses one logs a warning. Credentials are sent over HTTP only to loopback hosts (localhost,127.0.0.0/8,::1); any other HTTP registry must be anonymous.--registry-ca-file PATH— Trust an additional PEM CA bundle for registry HTTPS ([build] registry-ca-file). Certificate verification always stays on; there is no option to skip it.--registry-mirror UPSTREAM=MIRROR— Pull base images throughMIRRORbeforeUPSTREAM(repeatable, tried in order;[build.registry_mirrors]). Pushes never use mirrors, and mirrors never receive upstream credentials. See base-image registry mirrors.
Registry connections are direct: environment/system proxy settings are ignored. URLs containing embedded credentials are rejected; use the credential providers or authentication flags instead.
SBOMs are sidecar files: their UTC timestamps and UUID document identifiers are new for each generation, even when the OCI image build is reproducible. They do not affect the image manifest digest. Inventory contains Python distributions staged by pycontainer, not host packages, uninstalled requirements, or packages inside the base image.
The cache automatically:
- Reuses unchanged layers across builds (content-addressable by SHA256)
- Invalidates when file contents, relative paths, permission bits, the workdir or reproducibility settings change (mtime is ignored for reproducible builds)
- Invalidates when hardlinks between selected files are added or removed; the key records context-relative link targets, not inode numbers
- Evicts old entries using LRU when size limit reached (default: 5GB)
Dependency layer reuse. A whole staged dependency layer is reused only when
its complete target closure is provably hash-pinned: a lockfile selection
(except PDM static_urls locks, which bypass cache reads and writes because
the key does not yet record their artifact URLs), or
requirements (including nested -r/-c files) where every requirement is
==-pinned with --hash. A hit runs no pip install and makes no index requests,
and yields the same layer digest, DiffID and SBOM inventory as a fresh build.
The key covers requirement/constraint/find-links content, target platform,
pip target/ABI/libc tags, the installer’s target marker environment, locked
manifest roots and extras from the same snapshot used for package selection,
the backend used for closure verification, Python version and implementation,
workdir, type-stub stripping, pip version, the installer backend and sanitized index and find-links
identities, including their exact paths. Plain
requirements also key allowlisted ambient pip settings, read locally through
pip’s configuration parser even on a hit; snapshots preserve file/environment
precedence with both pip 25’s flat settings and pip 26’s per-file settings.
Shadowed settings are still checked for unsafe sources. Locked installs are --isolated.
Index credentials and userinfo placeholders never enter cache metadata.
Anything that cannot be proven is
an explicit miss printed as
Dependency layer cache miss: <reason>., including unpinned or unhashed
requirements, -e, --no-deps, direct-URL constraints, file: find-links,
virtualenv staging, --no-reproducible, unknown ambient pip settings, and any
index or find-links URL with userinfo, a credential-bearing path, query string
or fragment. Configured netrc credentials, client certificates and explicit
keyring providers also cause misses: authentication can route the same URL to
different feeds. Index URLs must use HTTP or HTTPS.
HTTP, HTTPS, all-protocol or system proxies also cause a miss unless
NO_PROXY=* bypasses them; a pip-configured proxy always causes a miss for
plain requirements. Proxies can route the same index to different feeds.
Plain requirements also miss for absolute includes, symlinked requirement
files, or local find-links paths that are absolute, symlinked, outside the
context, or contain directories or HTML. Local find-links from ambient pip
configuration, unsupported requirement encodings and ambiguous comments also
miss. Nonempty PYTHON* environment
variables such as PYTHONPATH, PYTHONHOME and PYTHONUSERBASE also cause
a miss for both lockfiles and plain requirements, except informational
Python-image version/bootstrap metadata; their values are never stored. Plain
requirements also miss when PIP_CONFIG_FILE is relative because pip runs in
the build context. On an eligible plain-requirements miss, the installer uses
private temporary copies of the keyed requirements, local find-links files,
pip settings and environment; the files are verified against the key before
use. Eligible locked installs also use the captured no-proxy environment.
Eligible installs disable netrc so credentials added after keying cannot change
their source.
Copies are limited to 512 MiB and 100,000 files, and failure to make or
verify them falls back to an uncached install. Temporary configuration can
contain credentials and is removed after staging. A hit reuses the artifacts
selected when the entry was stored. Avoid editing the build context while a
build runs: the snapshot protects cache identity, not all other image layers.
Saving and restoring the cache (offline export/import): the --cache-dir
directory (index.json plus blobs/sha256/) is self-contained and stores only
relative source paths, so it can be archived or saved by CI (for example with
actions/cache) and restored to a different absolute path and checkout
location. A restored cache produces cache hits and an identical OCI manifest,
config and layers. Partial restores are handled as follows:
- Blobs without
index.json: a clean miss; the layer is rebuilt and indexed. index.jsonwith missing or corrupt blobs: those entries are discarded and rebuilt.- Malformed
index.json: the build fails withCacheIndexError; delete the reportedindex.json(cached layers are rebuilt) or rerun with--no-cache. - Concurrent builds may share a restored directory; index updates are locked.
Caches are portable between machines of the same OS, not across operating
systems: Windows reports source files as mode 0o666, Linux checkouts as
0o644/0o755, and the mode is recorded in the layer, so a cache saved on
Windows misses on Linux (and vice versa) by design. Windows checkouts with
core.autocrlf also change file content. Key saved caches on the OS. Blobs
left without an index entry are not counted or evicted; delete the directory to
reclaim them. See GitHub Actions.
Python API
Section titled “Python API”from pycontainer.config import BuildConfigfrom pycontainer.builder import ImageBuilder
config = BuildConfig( tag="myapp:latest", context_dir=".", base_image="python:3.11-slim", # Optional: auto-detected if omitted include_deps=True, workdir="/app", env={"DEBUG": "false", "ENV": "production"}, labels={"version": "1.0", "maintainer": "team@example.com"}, manifest_annotations={"org.opencontainers.image.title": "myapp"}, index_annotations={"org.opencontainers.image.description": "myapp layout"}, include_paths=["src/", "lib/", "pyproject.toml"], exclude_paths=["src/generated", "fixtures/**"], entrypoint=["python", "-m", "myapp"], generate_sbom="spdx", # or "cyclonedx"; True defaults to SPDX reproducible=True, verbose=True)
builder = ImageBuilder(config)builder.build()Configuration File (pycontainer.toml)
Section titled “Configuration File (pycontainer.toml)”[build]base_image = "python:3.11-slim"workdir = "/app"include_deps = truereproducible = truegenerate-sbom = "cyclonedx" # false disables; true or "spdx" selects SPDXanalyze-layers = false # true writes layer-analysis.jsonsquash = false # true merges builder-created layers onlyrelease-notes-file = "CHANGELOG-1.0.0.md" # optional; relative to the context
[build.labels]maintainer = "team@example.com"version = "1.0.0"
[build.manifest_annotations]"org.opencontainers.image.title" = "myapp"
[build.index_annotations]"org.opencontainers.image.description" = "myapp layout"
[build.env]PORT = "8080"ENV = "production"DEBUG = "false"
[registry]url = "ghcr.io/myorg/myapp"Explicit CLI options override [build] values; omitted options leave the file
values intact, and settings absent from both use BuildConfig defaults. Keys
in [build] may use hyphens or underscores. After overrides are applied,
unknown settings and values with the wrong TOML type are reported as
configuration errors.
Stop signal and volumes
Section titled “Stop signal and volumes”stop_signal (--stop-signal) and volumes (--volume, repeatable) set the
OCI image config StopSignal and Volumes fields:
[build]stop_signal = "SIGINT"volumes = ["/data", "/var/cache/app"]- When unset, the base image’s
StopSignalandVolumesare inherited unchanged. A configuredstop_signalreplaces the base value. - Configured volumes are merged with the base volumes as a sorted,
de-duplicated set, so the config digest is deterministic. Base volumes
cannot be removed.
--volumevalues replace (not extend) the file’s list. - Signals must be canonical Linux names (
SIGTERM, notterm,15orsigterm). Volume paths must be absolute, normalized Linux paths;/, relative paths,./..segments, backslashes, trailing slashes and control characters are rejected. - Volumes are image metadata only: pycontainer does not create mounts, and the
container runtime decides how to back them. The stop signal is honored only by
runtimes that read it, such as
docker stop. - These are config fields, not OCI labels;
labelsare unaffected.
Process identity
Section titled “Process identity”user (--image-user) sets the OCI image config User field:
[build]user = "1000:1000"- Accepted forms are the six OCI Linux forms:
user,uid,user:group,uid:gid,uid:groupanduser:gid. Empty components, more than one:, surrounding whitespace and control or format characters are rejected before any cache, pull or output side effect. Error messages describe the defect without echoing the value. - When
useris unset or"", the base image’sUseris inherited verbatim (or omitted when the base has none).--image-useroverrides the file value, and--image-user ""clears it so the base value is inherited. --useris still accepted as an abbreviation of the registry--usernameoption; use--image-userfor the image identity.- Names are resolved by the container runtime inside the target image at run
time (for example from
/etc/passwd); pycontainer does not check that they exist. Specifying a group replaces the user’s supplementary groups. - This is image metadata only: pycontainer does not change file ownership,
create users, enforce the identity or configure host/container UID or GID
mappings. OCI
uidMappings/gidMappingsremain out of scope (#162, #51).
Opt-in runtime verification on Linux/WSL with Skopeo and a native
linux/amd64 Docker daemon:
PYTHONPATH=src timeout 600 python scripts/check_process_identity_runtime.py --evidence user-runtime.json.
This builds and starts all six forms plus unset/empty inheritance against the
Debian Python base’s nobody/nogroup accounts, checking actual process IDs
without a docker run --user override. It is not part of default pytest or
the release evidence gate; hermetic harness tests do not prove runtime behavior.
Same-repository pull requests also run it on the native linux/amd64 runner in
runtime-check.yml and upload process-identity-runtime-evidence; arm64 is
not exercised.
Health check (Docker metadata)
Section titled “Health check (Docker metadata)”An optional [build.healthcheck] table ([tool.pycontainer.healthcheck] in
pyproject.toml) writes a Docker-compatible Healthcheck image-config object:
[build.healthcheck]mode = "exec" # or "none" to disable an inherited checkcommand = ["/usr/local/bin/python", "/app/healthcheck.py"]interval-ms = 30000 # optional; also timeout-ms, start-period-msretries = 3 # optionalWithout the table the base image’s check is inherited unchanged; a configured table replaces the base object entirely. Unspecified timings are omitted so the runtime applies its defaults. The command runs without a shell and is not interpolated. Invalid settings fail before any pull or output. This is Docker Engine (Linux) metadata only; other runtimes and Kubernetes may ignore it. See health-check metadata.
--config also accepts a pyproject.toml whose settings live under
[tool.pycontainer] (with [tool.pycontainer.env] and
[tool.pycontainer.labels]), which is what pycontainer import generates.
The same keys, validation and CLI precedence apply. A file that defines both
[build] and [tool.pycontainer] is rejected rather than merged; keep exactly
one. A file passed explicitly that defines neither table (for example a
misspelled [biuld]) is an error, not a silent fall-back to defaults. Poetry-only keys such as push are reported as unknown by
pycontainer build; use --push instead. See
Dockerfile import.
pycontainer import Dockerfile --format toml > imported.tomlpycontainer import Dockerfile --strict --output pyproject.tomlTOML mode keeps the report on stderr. --strict rejects recorded warnings
before writing --output; it does not prove complete Dockerfile equivalence.
Optional [build.security.kubernetes] and [build.security.oci] tables
([tool.pycontainer.security.*] in pyproject.toml) write deployment
fragments to <output_dir>/security/ without changing the image. They are
not enforced by the image; see runtime security
fragments for the schema, supported versions and
how to apply them.
Concurrent builds targeting the same output directory are rejected; use a separate output directory or retry after the current build finishes.
Python version matrix
Section titled “Python version matrix”python -m pycontainer.cli build --python-version 3.11,3.12 --tag myapp:v1.2.3
builds separate images, not an OCI index combining Python versions. Layouts
are written to dist/image/py3.11 and dist/image/py3.12; --output changes
their parent directory. Each version can independently contain an architecture
index with --platform linux/amd64,linux/arm64.
Every explicit tag gets a -pyX.Y suffix. Unsuffixed explicit tags and aliases
from --latest/--semver-tags belong only to the first requested version, or
the version selected by --default-python-version. For example, the command
above gives both v1.2.3-py3.11 and v1.2.3-py3.12, with v1.2.3 on 3.11.
Version order is explicit; versions are not sorted or silently dropped.
Unpinned official python:<minor> bases are rewritten while preserving their
tag suffix (python:3.11-slim becomes python:3.12-slim). Custom, local,
digest-pinned and non-minor official bases require explicit mappings:
[build]tag = "ghcr.io/myorg/myapp:v1.2.3"python_versions = ["3.11", "3.12"]default_python_version = "3.12"platform = "linux/amd64,linux/arm64"output_dir = "dist/image"latest_tag = truesemver_tags = true
[build.python_matrix]"3.11" = "ghcr.io/myorg/python-base:eleven""3.12" = "ghcr.io/myorg/python-base:twelve"Each pulled base must provide the requested minor in PYTHON_VERSION; custom
bases must also declare PYTHON_IMPLEMENTATION=CPython. This is checked for
every architecture even without dependencies. Application environment
overrides and unverified tag names are not proof of the base’s Python version.
Dependency staging retains the existing wheel-only/virtualenv compatibility
checks; a missing wheel fails that version rather than dropping it. Lockfile
markers and hashed wheels are selected independently for each Python version
and platform, using the base’s full PYTHON_VERSION.
Matrix builds reject signing, provenance attestation and build --validate;
unsigned provenance (with single dependency layers) and separate validate image checks work per layout.
With --push, all versions build and pass integrity verification before any registry
publication. Blobs and manifests/indexes publish by digest first, then all
version-specific tags, then default-version aliases. Generic registries cannot
atomically update multiple tags. A later failure may leave earlier tags moved
or uploaded untagged content behind; the command exits nonzero and reports
each operation as confirmed, failed, unknown or unattempted. A timeout
or ambiguous server outcome is not reported as success or unchanged. No tags
are deleted, rolled back, restored or automatically retry-overwritten, since
another writer may have changed them. Completed local version layouts may
remain after another version fails. Local output locks protect builds and
publication from other cooperating builders; remote tags are not locked.
Validating configuration offline
Section titled “Validating configuration offline”pycontainer validate config resolves the effective build configuration the
same way build does (defaults, local Python detection, [build] or
[tool.pycontainer], and CLI-over-file precedence) without building, pulling,
pushing, touching the cache or writing files:
pycontainer validate config # build defaults for the current directorypycontainer validate config pycontainer.toml pyproject.toml --platform linux/arm64pycontainer validate config -c pyproject.tomlIt exits 0 when every configuration is valid and 2 for invalid settings,
missing files, files without a [build] or [tool.pycontainer] table,
conflicting tables or usage errors, and lists the registry,
dependency-resolution and runtime checks it did not perform. A passing
validation does not prove a build will succeed. See
configuration validation.
Validating images offline
Section titled “Validating images offline”pycontainer validate image verifies an existing OCI layout and reports
best-practice findings without a registry or container daemon. Use
pycontainer build --validate --push to run the same checks before publishing:
pycontainer validate image --output dist/image --format jsonpycontainer validate image --tag myapp:latest --platform linux/arm64pycontainer validate image --max-image-size-mb 500 --max-layer-size-mb 200pycontainer build --config pycontainer.toml --validate --pushEach run reports the stored image size, largest layer and, during
build --validate, base versus application/dependency contributions. These
are stored blob sizes (base layers usually compressed, application layers
uncompressed tar), not network transfer or cache reuse. Optional thresholds, set with
the flags above or max_image_size_mb / max_layer_size_mb under
[build.validate], warn as PCB006 and PCB007 only when exceeded.
CLI and TOML thresholds retain exact decimal precision; JSON reports them as
decimal strings (or null when unset), not rounded floats. Excessive precision
or magnitudes are rejected with exit 2; see the validation limits below.
BuildConfig JSON snapshots retain decimal thresholds as exact strings too;
an unoverridden TOML threshold must be a numeric literal, not a quoted string.
Validation exits 0 below the requested severity threshold, 1 for findings at or above it, and 2 for usage, layout or integrity errors. Base-image provenance is reported as unknown, not inferred from labels. See the image validation rules, suppression and limits.
Generating a configuration file
Section titled “Generating a configuration file”pycontainer init writes a [build] file offline from a template, or from an
explicitly invoked terminal wizard. It never prompts for credentials, never
contacts a registry or daemon, and never edits pyproject.toml:
pycontainer init --list-templates # fastapi, flask, genericpycontainer init --template fastapi # writes pycontainer.tomlpycontainer init -t flask --app web:app --port 8080 -o deploy/flask.tomlpycontainer init --interactive # TTY only; never overwritespycontainer build --config pycontainer.tomlThe result is validated with the same loader and resolver build --config
uses before it is published. An existing regular file is refused unless
--force is passed (templates only); links, directories and special files are
rejected. Cancellation never exposes a partial output file.
Creating without --force requires hard-link support for atomic no-clobber publication.
Templates write configuration only; they do not add application code or new
framework detection. See configuration templates and wizard.
Build arguments
Section titled “Build arguments”Declare inputs in either configuration table, then pass repeatable overrides:
[build]tag = "myapp:${VERSION}"workdir = "/app"entrypoint = ["python", "-m", "app"]
[build.build-args]VERSION = "1.0.0" # string defaultENVIRONMENT = {} # required, including an explicitly empty valueOPTION = { default = "" } # optional default table
[build.labels]version = "${VERSION}"literal = "$${VERSION}" # persists the literal ${VERSION}
[build.env]APP_ENV = "${ENVIRONMENT}" # explicit runtime persistencepycontainer build --config pycontainer.toml --build-arg ENVIRONMENT=production --build-arg VERSION=1.2.3For pyproject.toml, use [tool.pycontainer.build-args] instead.
The skaffold-build and tilt-build commands accept the same overrides
when using a configuration file.
Names match [A-Za-z_][A-Za-z0-9_]*; values are strings. Overrides split on
the first = (so OPTION=a=b is valid), and the last occurrence wins.
Ordinary explicit CLI settings override file settings before interpolation.
Malformed or undeclared arguments, missing required values, invalid/unclosed
references, and C0/C1/DEL control characters fail before building, including
in dry-run mode. Defaults are checked even when overridden.
${NAME} expands once, only in tag, tags, base_image, context_dir,
workdir, entrypoint, cmd, user, include_paths, exclude_paths,
output_dir, cache_dir, requirements_file, platform, stop_signal,
volumes, and the values
of env and labels. Hyphenated setting aliases work too. Dictionary keys,
SBOM formats, system-package declarations, healthcheck and other settings do not expand.
$$ escapes one literal dollar; bare $NAME stays literal. Inserted values
are not rescanned, defaults do not reference other arguments, and no host
environment lookup, expression evaluation or shell execution occurs.
Direct BuildConfig callers opt into interpolation by supplying build_args;
without it, existing literal dollar expressions are preserved. Copying or
serializing a config does not re-interpolate already expanded or
framework-generated values, even if its arguments change. Unexpanded user
fields and changed values, including edits made after construction, expand once
on a copy with arguments; copies without arguments defer their expansion. List
entries are matched by value and count, preserving earlier matching entries.
An override identical to an existing value is indistinguishable from an
unchanged copy and remains literal. Construct a fresh config from unexpanded
values to re-interpolate it. The config remembers nonempty argument values when
it resolves them, redacts output, or is copied or serialized. An in-place value
inserted and removed before any of these observations cannot be recovered.
Serialized configs, including dataclasses.asdict and JSON snapshots, retain
observed values for diagnostic redaction even after arguments are cleared;
treat these snapshots as sensitive.
Arguments are not secrets and are not automatically runtime environment
variables. Only explicit interpolation into persisted image fields (including
labels, environment, command or workdir) stores a value in image metadata.
Configuration/source files selected for the app layer are still copied normally;
exclude files containing defaults if they should not be shipped.
Diagnostic output redacts known nonempty argument values. Cache metadata contains
hashed resolved configuration/target/backend identity, not argument values;
argument builds omit source-path metadata. Unused argument changes do not
invalidate the app-layer cache. The cache stores actual layer contents, not
encrypted data. Dockerfile import --build-arg remains a separate, Dockerfile-
scoped interface; imported values escape dollars to preserve their runtime
meaning when loaded. Build arguments do not introduce stages; conditional file
selection is limited to the file rules below.
Conditional file rules
Section titled “Conditional file rules”file-rules add or remove application files based on declared build arguments
and the explicit target platform:
[build]include-paths = ["src", "pyproject.toml"]
[build.build-args]BUILD_MODE = "production"
[[build.file-rules]]when = 'BUILD_MODE == "dev"'include = ["debug_tools/**"]
[[build.file-rules]]when = 'BUILD_MODE == "dev" and target.arch == "arm64"'exclude = "debug_tools/x86_only"pycontainer build --config pycontainer.toml --build-arg BUILD_MODE=dev --platform linux/arm64Use [[tool.pycontainer.file-rules]] in pyproject.toml. File rules must be
a list of tables; an empty list leaves selection unchanged. Each rule has
exactly when plus one of include or exclude (a pattern or a non-empty
list). A condition is one or more NAME == "value" or NAME != "value"
comparisons joined by and; string values use double quotes and support only
\" and \\ escapes. Names are declared build arguments, target.os and
target.arch (from platform, including a --platform override). The host
environment is never read and nothing is evaluated as code.
File rules currently require a single target platform; comma-separated target
lists are rejected until per-target selection and application layers are supported.
A Python-version matrix can use file rules with one target platform; the same
resolved rules apply to every Python version.
Unknown names, unknown keys, malformed expressions, and absolute, drive-qualified or ..
patterns fail before building, even for inactive rules. Patterns are literal
(not ${}-expanded), relative to the context, case-sensitive, and use / or
\ interchangeably; a pattern matching a directory matches everything below it.
validate config checks these rules against the same resolved arguments and
platform as build, but does not select files or verify symlink targets.
When changing a BuildConfig platform or rules would change the active
patterns, create a new BuildConfig; builds reject a stale selection.
Active includes add to include-paths; every exclusion wins over every
include. That covers active exclude rules, exclude-paths, the default
exclusions (so a tests/** rule needs --no-default-excludes), and the output
and cache directories, which are always excluded. Conda environment prefixes
(directories containing conda-meta/) are also always pruned, including symlink
aliases to them. Ordinary includes skip these prefixes; a conditional rule
rooted inside one fails unless that root is already excluded. Host
Conda environments are never copied into the image. The selection is refreshed
once per build and shared by framework detection, --dry-run (which reports the count and,
with -v, each path), the app layer and the cache key; active rule sets are part
of the cache identity. With grouped dependency layers, conditional includes
cannot select files in the reserved <workdir>/.python tree.
Selected file symlinks must use a relative target and
resolve to another selected file inside the context; dangling, cyclic, absolute,
escaping or unselected targets are rejected. Directory links and Windows
junctions are never traversed; an include root through one is rejected unless
the root is already excluded. Automatic entrypoint discovery only reads a
selected pyproject.toml and rejects an excluded local script module; use an
explicit entrypoint if the intended module comes from elsewhere.