Docker image for postgres with Docker Compose in 2026

By Kate Baker
Docker image for postgres with Docker Compose in 2026

Running PostgreSQL in a container takes one line: docker run postgres. Running it in a way that survives a reboot, does not leak your password, does not quietly lose data on an upgrade, and can be restored at 3 AM takes a bit more thought.

This guide walks through the official docker image for postgres with Docker Compose, from picking a tag to a Compose file you would actually be comfortable putting on a server. It also covers the one change in PostgreSQL 18's image that trips up almost everyone copying older tutorials, and where a self-hosted container stops being the right call.

Which docker image for postgres should you use?

Use the Docker Official Image, published on Docker Hub simply as postgres. It is maintained by the Docker community together with PostgreSQL packagers, gets security rebuilds regularly, and is what virtually every tutorial and tool assumes.

The tags you will see:

TagWhat you getWhen to use it
postgres:18Latest 18.x minor release on DebianGood default
postgres:18.x (a specific minor)Exactly that minor versionReproducible builds, strict change control
postgres:18-alpine18.x on Alpine Linux, smaller imageWhen image size matters and you understand the caveats
postgres:latestWhatever the newest major is todayNever for anything with data you care about

Two rules that prevent most disasters:

  1. Always pin the major version. A major version bump (17 to 18) changes the on-disk format. If latest moves to a new major and your container restarts, PostgreSQL will refuse to start on the old data directory. Pinning postgres:18 still gets you minor updates, which are safe binary drop-ins.
  2. Do not switch between Debian and Alpine on the same data. Alpine uses musl libc, which sorts some text differently from glibc. Moving an existing data directory between the two can silently corrupt text indexes. Pick one and stay with it.

At the time of writing PostgreSQL 18 is the newest major supported by the image. New majors ship roughly every autumn, so check Docker Hub for the current list and the supported versions table on postgresql.org before you start a new project.

The PostgreSQL 18 volume change

If you copy a Compose file from a 2023 blog post, it probably mounts a volume like this:

volumes:
  - pgdata:/var/lib/postgresql/data

That was correct for images up to 17. Starting with the postgres:18 image, the data directory moved to a version-specific path (PGDATA is now /var/lib/postgresql/18/docker) and the image declares its volume at /var/lib/postgresql. The motivation is upgrades: with a version-specific subdirectory, old and new data directories can sit side by side on the same volume, which makes pg_upgrade --link practical.

For PostgreSQL 18 and later, mount the parent directory:

volumes:
  - pgdata:/var/lib/postgresql
If you mount the old /var/lib/postgresql/data path on 18, you are fighting the image's defaults. Either mount /var/lib/postgresql or explicitly set PGDATA and mount that. Do not leave it to luck.

If you already run 17 or earlier, nothing changes for you until you upgrade. Just be aware of it when you do.

A minimal Compose file for local development

For a laptop, this is enough:

# compose.yaml
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: devpassword
      POSTGRES_DB: app
    ports:
      - "127.0.0.1:5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql

volumes:
  pgdata:

Start it with docker compose up -d and connect with psql postgresql://app:devpassword@localhost:5432/app.

A few details worth noticing:

  • There is no version: key at the top. Docker Compose v2 ignores it and warns about it; the Compose Specification does not need it.
  • The port is bound to 127.0.0.1. Without that prefix, Docker publishes on all interfaces, and on Linux Docker's iptables rules can bypass host firewalls like ufw. That is how a lot of databases end up on public scanners.
  • A named volume (pgdata) is used rather than a bind mount. Named volumes avoid file permission headaches, especially on macOS and Windows.

Environment variables the image understands

The entrypoint script reads these on first start:

VariablePurpose
POSTGRES_PASSWORDSuperuser password. Required unless you set POSTGRES_HOST_AUTH_METHOD
POSTGRES_USERSuperuser name, defaults to postgres
POSTGRES_DBDefault database, defaults to the value of POSTGRES_USER
POSTGRES_INITDB_ARGSExtra arguments to initdb, for example --data-checksums
POSTGRES_HOST_AUTH_METHODAuth method for host connections. Never set it to trust outside throwaway local setups
PGDATAOverride the data directory location

Any of the POSTGRES_* variables can take a _FILE suffix (for example POSTGRES_PASSWORD_FILE) to read the value from a file. That is how you keep secrets out of your Compose file.

Important: these variables only take effect when the data directory is empty. Changing POSTGRES_PASSWORD later and restarting does nothing to the existing user. To change a password on a live database, run ALTER USER app WITH PASSWORD '...' inside psql.

Initialization scripts

Any *.sql, *.sql.gz, or *.sh files in /docker-entrypoint-initdb.d/ run once, in alphabetical order, when the database is first created:

-- initdb/01-extensions.sql
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
volumes:
  - pgdata:/var/lib/postgresql
  - ./initdb:/docker-entrypoint-initdb.d:ro

Use this for extensions and roles. Do not use it for your application schema. Schema belongs in your app's migration tool (Prisma, Alembic, Laravel migrations, and so on), because init scripts never run again once the volume exists.

A production-minded Compose setup

Here is a fuller setup for a single server: an app plus Postgres, with secrets, a health check, sensible tuning, and a restart policy.

