### Development Environment Setup Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md This setup is suitable for local development. It uses a plain password, trusts all connections, and maps the default PostgreSQL port to the host. ```bash docker run \ -e POSTGRES_PASSWORD=devpass \ -e POSTGRES_HOST_AUTH_METHOD=trust \ -p 5432:5432 \ postgres:18 ``` -------------------------------- ### Run Basic PostgreSQL Container Source: https://github.com/docker-library/postgres/blob/master/_autodocs/README.md Starts a PostgreSQL container with a specified password. This is the simplest way to get a PostgreSQL instance running. ```bash docker run \ -e POSTGRES_PASSWORD=mysecret \ postgres:18 ``` -------------------------------- ### Complete Output Example for PostgreSQL Versions Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md This example shows the full generated output for PostgreSQL versions 18 and 19, including tags, architectures, commit hashes, and directory structures. ```shell # this file is generated via https://github.com/docker-library/postgres/blob/abc123def456/generate-stackbrew-library.sh Maintainers: Tianon Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/postgres.git Tags: 19~beta1, 19~beta1-trixie Architectures: amd64, arm64, ppc64le GitCommit: def789abc123def789abc123def789abc123de Directory: 19/trixie Tags: 19~beta1-alpine, 19~beta1-alpine3.24 Architectures: amd64, arm64 GitCommit: def789abc123def789abc123def789abc123de Directory: 19/alpine3.24 Tags: 18.4, 18, latest, 18.4-trixie, 18-trixie, latest-trixie Architectures: amd64, arm64, ppc64le GitCommit: abc123def456789abc123def456789abc123de Directory: 18/trixie Tags: 18.4-bookworm, 18-bookworm, latest-bookworm Architectures: amd64, arm64, ppc64le GitCommit: abc123def456789abc123def456789abc123de Directory: 18/bookworm Tags: 18.4-alpine, 18-alpine, latest-alpine, 18.4-alpine3.24, 18-alpine3.24, latest-alpine3.24 Architectures: amd64, arm64, ppc64le GitCommit: abc123def456789abc123def456789abc123de Directory: 18/alpine3.24 Tags: 18.4-alpine3.23, 18-alpine3.23, latest-alpine3.23 Architectures: amd64, arm64 GitCommit: abc123def456789abc123def456789abc123de Directory: 18/alpine3.23 ``` -------------------------------- ### Architecture Support Example Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Illustrates how to determine the final supported architectures by intersecting base image and PostgreSQL package support. ```text Base image (debian:trixie): amd64, arm64, arm32v7, i386, mips64le, ppc64le, s390x PostgreSQL (trixie): amd64, arm64, ppc64le Result: amd64, arm64, ppc64le ``` -------------------------------- ### Start Temporary PostgreSQL Server Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Starts a temporary PostgreSQL server using a Unix socket for initialization purposes. This server is not network accessible and is managed using pg_ctl. ```bash docker_temp_server_start [postgres-args...] ``` -------------------------------- ### Example Invocations for Script Arguments Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md Demonstrates how the script argument handling works with no arguments and with additional arguments. ```bash # No arguments ./docker-ensure-initdb.sh # Becomes: postgres # With arguments ./docker-ensure-initdb.sh -c shared_buffers=256MB # Becomes: postgres -c shared_buffers=256MB ``` -------------------------------- ### Directory Output Structure Example Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Illustrates the directory structure created after running apply-templates.sh for a specific version (e.g., 18). ```bash 18/ ├── trixie/ │ ├── Dockerfile │ ├── docker-entrypoint.sh │ └── docker-ensure-initdb.sh ├── bookworm/ │ ├── Dockerfile │ ├── docker-entrypoint.sh │ └── docker-ensure-initdb.sh ├── alpine3.24/ │ ├── Dockerfile │ ├── docker-entrypoint.sh │ └── docker-ensure-initdb.sh └── alpine3.23/ ├── Dockerfile ├── docker-entrypoint.sh └── docker-ensure-initdb.sh ``` -------------------------------- ### Run PostgreSQL with Initialization Script Source: https://github.com/docker-library/postgres/blob/master/_autodocs/README.md Starts a PostgreSQL container and executes an SQL initialization script located at /docker-entrypoint-initdb.d/. The script is mounted as a volume. ```bash docker run \ -e POSTGRES_PASSWORD=secret \ -v ./schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro \ postgres:18 ``` -------------------------------- ### CI/CD Workflow Example Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Example of a CI workflow using update.sh to update specific PostgreSQL versions and checking for generated file changes. ```bash #!/bin/bash ./update.sh 18 19 # Update PostgreSQL 18 and 19 git diff --exit-code # Fail if generated files changed ``` -------------------------------- ### Setup Initial Database Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Creates the initial PostgreSQL database specified by the POSTGRES_DB environment variable. This function is idempotent and will only create the database if it does not already exist. ```bash docker_setup_db ``` -------------------------------- ### Custom Initialization Scripts Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md This example shows how to use the script with custom initialization scripts (e.g., SQL files) mounted into the `/docker-entrypoint-initdb.d/` directory. These scripts will be executed during initialization. ```bash docker run \ -e POSTGRES_PASSWORD=secret \ -v pgdata:/var/lib/postgresql \ -v ./schema.sql:/docker-entrypoint-initdb.d/01-schema.sql:ro \ -v ./data.sql:/docker-entrypoint-initdb.d/02-data.sql:ro \ postgres:18 \ /usr/local/bin/docker-ensure-initdb.sh ``` -------------------------------- ### Run PostgreSQL with Default Settings Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Use this command to start a PostgreSQL container with default settings. Ensure you set a password for the 'postgres' user. ```bash docker run \ -e POSTGRES_PASSWORD=mypass \ postgres:latest ``` -------------------------------- ### Example PostgreSQL Container Invocations Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Demonstrates various ways to run the PostgreSQL Docker container, including normal startup, with custom flags, executing custom commands, and requesting help. ```bash # Normal postgres start docker run postgres ``` ```bash # With flags docker run postgres -c shared_buffers=256MB ``` ```bash # Custom command docker run postgres /bin/bash ``` ```bash # Help docker run postgres --help ``` -------------------------------- ### Suite Override Example Usage Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/versions-sh.md Demonstrates how to use suite overrides to specify a Debian or Alpine release for a particular PostgreSQL version. ```bash debianSuites[14]='bullseye' # Use bullseye for PostgreSQL 14 alpineVersions[15]='3.21' # Use Alpine 3.21 for PostgreSQL 15 ``` -------------------------------- ### PostgreSQL Docker Image Manifest Example Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md This is an example of the output format generated by the script for the official-images library. It specifies maintainers, Git repository, tags, architectures, commit hash, and directory for different image variants. ```dockerfile # this file is generated via https://github.com/docker-library/postgres/blob/{COMMIT}/generate-stackbrew-library.sh Maintainers: Tianon Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/postgres.git Tags: 18.4, 18, latest, 18.4-trixie, 18-trixie, latest-trixie, 18.4-bookworm, 18-bookworm, latest-bookworm Architectures: amd64, arm64, ppc64le GitCommit: abc123def456... Directory: 18/trixie Tags: 18.4-alpine, 18-alpine, latest-alpine, 18.4-alpine3.24, 18-alpine3.24, latest-alpine3.24 Architectures: amd64, arm64, ppc64le GitCommit: abc123def456... Directory: 18/alpine3.24 ``` -------------------------------- ### Pre-release Tagging Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Examples of tag naming conventions for pre-release versions (beta) of PostgreSQL. ```text 19beta1 # Exact version only 19beta1-trixie # Explicit variant only 19beta1-alpine # Alpine variant only ``` -------------------------------- ### Example Output for Debian Variant Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Shows the expected output format for tags, architectures, git commit, and directory when processing a default Debian variant. ```text Tags: 18.4, 18, latest, 18.4-trixie, 18-trixie, latest-trixie Architectures: amd64, arm64, ppc64le GitCommit: abc123def456789abc123def456789abc123de Directory: 18/trixie ``` -------------------------------- ### Install NSS Wrapper in Dockerfile Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Install the NSS wrapper library in your Dockerfile if it's not already present in the base image. This is necessary for containers running with non-standard UIDs. ```dockerfile RUN apt-get install -y libnss-wrapper ``` ```dockerfile # or RUN apk add --no-cache libnss-wrapper ``` -------------------------------- ### Mount Initialization Scripts with Read-Only Permissions Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md When using a volume mount for initialization scripts, ensure proper permissions are set. This example mounts the scripts with read-only access. ```bash # If using volume mount, ensure proper permissions docker run \ -v ./init-scripts:/docker-entrypoint-initdb.d:ro \ postgres ``` -------------------------------- ### Avoid Conflicting Auth Arguments in Docker Run Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md This example demonstrates how to run a PostgreSQL container while avoiding conflicting authentication arguments that can lead to initialization errors. ```bash # Avoid conflicting auth arguments docker run \ -e POSTGRES_PASSWORD=secret \ # Don't add --auth-local, it conflicts with setup postgres ``` -------------------------------- ### Run PostgreSQL with Custom Database, User, and Password Source: https://github.com/docker-library/postgres/blob/master/_autodocs/README.md Configures a PostgreSQL container with a custom database name, user, and password. Useful for application-specific setups. ```bash docker run \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=myapp \ -e POSTGRES_USER=appuser \ postgres:18 ``` -------------------------------- ### Debian Dockerfile Generation Input Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Example JSON input for versions.json used to generate Debian-based Dockerfiles. ```json { "18": { "variant": "trixie", "trixie": { "version": "18.4-1.pgdg13+1", "arches": ["amd64", "arm64"] } } } ``` -------------------------------- ### Production Setup with High Availability Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md Use this configuration for production environments requiring high availability. It sets a password file, user, database, connection limits, buffer size, and authentication method. ```bash docker run \ -e POSTGRES_PASSWORD_FILE=/run/secrets/pgpassword \ -e POSTGRES_USER=pgapp \ -e POSTGRES_DB=appdb \ -e POSTGRES_INITDB_ARGS="-c max_connections=200 -c shared_buffers=512MB" \ -e POSTGRES_HOST_AUTH_METHOD=scram-sha-256 \ --secret pgpassword \ -v pgdata:/var/lib/postgresql/data \ postgres:18 ``` -------------------------------- ### Enforce Mode - CI Pipeline Setup Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md This script sets up and runs in 'enforce' mode, which is useful for CI pipelines. It will fail (exit code 1) if the database already exists. ```bash #!/bin/bash # Create symlink for enforce mode ln -s /usr/local/bin/docker-ensure-initdb.sh \ /usr/local/bin/docker-enforce-initdb.sh # Run enforcement - fails if database exists /usr/local/bin/docker-enforce-initdb.sh # Exits with code 1 if database is found ``` -------------------------------- ### Docker Compose Configuration for WAL Directory Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md Example of configuring the WAL directory using Docker Compose, demonstrating volume mounting for both data and WAL directories. ```yaml services: postgres: image: postgres:18 environment: POSTGRES_PASSWORD: secret POSTGRES_INITDB_WALDIR: /wal volumes: - pgdata:/var/lib/postgresql/data - waldata:/wal ``` -------------------------------- ### Install Decompression Tools in Dockerfile Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Install necessary decompression utilities like `xz-utils` or `zstd` within a custom Dockerfile. This is required if your base image lacks support for specific compressed file formats. ```dockerfile RUN apt-get install -y xz-utils # For .xz RUN apt-get install -y zstd # For .zst ``` -------------------------------- ### Kubernetes Init Container for Database Initialization Source: https://github.com/docker-library/postgres/blob/master/_autodocs/README.md An example of an init container in Kubernetes that uses the PostgreSQL image to initialize the database. It runs a specific entrypoint script. ```yaml initContainers: - name: init-db image: postgres:18 command: ["/usr/local/bin/docker-ensure-initdb.sh"] ``` -------------------------------- ### Dockerfile Template Processing Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md This example demonstrates how a Dockerfile template is processed with variable substitution to generate a final Dockerfile. It shows the input template, the variables used, and the resulting output. ```dockerfile FROM debian:{{ env.variant }}-slim ENV PG_VERSION {{ .[env.variant].version }} ``` ```text env.variant = trixie .[trixie].version = 18.4-1.pgdg13+1 ``` ```dockerfile FROM debian:trixie-slim ENV PG_VERSION 18.4-1.pgdg13+1 ``` -------------------------------- ### Example Tag Generation for Pre-release PostgreSQL Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md This shows the generated tags for a pre-release version of PostgreSQL (e.g., 19~beta1), including version-specific and base tags. ```text Tags: 19beta1, 19beta1-trixie ``` -------------------------------- ### Kubernetes PostgreSQL Init Container Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/README.md Example of an init container configuration for PostgreSQL in Kubernetes. It uses a specific image and a command to ensure the database is initialized. ```yaml # Init container approach initContainers: - name: init-db image: postgres:18 command: ["/usr/local/bin/docker-ensure-initdb.sh"] env: - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: password ``` -------------------------------- ### Run PostgreSQL Container Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/README.md Basic command to start a PostgreSQL container. Use environment variables to set the password, custom database name, or provide initialization scripts and Docker secrets. ```bash # Basic startup docker run -e POSTGRES_PASSWORD=secret postgres ``` ```bash # With custom database docker run \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=myapp \ postgres:18 ``` ```bash # With initialization script docker run \ -e POSTGRES_PASSWORD=secret \ -v ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro \ postgres ``` ```bash # With Docker Secrets docker run \ -e POSTGRES_PASSWORD_FILE=/run/secrets/password \ --secret password \ postgres ``` -------------------------------- ### Example Output for Alpine Variant Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Shows the expected output format for tags, architectures, git commit, and directory when processing a default Alpine variant. ```text Tags: 18.4-alpine, 18-alpine, latest-alpine, 18.4-alpine3.24, 18-alpine3.24, latest-alpine3.24 Architectures: amd64, arm64, ppc64le GitCommit: abc123def456789abc123def456789abc123de Directory: 18/alpine3.24 ``` -------------------------------- ### Docker Compose Configuration Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md This Docker Compose configuration demonstrates how to use the `docker-ensure-initdb.sh` script within a service definition. It ensures the database is initialized idempotently and then starts the PostgreSQL server. ```yaml version: '3.8' services: postgres: image: postgres:18 environment: POSTGRES_PASSWORD: secretpass POSTGRES_DB: myapp volumes: - pgdata:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro command: | sh -c '/usr/local/bin/docker-ensure-initdb.sh && postgres' volumes: pgdata: ``` -------------------------------- ### versions.json Schema Example Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md This JSON object illustrates the structure and content of the versions.json file, which defines metadata for different PostgreSQL versions and their base OS variants. ```json { "18": { "alpine": "3.24", "debian": "trixie", "trixie": { "version": "18.4-1.pgdg13+1", "arches": ["amd64", "arm64", "ppc64el"] }, "bookworm": { "version": "18.4-1.pgdg12+1", "arches": ["amd64", "arm64", "ppc64el"] }, "variants": [ "trixie", "bookworm", "alpine3.24", "alpine3.23" ], "version": "18.4", "sha256": "81a81ec695fb0c7901407defaa1d2f7973617154cf27ba74e3a7ab8e64436094", "major": 18 } } ``` -------------------------------- ### Example Tag Generation for Stable PostgreSQL Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md This shows the generated tags for a stable release of PostgreSQL (e.g., 18.4), including version-specific and base tags. ```text Tags: 18.4, 18, latest, 18.4-trixie, 18-trixie, latest-trixie ``` -------------------------------- ### Run PostgreSQL Container as Postgres User Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Start the PostgreSQL container directly as the 'postgres' user to ensure correct file permissions for the PGDATA directory. ```bash docker run --user postgres \ -e POSTGRES_PASSWORD=secret \ -v pgdata:/var/lib/postgresql/data \ postgres ``` -------------------------------- ### Testing Generated PostgreSQL Images Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md Build a specific PostgreSQL variant, run it, and validate its structure using container-structure-test. Ensure you have Docker and container-structure-test installed. ```bash # Build specific variant docker build -t postgres:18-test 18/trixie/ # Test image docker run -e POSTGRES_PASSWORD=test postgres:18-test # Validate with container structure tests ./container-structure-test test --image postgres:18-test config.yaml ``` -------------------------------- ### Conditional Logic in Dockerfile Templates Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Implement version-specific commands using conditional syntax. This example checks if the current version is 14, 15, or 16, and conditionally executes a command. ```dockerfile {{ if env.version | IN("14", "15", "16") then ( RUN set -eux; ln -svf gosu /usr/local/bin/su-exec {{ ) else "" end }} ``` -------------------------------- ### Main Orchestration Function for PostgreSQL Container Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md The primary function that orchestrates the PostgreSQL container startup flow. It handles flag-based invocations, environment setup, initialization, and server startup. ```bash _main [args...] ``` -------------------------------- ### Customize PostgreSQL Initialization Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/README.md Demonstrates how to prepare SQL and shell scripts for custom PostgreSQL database initialization. These scripts are then mounted into the container's initialization directory. ```bash # SQL script cat > /tmp/init.sql <<'EOF' CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL ); EOF ``` ```bash # Shell script cat > /tmp/setup.sh <<'EOF' #!/bin/bash echo "Setting up database..." EOF ``` ```bash # Use in container docker run \ -e POSTGRES_PASSWORD=secret \ -v /tmp/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro \ -v /tmp/setup.sh:/docker-entrypoint-initdb.d/02-setup.sh:ro \ postgres ``` -------------------------------- ### Get Directory Commit Hash Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Returns the most recent git commit that modified a Dockerfile or files it copies from. It extracts COPY instructions, filters out --from references, and then gets the commit for the Dockerfile and copied files. ```bash dirCommit() { local dir="$1"; shift ( cd "$dir" files="$( git show HEAD:./Dockerfile | awk ' toupper($1) == "COPY" { for (i = 2; i < NF; i++) { if ($i ~ /^--from=/) { next } print $i } } ' )" fileCommit Dockerfile $files ) } ``` -------------------------------- ### Process Initialization Files Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Executes initialization scripts and SQL files located in the /docker-entrypoint-initdb.d/ directory. Supports .sh, .sql, .sql.gz, .sql.xz, and .sql.zst files. ```bash docker_process_init_files [file ...] ``` -------------------------------- ### Non-Default Alpine Tagging Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Examples of tag naming conventions for a non-default Alpine variant (3.23) of PostgreSQL. ```text 18.4-alpine3.23 18-alpine3.23 latest-alpine3.23 ``` -------------------------------- ### Add /docker-entrypoint-initdb.d Directory to Dockerfile Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md If the `/docker-entrypoint-initdb.d/` directory is missing in a custom Docker image, add this command to your Dockerfile to create it. ```bash # If missing in custom image, add to Dockerfile RUN mkdir -p /docker-entrypoint-initdb.d ``` -------------------------------- ### Default Alpine Tagging Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Examples of tag naming conventions for the default Alpine variant (3.24) of PostgreSQL. ```text 18.4-alpine # Major + alpine 18-alpine latest-alpine 18.4-alpine3.24 # Explicit version 18-alpine3.24 latest-alpine3.24 ``` -------------------------------- ### Generated Debian Dockerfile Output Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Example output of a generated Dockerfile for Debian, showing the inserted PG_VERSION. ```dockerfile # # NOTE: THIS DOCKERFILE IS GENERATED VIA "apply-templates.sh" # # PLEASE DO NOT EDIT IT DIRECTLY. # FROM debian:trixie-slim # ...rest of Dockerfile... ENV PG_VERSION 18.4-1.pgdg13+1 # ... ``` -------------------------------- ### Dockerfile COPY and ENTRYPOINT Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Shows how the docker-entrypoint.sh script is copied into the image and set as the ENTRYPOINT. ```dockerfile COPY docker-entrypoint.sh /usr/local/bin/ ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] ``` -------------------------------- ### Non-Default Debian Variant Tagging Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Examples of tag naming conventions for a non-default Debian variant (bookworm) of PostgreSQL. ```text 18.4-bookworm 18-bookworm latest-bookworm ``` -------------------------------- ### Generated Alpine Dockerfile Output Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Example output of a generated Dockerfile for Alpine, showing the inserted Alpine version. ```dockerfile FROM alpine:3.24 ``` -------------------------------- ### Mount Single SQL File for Initialization Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md Mount a single SQL initialization script directly into the container's init directory using a Docker volume. ```bash docker run \ -v ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro \ postgres ``` -------------------------------- ### Default Variant Tagging (Debian Latest) Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Examples of tag naming conventions for the default Debian variant (trixie) of PostgreSQL. ```text 18.4 # Exact version, default variant 18 # Major version, default variant (stable only) latest # Latest release 18.4-trixie # Explicit variant 18-trixie # Major version + variant latest-trixie # Latest + variant ``` -------------------------------- ### View PostgreSQL Container Logs Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md View the full startup logs of a PostgreSQL container to diagnose initialization or connection issues. ```bash # View full startup logs docker logs container-name ``` -------------------------------- ### Test Initialization Script in Container Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Run an initialization script within a temporary PostgreSQL container to test its execution. This mounts the script read-only into the entrypoint directory. ```bash docker run \ -v ./script.sh:/docker-entrypoint-initdb.d/script.sh:ro \ postgres bash /docker-entrypoint-initdb.d/script.sh ``` -------------------------------- ### Defining and Using a Template Variable Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Define a template variable using `def` and then interpolate it. This example extracts the Alpine version number from the variant string. ```dockerfile {{ def alpine_version: env.variant | ltrimstr("alpine") -}} FROM alpine:{{ alpine_version }} ``` -------------------------------- ### Copying InitDB Script to Docker Image Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md Copy the docker-entrypoint.sh and docker-ensure-initdb.sh scripts into the Docker image's binary path. Both scripts are generated from the same source template. ```dockerfile COPY docker-entrypoint.sh docker-ensure-initdb.sh /usr/local/bin/ ``` -------------------------------- ### Make Initialization Script Executable Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Ensure that initialization scripts in `/docker-entrypoint-initdb.d/` have execute permissions. This is a common fix for shell script syntax errors. ```bash chmod +x /docker-entrypoint-initdb.d/setup.sh ``` -------------------------------- ### In-Place PostgreSQL Upgrade with pg_upgrade Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Perform an in-place upgrade of PostgreSQL data using `pg_upgrade`. This requires both PostgreSQL 17 and 18 to be installed on the same machine. ```bash # For in-place upgrade with existing data # Requires both PostgreSQL 17 and 18 on same machine pg_upgrade \ --old-bindir /usr/lib/postgresql/17/bin \ --new-bindir /usr/lib/postgresql/18/bin \ --old-datadir /var/lib/postgresql/17/docker \ --new-datadir /var/lib/postgresql/18/docker \ --link ``` -------------------------------- ### Mount Entire Directory of Scripts for Initialization Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md Mount an entire directory containing multiple initialization scripts into the container's init directory using a Docker volume. ```bash docker run \ -v ./init-scripts:/docker-entrypoint-initdb.d:ro \ postgres ``` -------------------------------- ### Initialize PostgreSQL Database Directory Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Initializes a new PostgreSQL data directory using initdb. It creates system databases, a superuser, and handles password securely via stdin. Supports custom initdb arguments and WAL directory configuration. ```bash docker_init_database_dir [initdb-args...] ``` -------------------------------- ### Verify Minimum Environment Variables Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Ensures essential environment variables like POSTGRES_PASSWORD are set for secure database initialization. Exits with an error if POSTGRES_PASSWORD is empty and authentication is not set to 'trust'. ```bash docker_verify_minimum_env ``` -------------------------------- ### Typical Usage from update.sh Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Shows the common usage path where update.sh calls both versions.sh and apply-templates.sh for a specific version. ```bash ./update.sh 18 ``` -------------------------------- ### Create Directories Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Creates directories, including parent directories if they do not exist. Fails if the filesystem is read-only. ```bash mkdir -p "$dir" ``` -------------------------------- ### Ensure Mode - Idempotent Initialization (First Run) Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md Use this command to initialize the PostgreSQL database on the first run. It's idempotent, meaning subsequent runs will detect an existing database and exit successfully. ```bash docker run \ -e POSTGRES_PASSWORD=mypass \ -v pgdata:/var/lib/postgresql \ postgres:18 \ /usr/local/bin/docker-ensure-initdb.sh ``` -------------------------------- ### Kubernetes Startup Probe for PostgreSQL Readiness Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md Configure a Kubernetes startup probe to check PostgreSQL readiness using `pg_isready`. This is an alternative to using an init container for database initialization. ```yaml containers: - name: postgres image: postgres:18 startupProbe: exec: command: - /usr/bin/pg_isready - -U - postgres initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 30 ``` -------------------------------- ### Debugging SQL Scripts Locally and in Container Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Test your initialization SQL scripts locally using `psql` or within a Docker container by mounting the script and checking logs. ```bash # Test script locally psql -U postgres -f init.sql # Or in container docker run \ -e POSTGRES_PASSWORD=secret \ -v ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro \ postgres \ # Script will execute during startup; check logs with docker logs ``` -------------------------------- ### Stop Temporary PostgreSQL Server Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Stops the temporary PostgreSQL server that was started for initialization. It uses pg_ctl with a fast shutdown signal and waits for the server to fully stop. ```bash docker_temp_server_stop ``` -------------------------------- ### Create PostgreSQL Data and Socket Directories Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Ensures that the PostgreSQL data directory ($PGDATA), socket directory (/var/run/postgresql), and WAL directory (if specified) are created with appropriate permissions. Handles ownership changes when run as root. ```bash docker_create_db_directories ``` -------------------------------- ### Run PostgreSQL with Custom initdb Arguments Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Pass custom arguments to the `initdb` command using `POSTGRES_INITDB_ARGS`. This allows for fine-grained control over database initialization parameters. ```bash docker run \ -e POSTGRES_PASSWORD=pass \ -e POSTGRES_INITDB_ARGS="-c shared_buffers=256MB -c work_mem=16MB" \ postgres:latest ``` -------------------------------- ### Verify /docker-entrypoint-initdb.d Directory Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Check if the `/docker-entrypoint-initdb.d/` directory exists within the PostgreSQL image. This is useful for troubleshooting initialization script errors. ```bash # Verify directory exists in image docker run postgres ls -la /docker-entrypoint-initdb.d/ ``` -------------------------------- ### Directory Structure Creation Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Creates the necessary directory hierarchy for each version and variant, following the pattern {VERSION}/{VARIANT}/. ```bash dir="$version/$variant" mkdir -p "$dir" ``` -------------------------------- ### Get File Commit Hash Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Returns the most recent git commit hash that modified specified files. This creates an immutable reference to the exact version of files used to generate an image. ```bash fileCommit() { git log -1 --format='format:%H' HEAD -- "$@" } ``` -------------------------------- ### Check for Help or Version Arguments Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Checks if the provided command-line arguments request help or version information. Returns an exit code of 0 if help/version is requested, and 1 otherwise. ```bash _pg_want_help [args...] ``` -------------------------------- ### Docker Compose Configuration for Initialization Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md Configure Docker Compose to mount initialization scripts into the PostgreSQL container. ```yaml services: postgres: image: postgres:18 environment: POSTGRES_PASSWORD: secret POSTGRES_DB: myapp volumes: - pgdata:/var/lib/postgresql/data - ./schema.sql:/docker-entrypoint-initdb.d/01-schema.sql:ro - ./data.sql:/docker-entrypoint-initdb.d/02-data.sql:ro ``` -------------------------------- ### Object Access and Array Joining in Dockerfile Templates Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Access nested fields within JSON objects and join array elements into a string. This example retrieves architecture information and formats it as a pipe-separated string. ```dockerfile {{ .[env.variant].arches | join(" | ") }} ``` -------------------------------- ### Kubernetes StatefulSet Configuration Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md This Kubernetes StatefulSet configuration uses an init container to run `docker-ensure-initdb.sh`, ensuring the PostgreSQL data directory is initialized before the main application container starts. It utilizes PersistentVolumeClaims for data storage. ```yaml apiVersion: apps/v1 kind: StatefulSet metadata: name: postgres spec: serviceName: postgres replicas: 1 selector: matchLabels: app: postgres template: metadata: labels: app: postgres spec: initContainers: - name: ensure-init image: postgres:18 command: ["/usr/local/bin/docker-ensure-initdb.sh"] env: - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-creds key: password volumeMounts: - name: data mountPath: /var/lib/postgresql/data containers: - name: postgres image: postgres:18 ports: - containerPort: 5432 env: - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-creds key: password volumeMounts: - name: data mountPath: /var/lib/postgresql/data volumeClaimTemplates: - metadata: name: data spec: accessModes: ["ReadWriteOnce"] resources: requests: storage: 10Gi ``` -------------------------------- ### Kubernetes Init Container Pattern for PostgreSQL Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md Use the docker-ensure-initdb.sh script within a Kubernetes init container to initialize the PostgreSQL data directory before the main application container starts. This ensures the database is ready when the main container begins. ```yaml apiVersion: v1 kind: Pod metadata: name: postgres-example spec: initContainers: - name: init-db image: postgres:18 command: ["/usr/local/bin/docker-ensure-initdb.sh"] env: - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: password - name: PGDATA value: /var/lib/postgresql/data volumeMounts: - name: postgres-storage mountPath: /var/lib/postgresql containers: - name: postgres image: postgres:18 command: ["postgres"] env: - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: password - name: PGDATA value: /var/lib/postgresql/data volumeMounts: - name: postgres-storage mountPath: /var/lib/postgresql volumes: - name: postgres-storage emptyDir: {} ``` -------------------------------- ### Run PostgreSQL with Trust Authentication (Development) Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-entrypoint.md Enable trust authentication for PostgreSQL. This is insecure and should only be used for development purposes. ```bash docker run \ -e POSTGRES_HOST_AUTH_METHOD=trust \ postgres:latest ``` -------------------------------- ### Generate Library File to Standard Output Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Run this command to output the generated library file to stdout, which is useful for verification before committing changes. ```bash ./generate-stackbrew-library.sh ``` -------------------------------- ### Generate Dockerfile using jq-template.awk Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md This command demonstrates how to use the jq-template.awk script with gawk to process a template file and generate a final Dockerfile. ```bash gawk -f jq-template.awk Dockerfile-debian.template > 18/trixie/Dockerfile ``` -------------------------------- ### Fetch Raw Package List Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/versions-sh.md Fetches the raw, uncompressed package list from the PostgreSQL Debian repository for a given suite, component, and architecture. It uses `curl` to download a bzip2-compressed file, then decompresses it. ```bash _raw_package_list SUITE COMPONENT ARCH ``` ```bash _raw_package_list trixie main amd64 # Fetches: http://apt.postgresql.org/pub/repos/apt/dists/trixie-pgdg/main/binary-amd64/Packages.bz2 ``` -------------------------------- ### Source Docker Entrypoint Script Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md This command sources the main docker-entrypoint.sh script to utilize its initialization functions. It's a prerequisite for the initialization sequence. ```bash source /usr/local/bin/docker-entrypoint.sh ``` -------------------------------- ### Run PostgreSQL in Foreground for Logs Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Run the PostgreSQL container in the foreground to see detailed startup messages directly in the console, aiding in debugging connection refused errors. ```bash # Run in foreground to see startup messages docker run \ -e POSTGRES_PASSWORD=secret \ postgres 2>&1 | head -100 ``` -------------------------------- ### Debug Init Container Issues Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Commands to debug hanging init containers. Check logs, execute commands within the pod, and verify disk space. ```bash # Check logs kubectl logs pod-name -c init-db ``` ```bash # Exec into pod kubectl exec -it pod-name -- /bin/bash ``` ```bash # Check disk space kubectl exec pod-name -- df -h ``` -------------------------------- ### Docker Pull Command for Manifest List Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Demonstrates how Docker pulls a multi-arch manifest list, which contains architecture-specific images. ```bash docker pull postgres:18.4 # Pulls multi-arch manifest containing: # - postgres:18.4-amd64 # - postgres:18.4-arm64 # - postgres:18.4-ppc64le ``` -------------------------------- ### Fetch Supported Architectures Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/versions-sh.md Determines the supported architectures for a given Debian suite by fetching and parsing the Release metadata from the PostgreSQL repository. It caches the results to minimize HTTP requests. ```bash fetch_suite_arches SUITE ``` -------------------------------- ### Iterate Through PostgreSQL Versions Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/generate-stackbrew-library.md Loops through sorted PostgreSQL versions, setting the 'version' environment variable for each. ```bash for version; do export version # Process version done ``` -------------------------------- ### Create New Version Directory Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md Use this command to create a new directory for a PostgreSQL version. Replace '{20}' with the desired version number. ```bash mkdir -p {20} ``` -------------------------------- ### _raw_package_list Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/versions-sh.md Fetches the raw, bzip2-compressed package list from the PostgreSQL Debian repository for a specified suite, component, and architecture. It decompresses the list and outputs it in Debian format. ```APIDOC ## _raw_package_list ### Description Fetches raw package list from PostgreSQL Debian repository. ### Method Not Applicable (Shell command) ### Endpoint Not Applicable ### Parameters #### Path Parameters Not Applicable #### Query Parameters Not Applicable #### Request Body Not Applicable ### Parameters - **SUITE** (string) - Required - Debian suite name (e.g., `trixie`, `bookworm`) - **COMPONENT** (string) - Required - Repository component (`main` or major version number) - **ARCH** (string) - Required - Architecture name (e.g., `amd64`, `arm64`, `ppc64el`) ### Request Example ```bash _raw_package_list trixie main amd64 ``` ### Response #### Success Response Uncompressed package list (Debian format) #### Response Example ``` Package: postgresql-18 Version: 18.4-1.pgdg13+1 Architecture: amd64 ... (rest of package metadata) ``` ### URL Pattern `http://apt.postgresql.org/pub/repos/apt/dists/{SUITE}-pgdg/{COMPONENT}/binary-{ARCH}/Packages.bz2` ### Process 1. Downloads bzip2-compressed Packages file 2. Decompresses with `bunzip2` 3. Outputs raw Debian package metadata ### Error Handling Uses `curl -fsSL` which exits on HTTP errors. ``` -------------------------------- ### Accessing Build Environment Variables Source: https://github.com/docker-library/postgres/blob/master/_autodocs/build-system.md Demonstrates how to access build environment variables within templates. These variables provide information about the PostgreSQL version, variant, and build details. ```plaintext env.version → Current PostgreSQL version env.variant → Current variant .[env.variant] → Variant metadata from versions.json .[env.variant].version → Package version .[env.variant].arches → Supported architectures ``` -------------------------------- ### Drop and Create Table Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Ensures a clean state by dropping an existing table before creating it. Use `CASCADE` if dependent objects exist. ```sql DROP TABLE IF EXISTS users CASCADE; CREATE TABLE users (id INT PRIMARY KEY); ``` -------------------------------- ### Script Copying Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md Copies essential entrypoint scripts (docker-entrypoint.sh and docker-ensure-initdb.sh) into each variant directory, preserving file permissions. ```bash cp -a docker-entrypoint.sh docker-ensure-initdb.sh "$dir/" ``` -------------------------------- ### Use Ensure Mode Instead of Enforce Source: https://github.com/docker-library/postgres/blob/master/_autodocs/errors.md Use `docker-ensure-initdb.sh` when a clean database is not strictly required or when the database might already exist. Use `docker-enforce-initdb.sh` for strict CI testing where a clean state is mandatory. ```bash # Instead of enforce (which fails if DB exists) /usr/local/bin/docker-ensure-initdb.sh ``` ```bash # enforce is for strict CI testing /usr/local/bin/docker-enforce-initdb.sh ``` -------------------------------- ### Version Selection Logic Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/apply-templates.md If no arguments are provided, this script processes all versions defined in versions.json. Custom versions can be specified as arguments. ```bash if [ "$#" -eq 0 ]; then versions="$(jq -r 'keys | map(@sh) | join(" ")' versions.json)" eval "set -- $versions" fi ``` -------------------------------- ### Ensure Mode - Idempotent Initialization (Second Run) Source: https://github.com/docker-library/postgres/blob/master/_autodocs/api-reference/docker-ensure-initdb.md This demonstrates the idempotent nature of the script. On a subsequent run, it detects the already initialized database and exits successfully without re-initializing. ```bash docker run \ -e POSTGRES_PASSWORD=mypass \ -v pgdata:/var/lib/postgresql \ postgres:18 \ /usr/local/bin/docker-ensure-initdb.sh # Output: note: database already initialized in '/var/lib/postgresql/data' ``` -------------------------------- ### Set Initial Database Name Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md Specify the name of the initial database to be created using the POSTGRES_DB environment variable. This database is created during initialization and skipped if it already exists. ```bash docker run \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=myapp \ postgres ``` -------------------------------- ### Compressed SQL File Execution (xz) Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md The container automatically decompresses and executes xz-compressed SQL files. ```bash xz init.sql -c > init.sql.xz # Container auto-decompresses and executes ``` -------------------------------- ### Compressed SQL File Execution (zstandard) Source: https://github.com/docker-library/postgres/blob/master/_autodocs/configuration.md The container automatically decompresses and executes zstandard-compressed SQL files. ```bash zstd init.sql -o init.sql.zst # Container auto-decompresses and executes ```