### Minimal Installation with Slim Debian Bookworm Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md A Dockerfile example demonstrating a minimal installation pattern using the slim Python 3.12 Debian bookworm image. It installs only necessary application dependencies and Python packages. ```dockerfile FROM python:3.12-slim-bookworm # Install only application dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY app.py . CMD ["python", "app.py"] ``` -------------------------------- ### Variable Substitution Examples Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Demonstrates how environment variables and template logic are substituted into the Dockerfile. These examples show the output for different base images (bookworm and alpine). ```template {{ env.version }} ``` ```template {{ env.variant }} ``` ```template {{ is_alpine }} ``` ```template {{ is_slim }} ``` ```template {{ rcVersion }} ``` ```template {{ .version }} ``` -------------------------------- ### apply-templates.sh Usage Examples Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Demonstrates how to run the apply-templates.sh script to generate Dockerfiles. Supports generating for all versions or specific versions. ```bash # Generate Dockerfiles for all versions ./apply-templates.sh # Generate Dockerfiles for specific versions ./apply-templates.sh 3.12 3.13 # Generate Dockerfile for a single version ./apply-templates.sh 3.12 ``` -------------------------------- ### Example Output Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Shows a sample of the generated output for Python Docker images, including tags, commit hash, directory, and architectures. ```text # this file is generated via https://github.com/docker-library/python/blob/abc123def456/generate-stackbrew-library.sh Maintainers: Tianon Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/python.git Builder: buildkit Tags: 3.14.5, 3.14, 3, latest GitCommit: abc123def456 Directory: 3.14/bookworm Architectures: amd64, arm32v7, arm64v8, i386, ppc64le, s390x Tags: 3.14.5-bookworm, 3.14-bookworm, 3-bookworm, latest-bookworm GitCommit: abc123def456 Directory: 3.14/bookworm Architectures: amd64, arm32v7, arm64v8, i386, ppc64le, s390x ``` -------------------------------- ### Dockerfile Naming Convention Examples Source: https://github.com/docker-library/python/blob/master/_autodocs/configuration.md Provides examples of the naming convention for generated Dockerfiles, indicating the Python version, distribution variant, and specific image type (e.g., slim, alpine, windows). ```text 3.12/bookworm/Dockerfile 3.12/slim-bookworm/Dockerfile 3.12/alpine3.23/Dockerfile 3.13/windows/windowsservercore-ltsc2025/Dockerfile ``` -------------------------------- ### Architecture Detection Workflow Example Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md Demonstrates the steps involved in detecting and assigning architectures for a specific Docker image variant by querying parent image details. ```text FROM buildpack-deps:bookworm → Query buildpack-deps:bookworm architectures → Returns: amd64, arm32v7, arm64v8, i386, ppc64le, s390x → Assign to bookworm variant ``` -------------------------------- ### Multi-Stage Build Example Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md Demonstrates a multi-stage Docker build where build artifacts from a 'builder' stage are copied to a final, smaller image. ```dockerfile FROM python:3.12-slim as builder RUN pip install --user -r requirements.txt FROM python:3.12-slim COPY --from=builder /root/.local /root/.local ``` -------------------------------- ### Download Python Installer Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Downloads the Python installer executable from a given URL to the current directory. This command is part of the Windows installation process. ```powershell Invoke-WebRequest -Uri $url -OutFile 'python.exe' ``` -------------------------------- ### Version Sorting Example Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Illustrates the version sorting logic, which orders versions in descending order. ```javascript ["3.14", "3.13", "3.12", "3.11", "3.10"] ``` -------------------------------- ### Example Directory Structure for Python 3.12 Source: https://github.com/docker-library/python/blob/master/_autodocs/configuration.md Illustrates the directory structure created by `apply-templates.sh` for a specific Python version, showing Dockerfiles for various distribution variants. ```text 3.12/ ├── trixie/Dockerfile ├── slim-trixie/Dockerfile ├── bookworm/Dockerfile ├── slim-bookworm/Dockerfile ├── alpine3.23/Dockerfile └── alpine3.22/Dockerfile ``` -------------------------------- ### update.sh Usage Examples Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Shows how to execute the update.sh script, which orchestrates both version checking and Dockerfile generation. It can update all versions or specific ones. ```bash # Update everything (versions and Dockerfiles) ./update.sh # Update specific versions ./update.sh 3.12 3.13 # Update release candidate ./update.sh 3.15-rc ``` -------------------------------- ### versions.json Schema Example Source: https://github.com/docker-library/python/blob/master/_autodocs/configuration.md Illustrates the structure of the versions.json file, detailing metadata for a specific Python version series. ```json { "3.10": { "checksums": { "source": { "sha256": "hash_value" }, "windows": { "sha256": "hash_value" } }, "setuptools": { "version": "79.0.1" }, "variants": [ "trixie", "slim-trixie", "bookworm", "slim-bookworm", "alpine3.23", "alpine3.22" ], "version": "3.10.20" } } ``` -------------------------------- ### Handle Python Installer Errors Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Logs the exit code of the Python installer and displays the content of the most recent temporary file, which typically contains installer logs. This aids in diagnosing installation failures. ```powershell Write-Host 'Running python installer failed with exit code: {0}' Get-ChildItem $env:TEMP | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1 | Get-Content ``` -------------------------------- ### Declarative Configuration Example (versions.json) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This JSON structure defines the Python versions and variants to be maintained. It includes version details, checksums, setuptools information, and a list of variants. ```json { "VERSION": { "version": "FULL_VERSION", "checksums": { ... }, "setuptools": { ... }, "variants": ["variant1", "variant2", ...] } } ``` -------------------------------- ### Build for Multiple Architectures with Docker Buildx Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Example command to build a Docker image for multiple platforms using `docker buildx`. This is essential for distributing applications across different CPU architectures. ```bash # Build for multiple architectures docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest . ``` -------------------------------- ### Verify Python and Pip Installation Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Checks if the Python and pip installations were successful by running their version commands. This is a crucial step after the installation process to confirm everything is working as expected. ```powershell python --version pip --version ``` -------------------------------- ### Python Docker Image Tagging Examples Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md Illustrates how version aliases and variant suffixes are used to define Docker image tags for different Python versions and distributions. ```text 3.12, 3.12.13, 3, latest # All point to Python 3.12 full 3.12-slim, 3.12-slim-bookworm # Slim variants 3.12-alpine, 3.12-alpine3.23 # Alpine variants 3.12-windowsservercore-ltsc2025 # Windows ``` -------------------------------- ### Verify Python Installer Checksum Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Compares the SHA256 checksum of the downloaded Python installer with the expected checksum stored in the environment variable PYTHON_SHA256. This ensures the integrity of the downloaded file. ```powershell (Get-FileHash python.exe -Algorithm sha256).Hash -ne $env:PYTHON_SHA256 ``` -------------------------------- ### Install Python Dependencies on Alpine Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Installs runtime dependencies and then builds Python packages using a multi-stage build pattern to keep the final image small. This is ideal for microservices and resource-constrained environments. ```dockerfile RUN apk add --no-cache postgresql-client COPY requirements.txt . RUN apk add --no-cache --virtual .build-deps gcc musl-dev && \ pip install --no-cache-dir -r requirements.txt && \ apk del .build-deps COPY app.py . CMD ["python", "app.py"] ``` -------------------------------- ### Defining Custom Functions in Templates Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Provides examples of defining reusable functions like 'is_alpine', 'is_slim', 'rcVersion', 'should_pgp', and 'clean_apt' within the template preamble. ```jq def is_alpine: env.variant | startswith("alpine") ; def is_slim: env.variant | startswith("slim-") ; def rcVersion: env.version | rtrimstr("-rc") ; def should_pgp: rcVersion | IN("3.10", "3.11", "3.12", "3.13") ; def clean_apt: if env.variant | contains("bookworm") then "rm -rf /var/lib/apt/lists/*" else "apt-get dist-clean" end ; ``` -------------------------------- ### Docker Image Build Caching Example Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md Illustrates how Docker's layer caching works with RUN commands, emphasizing that changes in earlier layers invalidate cache for subsequent layers. ```dockerfile RUN apt-get update; apt-get install -y ... # Layer 1: cached if no change RUN ./configure --enable-optimizations # Layer 2: re-run if dependency changed RUN make -j $(nproc) # Layer 3: re-run if layer 2 changed ``` -------------------------------- ### Perform Silent Python Installation Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Installs Python silently on Windows using the downloaded installer. It configures the installation for all users, specifies the target directory, adds Python to the system PATH, and includes pip while excluding documentation and tests. ```powershell Start-Process python.exe -Wait -NoNewWindow -PassThru -ArgumentList @( '/quiet', 'InstallAllUsers=1', 'TargetDir=C:\Python', 'PrependPath=1', 'Shortcuts=0', 'Include_doc=0', 'Include_pip=1', 'Include_test=0' ) ``` -------------------------------- ### Create Symlinks for Python Binaries Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Creates symbolic links for common Python executables to ensure they are accessible in the PATH. This is typically done after a successful installation. ```bash ln -svT idle3 /usr/local/bin/idle ln -svT pip3 /usr/local/bin/pip ln -svT pydoc3 /usr/local/bin/pydoc ln -svT python3 /usr/local/bin/python ln -svT python3-config /usr/local/bin/python-config ``` -------------------------------- ### Sigstore Verification (Python 3.12+) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This command uses 'wget' and 'jq' to fetch and parse the Sigstore signature for a release, which is the preferred method for checksum verification starting from Python 3.12 due to its modern cryptographic bundles and machine-readable format. ```bash wget -qO- "$url.sigstore" | jq '.messageSignature.messageDigest' ``` -------------------------------- ### Construct Python Download URL Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Constructs the download URL for the Python Windows installer. It uses the specified version to form the path to the executable, ensuring the correct architecture (amd64) is targeted. ```powershell $url = 'https://www.python.org/ftp/python/{version}/python-{fullVersion}-amd64.exe' ``` -------------------------------- ### Alpine Build Dependencies Management Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This bash command shows how to install and remove build dependencies on Alpine systems using a named virtual package for easy cleanup. ```bash apk add --no-cache --virtual .build-deps [build-deps] # ... build Python ... apk del --no-network .build-deps ``` -------------------------------- ### Kubernetes Pod with Architecture Node Selector Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Example Kubernetes pod definition specifying an architecture. This ensures the pod is scheduled on nodes matching the required architecture, using a cross-platform Python image. ```yaml apiVersion: v1 kind: Pod metadata: name: python-app spec: nodeSelector: kubernetes.io/arch: arm64 # Ensure ARM64 node containers: - name: app image: python:3.12-alpine3.23 # Works on all architectures imagePullPolicy: IfNotPresent ``` -------------------------------- ### Aliases Map Configuration Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Defines built-in aliases for Python Docker image tags. This example shows how Python 3.14 is aliased. ```bash declare -A aliases=( [3.14]='3 latest' ) ``` -------------------------------- ### Remove Build Artifacts Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md After installation, these commands clean up the build directory and remove unnecessary files such as compiled Python bytecode (.pyc, .pyo) and static libraries (.a) to minimize image size. ```bash rm -rf /usr/src/python find /usr/local -depth '(' \ -type d -a '(' -name test -o -name tests -o -name idle_test ')' \ -o -type f -a '(' -name '*.pyc' -o -name '*.pyo' -o -name 'libpython*.a' ')' \ ')' -exec rm -rf '{}' '+' ``` -------------------------------- ### Dockerfile for Alpine Linux Python Image Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md A basic Dockerfile to start with the Python 3.12 Alpine 3.23 image. This variant is known for its minimal size and fast startup, suitable for resource-constrained environments. ```dockerfile FROM python:3.12-alpine3.23 ``` -------------------------------- ### Python versions.json Data Structure Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Example JSON structure for versions.json, which provides versioning, checksums, and variant information for Python builds. This data is used by the Dockerfile templates. ```json { "version": "3.12.13", "checksums": { "source": { "sha256": "c08bc65a81971c1dd5783182826503369466c7e67374d1646519adf05207b684" }, "windows": { "sha256": "3c9c81d80f91c002ced86d645422d81432c68c7d9b6b0e974768ca2e449a4d00" } }, "setuptools": { "version": "79.0.1" }, "variants": [ "trixie", "slim-trixie", "bookworm", "slim-bookworm", "alpine3.23", "alpine3.22" ] } ``` -------------------------------- ### Mapping and Concatenating Array Elements Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Maps an expression over array elements and concatenates the results. This example produces multiple lines, one for each element in the array. ```jq {{ map( {{ . }} \ ) | add }} ``` -------------------------------- ### Debian Build Dependencies Management Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This bash script demonstrates how to manage build dependencies on Debian-based systems. It saves the current apt-mark state, installs build dependencies, builds Python, and then cleans up by removing only the auto-installed build dependencies. ```bash savedAptMark="$(apt-mark showmanual)" # Save current state apt-get update apt-get install -y --no-install-recommends [build-deps] # ... build Python ... apt-mark auto '.*' > /dev/null # Mark all as auto-installed apt-mark manual $savedAptMark # Restore original manual packages apt-get purge -y --auto-remove # Remove auto-installed packages ``` -------------------------------- ### Set Default Command for Python Container Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Sets the default command to execute when a container based on this Dockerfile starts. In this case, it defaults to running the Python interpreter. ```dockerfile CMD ["python"] ``` -------------------------------- ### Runtime Dependency Detection (Alpine) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This bash command uses `scanelf` to identify ELF dependencies for executable files in `/usr/local`. It's part of the process to determine and install only the required runtime packages on Alpine. ```bash find /usr/local -type f -executable -not \( -name '*tkinter*' \) -exec scanelf --needed --nobanner --format '%n#p' '{}' ';' ``` -------------------------------- ### Conditional Logic in Templates (Version Prefix Check) Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Shows how to use the `startswith` function to conditionally output 'new' or 'old' based on the Python version. ```jq {{ if (version | startswith("3.1")) then "new" else "old" end }} ``` -------------------------------- ### Get File Commit Hash Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Retrieves the Git commit hash for the most recent modification of specified files. ```bash git log -1 --format='format:%H' HEAD -- "$@" ``` -------------------------------- ### String Prefix and Containment Checks Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Shows how to use 'startswith' to check for string prefixes and 'contains' to check for substrings, useful for conditional logic based on string values. ```jq {{ env.variant | startswith("alpine") }} {{ env.variant | startswith("slim-") }} {{ env.variant | contains("bookworm") }} ``` -------------------------------- ### update.sh Equivalent Commands Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Illustrates that running update.sh is equivalent to sequentially executing versions.sh and apply-templates.sh with the same arguments. ```bash ./versions.sh 3.12 3.13 ./apply-templates.sh 3.12 3.13 ``` -------------------------------- ### SPDX Manifest Verification (Fallback) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md As a fallback method, this command downloads and parses the SPDX manifest to verify CPython release integrity. It selects packages named 'CPython' and is a more human-readable but slower alternative to Sigstore. ```bash wget -qO- "$url.spdx.json" | jq '.packages[] | select(.name == "CPython")' ``` -------------------------------- ### Parallel Build with Make Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This snippet demonstrates how to use 'make' with the '-j' flag to enable parallel compilation, utilizing all available CPU cores for faster build times. It first determines the number of available processors. ```bash nproc="$(nproc)" make -j "$nproc" ``` -------------------------------- ### Multi-Stage Build for Small Alpine Images Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md A recommended pattern for Alpine Linux to minimize image size by separating build dependencies from the final runtime image. This approach ensures only necessary components are included in the production image. ```dockerfile FROM python:3.12-alpine3.23 as builder RUN apk add --no-cache --virtual .build-deps gcc musl-dev COPY requirements.txt . RUN pip install --user --no-cache-dir -r requirements.txt FROM python:3.12-alpine3.23 COPY --from=builder /root/.local /root/.local ENV PATH=/root/.local/bin:$PATH COPY app.py . CMD ["python", "app.py"] ``` -------------------------------- ### Template Processing Workflow Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Outlines the step-by-step process for generating Dockerfiles using the template system, from template selection to final output. ```text 1. apply-templates.sh selects template ├─ Windows variants → Dockerfile-windows.template └─ Linux variants → Dockerfile-linux.template 2. Environment variables exported ├─ export version="3.12" ├─ export variant="bookworm" ├─ export windowsVariant="servercore" (Windows only) └─ export windowsRelease="ltsc2022" (Windows only) 3. versions.json loaded as JSON context └─ . = JSON object for version "3.12" 4. jq-template.awk processes template ├─ Parses {{ }} syntax ├─ Evaluates jq expressions ├─ Resolves conditionals ├─ Substitutes variables └─ Strips excess whitespace 5. Output piped to Dockerfile ├─ Prepend generation warning └─ Write to VERSION/VARIANT/Dockerfile ``` -------------------------------- ### Dockerfile with Slim Bookworm Base Image Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md A sample Dockerfile using a specific Python variant. This demonstrates how to specify a base image for your application, leveraging pre-built, optimized images. ```dockerfile FROM python:3.12-slim-bookworm # Your application code ``` -------------------------------- ### Conditional Dockerfile FROM Instruction Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Uses if-then-else logic to dynamically set the base image (FROM instruction) based on whether the variant is alpine, slim, or a standard buildpack-deps. ```jq {{ if is_alpine then ( FROM alpine:{{ env.variant | ltrimstr("alpine") }} ) elif is_slim then ( FROM debian:{{ env.variant | ltrimstr("slim-") }}-slim ) else ( FROM buildpack-deps:{{ env.variant }} ) end }} ``` -------------------------------- ### Generate Dockerfiles from Templates Source: https://github.com/docker-library/python/blob/master/_autodocs/README.md Generates Dockerfiles based on version templates. Specify the versions to generate as arguments. ```bash # Generate Dockerfiles from templates ./apply-templates.sh [VERSION...] ``` -------------------------------- ### Refresh Environment PATH Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Updates the system's PATH environment variable to include the newly installed Python directory. This ensures that Python commands can be executed from any location in the command prompt. ```powershell $env:PATH = [Environment]::GetEnvironmentVariable('PATH', [EnvironmentVariableTarget]::Machine) ``` -------------------------------- ### Adding New Build Dependencies (Alpine vs. Debian Slim) Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Illustrates how to conditionally add build dependencies based on whether the image is Alpine or Debian Slim. This snippet should be edited around line 95 of `Dockerfile-linux.template`. ```jq def build_deps: [ if is_alpine then # Alpine packages here "new-alpine-package", else if is_slim then # Debian slim packages here "new-debian-package", else empty end, end ] -}} ``` -------------------------------- ### Base Image Selection Logic Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Selects the appropriate base image (Alpine, Debian Slim, or Debian Full) based on the `is_alpine` and `is_slim` template variables. ```dockerfile {{ if is_alpine then ( -}} FROM alpine:{{ env.variant | ltrimstr("alpine") }} {{ ) elif is_slim then ( -}} FROM debian:{{ env.variant | ltrimstr("slim-") }}-slim {{ ) else ( -}} FROM buildpack-deps:{{ env.variant }} {{ ) end }} ``` -------------------------------- ### Recommended Docker Tag Selection Strategy Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Guidance on choosing the most specific Docker tag for your Python application based on use case. This helps in balancing stability, size, and feature requirements. ```text Production, latest patches | Major.minor | `python:3.12` Pin exact version | Full version | `python:3.12.13` Stable, lightweight | Slim major.minor | `python:3.12-slim` Minimal size | Alpine major.minor | `python:3.12-alpine` Development | Full variant | `python:3.12-bookworm` Windows specific | Windows variant | `python:3.12-windowsservercore-ltsc2025` ``` -------------------------------- ### Full Python Docker Image Update Source: https://github.com/docker-library/python/blob/master/_autodocs/configuration.md A wrapper script that sequentially executes `versions.sh` and `apply-templates.sh` with the same arguments. This performs a complete refresh of version metadata and generated Dockerfiles. ```bash ./update.sh [VERSION...] ``` -------------------------------- ### Discover CPython Releases via Python.org FTP Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This command fetches the directory listing from the Python.org FTP server to discover available Python releases. It serves as a backup method for version detection, complementing GitHub checks. ```bash wget -qO- 'https://www.python.org/ftp/python/' | grep ' library ``` -------------------------------- ### Update and Generate Dockerfiles Source: https://github.com/docker-library/python/blob/master/_autodocs/README.md Performs both version metadata update and Dockerfile generation. Specify the versions to update as arguments. ```bash # Do both at once ./update.sh [VERSION...] ``` -------------------------------- ### Template Selection Logic Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Determines which Dockerfile template to use based on the variant type. Processes Windows variants separately from Linux variants. ```bash if variant starts with "windows/" then use Dockerfile-windows.template extract windowsVariant (e.g., "servercore", "nanoserver") extract windowsRelease (e.g., "ltsc2022") else use Dockerfile-linux.template fi ``` -------------------------------- ### Debug Template Processing with set -x Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Enables shell debugging to trace the execution of the `apply-templates.sh` script and template expansion. This can also be enabled within `jq-template.awk` if supported. ```bash { generated_warning gawk -v DEBUG=1 -f "$jqt" "$template" # If jq-template.awk supports it } > "$version/$dir/Dockerfile" ``` -------------------------------- ### Generate Stackbrew Library Metadata Source: https://github.com/docker-library/python/blob/master/_autodocs/configuration.md Outputs Docker image metadata in the official-images library format to standard output. It sorts versions, includes all variants, and determines commit hashes, architecture support, and tag aliases. If no versions are specified, it generates metadata for all versions. ```bash ./generate-stackbrew-library.sh [VERSION...] ``` -------------------------------- ### Accessing Data from versions.json in Templates Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Shows how to access top-level fields from the versions.json data within the jq template. ```jq {{ .version }} {{ .checksums.source.sha256 }} {{ .checksums.windows.sha256 }} {{ .setuptools.version }} {{ .variants }} ``` -------------------------------- ### Run Full Debian Bookworm Python Image Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Launches an interactive bash session within the full Python 3.12 Debian bookworm Docker image. This variant includes a comprehensive development environment. ```bash docker run -it python:3.12-bookworm /bin/bash ``` -------------------------------- ### Base Image Selection for Windows Dockerfile Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Specifies the base Windows image for a Docker container, using variables for the Windows variant and release. Supported variants include 'servercore' and 'nanoserver', with releases like 'ltsc2025' or 'ltsc2022'. ```dockerfile FROM mcr.microsoft.com/windows/{{ env.windowsVariant }}:{{ env.windowsRelease }} ``` -------------------------------- ### Conditional Logic in Templates (Major Version Extraction) Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Demonstrates extracting the major version number from a version string using `split` and array indexing. ```jq {{ version | split(".") | .[0] }} ``` -------------------------------- ### versions.json Structure Source: https://github.com/docker-library/python/blob/master/_autodocs/README.md JSON document listing Python version details, including version number, checksums, setuptools version, and base image variants. ```json { "VERSION": { "version": "X.Y.Z", // Full Python version "checksums": { ... }, // SHA256 hashes for verification "setuptools": { "version": "..." }, // Setuptools version to include "variants": [...] // List of base image variants } } ``` -------------------------------- ### Generate Docker Hub Library Metadata Source: https://github.com/docker-library/python/blob/master/_autodocs/README.md Generates metadata for the Docker Hub Python library. Output is redirected to 'library'. ```bash # Generate Docker Hub library metadata ./generate-stackbrew-library.sh [VERSION...] > library ``` -------------------------------- ### GPG Signature Verification (Legacy) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This command sequence verifies GPG signatures for tarballs, used as a legacy method for Python versions 3.10-3.13. It first imports the GPG key and then verifies the signature against the tarball. ```bash gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys "$GPG_KEY" gpg --batch --verify python.tar.xz.asc python.tar.xz ``` -------------------------------- ### Output Format Structure Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Defines the structure for outputting Docker image metadata in the official-images library format. ```text # this file is generated via https://github.com/docker-library/python/blob/COMMIT_HASH/generate-stackbrew-library.sh Maintainers: Name (@username), Name (@username) GitRepo: https://github.com/docker-library/python.git Builder: buildkit ENTRY ``` ```text Tags: tag1, tag2, tag3, ... GitCommit: COMMIT_HASH Directory: VERSION/VARIANT Architectures: arch1, arch2, arch3, ... ``` -------------------------------- ### Accessing Template Variables Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Demonstrates how to access fields and nested fields from the template context. Use conditional checks for optional fields to handle cases where they might be missing. ```jq {{ .version }} # Field access {{ .checksums.source.sha256 }} # Nested field access {{ if .setuptools then ... end }} # Conditional on field existence ``` -------------------------------- ### Runtime Dependency Detection (Debian/Debian-slim) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This bash command uses `ldd` to find dynamic library dependencies for executable files in `/usr/local`. It filters out local dependencies and is used to determine necessary runtime packages. ```bash find /usr/local -type f -executable -not \( -name '*tkinter*' \) -exec ldd '{}' ';' \ | awk '/=>/ { so = $(NF-1); if (index(so, "/usr/local/") == 1) { next }; ... }' ``` -------------------------------- ### Multi-Stage Build with Rpath Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This multi-stage build process compiles Python, removes an intermediate executable, and then performs a final build with an rpath. The rpath ensures the Python executable can find its shared library relative to its location. ```bash make -j "$nproc" rm python make -j "$nproc" \ "LDFLAGS=${LDFLAGS:-} -Wl,-rpath='$$ORIGIN/../lib'" \ python ``` -------------------------------- ### Update Dockerfile Templates Script Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md Workflow for updating Dockerfile templates, regenerating all Dockerfiles, and committing the changes. ```bash # 1. Edit template (e.g., add new build dependency) vim Dockerfile-linux.template # 2. Regenerate all Dockerfiles ./apply-templates.sh # 3. Review all changes git diff # 4. Commit git commit -am "Add new build dependency to all versions" # 5. Push git push origin main ``` -------------------------------- ### CPython Optimization Flags (Non-Alpine) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This command enables profile-guided optimization (PGO) during the CPython build process on non-Alpine variants. This can result in faster Python binaries but increases build time. ```bash ./configure --enable-optimizations ``` -------------------------------- ### Generate Metadata for Specific Versions Source: https://github.com/docker-library/python/blob/master/_autodocs/scripts-reference.md Generates Docker image metadata for specified Python versions. The output is redirected to a file named 'library'. ```bash # Generate metadata for specific versions ./generate-stackbrew-library.sh 3.12 3.13 > library ``` -------------------------------- ### Accessing Environment Variables in Templates Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Demonstrates how to access environment variables within the jq template syntax using the 'env' object. ```jq {{ env.version }} {{ env.variant }} {{ env.windowsVariant }} {{ env.windowsRelease }} ``` -------------------------------- ### Python Docker Image Version Aliases Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Commonly used tags for specifying Python versions and variants in Docker. These aliases simplify image selection for different needs, from exact versions to major versions and specific OS variants. ```text 3.12.13 # Full version 3.12 # Major.minor version 3 # Major version only latest # Latest Python version (if 3.x is current) 3.12.13-bookworm # Full version + variant 3.12-bookworm # Major.minor + variant 3-bookworm latest-bookworm 3.12-slim # Common names for slim variants 3.12-slim-bookworm # Full name 3.12-alpine # Common names for Alpine 3.12-alpine3.23 # Full version 3.12-windowsservercore # Windows variant ``` -------------------------------- ### Python Docker Image Variant Decision Tree Source: https://github.com/docker-library/python/blob/master/_autodocs/docker-image-variants.md Use this decision tree to select the optimal Python Docker image variant based on your project's needs, such as OS, size, and package freshness. ```text Start │ ├─ Windows container? │ └─ YES → Use windowsservercore-ltsc2025 or ltsc2022 │ └─ Linux container? ├─ Minimal size critical? (Serverless, scaling) │ ├─ YES → alpine3.23 or alpine3.22 │ │ (50-80 MB, but packages from source) │ └─ NO │ ├─ Production, small size important? │ │ ├─ YES → slim-bookworm or slim-trixie │ │ │ (370 MB, pre-built packages) │ │ └─ NO │ │ ├─ Development/CI needed? │ │ │ ├─ YES → bookworm or trixie │ │ │ │ (850 MB, full tools) │ │ │ └─ NO → slim-bookworm │ │ │ │ │ ├─ Latest packages needed? │ │ │ ├─ YES → trixie variant │ │ │ └─ NO → bookworm variant │ │ │ │ │ └─ Python 3.14+? │ │ ├─ YES (all trixie) │ │ └─ NO → bookworm/trixie available ``` -------------------------------- ### Frame Pointer Support Configuration (x86_64, aarch64) Source: https://github.com/docker-library/python/blob/master/_autodocs/build-system.md This bash snippet configures CFLAGS to include `-fno-omit-frame-pointer` and `-mno-omit-leaf-frame-pointer` for x86_64 and aarch64 architectures, enabling performance profiling with Linux perf. ```bash EXTRA_CFLAGS="${EXTRA_CFLAGS:-} -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer" ``` -------------------------------- ### Piping Output Between Filters Source: https://github.com/docker-library/python/blob/master/_autodocs/template-system.md Illustrates the use of the pipe operator '|' to pass the output of one jq expression as the input to another, enabling chained operations. ```jq {{ env.variant | startswith("alpine") }} {{ .version | rtrimstr("-rc") }} {{ build_deps | if length > 0 then ... end }} ```