# compose.yaml
services:
  db:
    image: postgres:18
    restart: unless-stopped
    environment:
      POSTGRES_USER: app
      POSTGRES_DB: app
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
      POSTGRES_INITDB_ARGS: "--data-checksums"
    secrets:
      - db_password
    volumes:
      - pgdata:/var/lib/postgresql
    shm_size: 256mb
    command:
      - postgres
      - -c
      - shared_buffers=512MB
      - -c
      - effective_cache_size=1536MB
      - -c
      - max_connections=100
      - -c
      - log_min_duration_statement=500
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s
    # no "ports:" - only the app on the internal network can reach it

  app:
    image: ghcr.io/you/app:latest
    restart: unless-stopped
    environment:
      DB_HOST: db
      DB_USER: app
      DB_NAME: app
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    depends_on:
      db:
        condition: service_healthy
    ports:
      - "8080:8080"

secrets:
  db_password:
    file: ./secrets/db_password.txt

volumes:
  pgdata:

What each piece is doing:

  • secrets: Compose mounts the file at /run/secrets/db_password inside the container. The password never appears in docker inspect environment output or in your Git history. Add secrets/ to .gitignore. Your app needs to read the file too; many frameworks support a _FILE convention, or you can read it at startup.
  • No published port on db: the app reaches the database at hostname db over the Compose network. Nothing outside the host can.
  • shm_size: Docker's default /dev/shm is 64 MB. PostgreSQL uses shared memory for parallel queries, and a small /dev/shm shows up as confusing "could not resize shared memory segment" errors under load.
  • command flags: shared_buffers around 25% of the memory you give the container and effective_cache_size around 50–75% are standard starting points. Adjust to your actual limits. For many settings, a mounted postgresql.conf is cleaner; -c flags are fine for a handful.
  • --data-checksums: detects silent storage corruption. It has to be set at initdb time, which is why it lives here. (PostgreSQL 18 enables checksums by default in initdb, so on 18 this flag is belt-and-braces; on older versions it matters.)
  • Health check + depends_on: condition: service_healthy: the app does not start until Postgres accepts connections, which removes a whole class of "connection refused on boot" crash loops.

Bring it up and confirm the database is healthy:

docker compose up -d
docker compose ps

Backups: the part everyone postpones

A volume is not a backup. If the disk dies, the volume goes with it. At minimum, take logical dumps on a schedule and copy them off the machine.

# Dump in PostgreSQL's custom format (compressed, supports selective restore)
docker compose exec -T db pg_dump -U app -Fc app > "backup-$(date +%F).dump"

# Restore into a fresh database
docker compose exec -T db pg_restore -U app -d app --clean --if-exists < backup-2026-11-24.dump

The -T flag disables TTY allocation so the binary dump is not mangled by the terminal.

Then:

  1. Run the dump from cron or a systemd timer.
  2. Upload it to object storage (any S3-compatible bucket works with aws s3 cp --endpoint-url ... or rclone).
  3. Keep a retention policy, for example 7 daily and 4 weekly.
  4. Test a restore at least once a month. An untested backup is a hope, not a backup.

For larger databases or point-in-time recovery, look at tools like pgBackRest or WAL-G, which stream write-ahead logs continuously. They are powerful and also a real operational commitment.

Upgrading major versions

Minor updates are easy: docker compose pull db && docker compose up -d db.

Major upgrades need a data migration. The simplest approach for small and medium databases:

  1. pg_dump (or pg_dumpall for roles too) from the old container.
  2. Start a new service on the new major with a new, empty volume.
  3. Restore the dump into it.
  4. Point the app at the new service, verify, then remove the old volume later.

The 18+ directory layout makes in-place pg_upgrade more practical too, but dump and restore is the method that is hardest to get wrong.

When to stop self-hosting the container

Everything above works, and plenty of teams run Postgres in Compose happily for years. But look at the list of responsibilities you just signed up for: backups and restore tests, off-site copies, monitoring disk space, security patches for the host, major upgrades, and being the person who gets paged when the disk fills up.

For a side project or a single internal tool, that is fine. For a SaaS with paying customers and one engineer, it is often the wrong place to spend your hours. A managed database takes over the parts that are boring right up until they are catastrophic.

A practical split many teams use:

  • Local development: the Compose setup above, with the same major version as production. This keeps dev/prod parity.
  • Production: a managed PostgreSQL instance, connected through a DATABASE_URL environment variable.

On Granite.so, for example, you create a managed database from the dashboard, attach its connection details to your app as environment variables, and deploy the app itself from your Git repo or Docker image, with S3-compatible storage available for uploads and backups next to it. Your app code does not change, since it still just reads a connection string. The Hobby plan is $9 per month with $15 of monthly usage credits included.

Whichever way you go, keep the local Compose file. It is still the fastest way to get a real PostgreSQL in front of your code.

Checklist

  • Image pinned to a major version (postgres:18), never latest
  • Volume mounted at /var/lib/postgresql on 18+, /var/lib/postgresql/data on 17 and older
  • Password supplied via POSTGRES_PASSWORD_FILE and Compose secrets
  • No port published in production, or bound to 127.0.0.1 locally
  • Health check plus depends_on: condition: service_healthy
  • shm_size raised above the 64 MB default
  • Scheduled pg_dump copied off the machine, restore tested
  • A written plan for the next major upgrade

Keep reading

More posts tagged “Tutorials”.
Be first in line for updates
and special pricing
Get early access to new features and exclusive discounts delivered straight to your inbox