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:
| Tag | What you get | When to use it |
|---|---|---|
postgres:18 | Latest 18.x minor release on Debian | Good default |
postgres:18.x (a specific minor) | Exactly that minor version | Reproducible builds, strict change control |
postgres:18-alpine | 18.x on Alpine Linux, smaller image | When image size matters and you understand the caveats |
postgres:latest | Whatever the newest major is today | Never for anything with data you care about |
Two rules that prevent most disasters:
- Always pin the major version. A major version bump (17 to 18) changes the on-disk format. If
latestmoves to a new major and your container restarts, PostgreSQL will refuse to start on the old data directory. Pinningpostgres:18still gets you minor updates, which are safe binary drop-ins. - 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/dataThat 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/postgresqlIf you mount the old/var/lib/postgresql/datapath on 18, you are fighting the image's defaults. Either mount/var/lib/postgresqlor explicitly setPGDATAand 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 likeufw. 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:
| Variable | Purpose |
|---|---|
POSTGRES_PASSWORD | Superuser password. Required unless you set POSTGRES_HOST_AUTH_METHOD |
POSTGRES_USER | Superuser name, defaults to postgres |
POSTGRES_DB | Default database, defaults to the value of POSTGRES_USER |
POSTGRES_INITDB_ARGS | Extra arguments to initdb, for example --data-checksums |
POSTGRES_HOST_AUTH_METHOD | Auth method for host connections. Never set it to trust outside throwaway local setups |
PGDATA | Override 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. ChangingPOSTGRES_PASSWORDlater and restarting does nothing to the existing user. To change a password on a live database, runALTER USER app WITH PASSWORD '...'insidepsql.
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:roUse 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_passwordinside the container. The password never appears indocker inspectenvironment output or in your Git history. Addsecrets/to.gitignore. Your app needs to read the file too; many frameworks support a_FILEconvention, or you can read it at startup.- No published port on
db: the app reaches the database at hostnamedbover the Compose network. Nothing outside the host can. shm_size: Docker's default/dev/shmis 64 MB. PostgreSQL uses shared memory for parallel queries, and a small/dev/shmshows up as confusing "could not resize shared memory segment" errors under load.commandflags:shared_buffersaround 25% of the memory you give the container andeffective_cache_sizearound 50–75% are standard starting points. Adjust to your actual limits. For many settings, a mountedpostgresql.confis cleaner;-cflags are fine for a handful.--data-checksums: detects silent storage corruption. It has to be set atinitdbtime, which is why it lives here. (PostgreSQL 18 enables checksums by default ininitdb, 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 psBackups: 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.dumpThe -T flag disables TTY allocation so the binary dump is not mangled by the terminal.
Then:
- Run the dump from cron or a systemd timer.
- Upload it to object storage (any S3-compatible bucket works with
aws s3 cp --endpoint-url ...orrclone). - Keep a retention policy, for example 7 daily and 4 weekly.
- 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:
pg_dump(orpg_dumpallfor roles too) from the old container.- Start a new service on the new major with a new, empty volume.
- Restore the dump into it.
- 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_URLenvironment 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), neverlatest - Volume mounted at
/var/lib/postgresqlon 18+,/var/lib/postgresql/dataon 17 and older - Password supplied via
POSTGRES_PASSWORD_FILEand Compose secrets - No port published in production, or bound to
127.0.0.1locally - Health check plus
depends_on: condition: service_healthy shm_sizeraised above the 64 MB default- Scheduled
pg_dumpcopied off the machine, restore tested - A written plan for the next major upgrade