Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

POSTGRES_PASSWORD Is Ignored: Docker Volume Init Rules

The official image reads POSTGRES_PASSWORD once, at initdb. Why changed credentials and users do nothing on an existing volume, and how to rotate safely.

~5 min readSQL
#PostgreSQL#Docker#Configuration#Security
3D illustration of a sealed container with a mounted volume plate and a key turning in a closed lock

Introduction & Quick Summary

Symptom. You change POSTGRES_PASSWORD in .env, run docker compose up -d, and the application still authenticates with the old password — or fails with FATAL: password authentication failed for user "app" while the new password sits in the environment. The same thing happens to POSTGRES_USER (FATAL: role "app" does not exist) and to POSTGRES_DB (the database is missing, but postgres exists).

Cause. The official postgres image applies those variables only while creating a new cluster. Its entrypoint checks for $PGDATA/PG_VERSION; if the file exists, it skips initdb and every init script, then starts the server against the existing data directory — where the old roles, the old password hash and the old databases already live. Environment variables are not a configuration channel for a running cluster.

Fix. Either change the password inside the database (ALTER ROLE … WITH PASSWORD) and leave the volume alone, or delete the volume deliberately when the data is disposable (docker compose down -v). Choose the first for anything you care about: the second is a full data loss, and it is the only way for the variables to be applied again.

Core Mechanics, Signatures & Reproducible Setup

The entrypoint's logic, simplified, is three branches:

  1. No $PGDATA/PG_VERSION → initdb with POSTGRES_INITDB_ARGS, create POSTGRES_USER as superuser (default postgres), create POSTGRES_DB (default = user), set the password from POSTGRES_PASSWORD or POSTGRES_PASSWORD_FILE.
  2. $PGDATA/PG_VERSION exists → skip all of the above, start the server.
  3. In both cases, files in /docker-entrypoint-initdb.d/ run only on a fresh cluster.

A reproducer that shows the behaviour in four commands:

bash
docker volume create pgdata-demo docker run -d --name pg -e POSTGRES_PASSWORD=first -v pgdata-demo:/var/lib/postgresql/data postgres:17 sleep 5 && docker exec pg psql -U postgres -c "select 1" # works with 'first' docker rm -f pg docker run -d --name pg -e POSTGRES_PASSWORD=second -v pgdata-demo:/var/lib/postgresql/data postgres:17 sleep 5 docker exec -e PGPASSWORD=second pg psql -U postgres -c "select 1" # authentication failed docker exec -e PGPASSWORD=first pg psql -U postgres -c "select 1" # still the old password

The password lives in pg_authid inside the cluster. initdb hashes it once; nothing in the image reads POSTGRES_PASSWORD again.

Key Comparison Table

Which variables apply when:

VariableFresh clusterExisting clusterNotes
POSTGRES_PASSWORDAppliedIgnoredUse ALTER ROLE afterwards
POSTGRES_USERCreates superuserIgnoredRole must exist already
POSTGRES_DBCreates databaseIgnoredcreatedb manually
POSTGRES_INITDB_ARGSAppliedIgnoredEncoding, locale, checksums fixed at init
POSTGRES_HOST_AUTH_METHODWrites pg_hba.confIgnoredtrust disables password checks entirely
PGDATAChooses directoryChooses directoryA different path looks like a fresh cluster
POSTGRES_PASSWORD_FILEAppliedIgnoredSame rules, value read from a file
/docker-entrypoint-initdb.d/*ExecutedIgnoredScripts are one-shot

The four failure messages and what they actually mean:

MessageReal causeFix
password authentication failedOld hash in pg_authidALTER ROLE, or recreate the volume
role "app" does not existPOSTGRES_USER changed after initCREATE ROLE app LOGIN PASSWORD …
database "app" does not existPOSTGRES_DB changed after initCREATE DATABASE app OWNER app
Database is uninitialized and superuser password is not specifiedNo password on a fresh volumeSet POSTGRES_PASSWORD or POSTGRES_PASSWORD_FILE

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Rotating the password without losing data

Run the change against the running server as a superuser. Inside the container the postgres role authenticates over the local socket, so no password is needed:

bash
docker exec -it pg psql -U postgres -c \ "ALTER ROLE app WITH PASSWORD 'new-secret';" # verify, then roll it out to the application's environment docker exec -e PGPASSWORD=new-secret pg psql -U app -d app -c "select current_user;"

For a scripted rotation, psql reads PGPASSWORD from the environment and the new value never appears in shell history if you pass it with -v and \gexec or read it from a secret file.

2. The volume mounted at the wrong path

A named volume pointed at a path the image does not use is an empty volume, so initdb runs again and the new password does apply — against a brand new cluster, while your old data still sits in another volume. The PostgreSQL 18 image moved the default data directory to a version-specific path and declares the volume one level up, so a docker-compose.yaml written for 16 that mounts /var/lib/postgresql/data silently gets a fresh cluster on 18:

yaml
services: db: image: postgres:18 environment: POSTGRES_PASSWORD_FILE: /run/secrets/pg_password PGDATA: /var/lib/postgresql/18/docker # match the image's default explicitly volumes: - pgdata18:/var/lib/postgresql/18/docker

Always pin the tag (postgres:17.5, not postgres:latest) and check docker inspect for the actual PGDATA before migrating a volume.

3. Init scripts that only ever ran once

/docker-entrypoint-initdb.d/*.sql is a bootstrap mechanism, not a migration tool. A script that creates the application role runs on the first start and never again, so adding a second script later does nothing on existing environments:

yaml
volumes: - ./init/01-roles.sql:/docker-entrypoint-initdb.d/01-roles.sql:ro

Use a migration tool (Flyway, Liquibase, Prisma Migrate, Alembic, plain versioned SQL) for anything that must apply to existing data, and keep init scripts limited to roles and extensions for fresh developer machines.

4. Secret files instead of environment variables

POSTGRES_PASSWORD_FILE reads the password from a mounted file, which avoids exposing it in docker inspect and in /proc/*/environ. It obeys the same first-init rule, so it helps provision a cluster, not rotate it:

yaml
secrets: pg_password: file: ./secrets/pg_password.txt services: db: image: postgres:17 environment: POSTGRES_PASSWORD_FILE: /run/secrets/pg_password secrets: [pg_password]

5. Authentication methods after POSTGRES_HOST_AUTH_METHOD=trust

Setting trust writes pg_hba.conf at init and removes the password check — convenient for a throwaway test container, dangerous in anything shared. If a teammate added it to make a failing login go away, the cluster now accepts any password, and removing the variable later does not rewrite pg_hba.conf:

bash
docker exec pg psql -U postgres -c "show hba_file;" docker exec pg tail -5 "$(docker exec pg psql -U postgres -tAc 'show hba_file')"

Fix by editing pg_hba.conf (scram-sha-256 for host lines) and reloading with SELECT pg_reload_conf(); — or by recreating the volume when the data is disposable.

6. Kubernetes and managed platforms

In Kubernetes the same rule applies to the StatefulSet's PGDATA, and the official charts manage credentials through a Secret that initialises the cluster once. Changing the Secret rotates nothing:

bash
kubectl exec -it sts/postgresql-0 -- psql -U postgres -c "ALTER ROLE app PASSWORD '…';"

On managed services (RDS, Cloud SQL, Neon, Supabase) there is no entrypoint at all: environment variables in a Terraform config or a Helm value describe the creation parameters, and password changes go through the provider's API or SQL.

Common Compilation/Runtime Mistakes & Version Gotchas

  • docker compose restart after changing the password. A restart reuses the same container and cluster; only the data directory decides, and it already exists.
  • down -v on a shared environment. -v removes named volumes. Run docker compose config --volumes first and confirm the volume is not the one holding real data.
  • POSTGRES_PASSWORD with special characters and $. Compose interpolates $ in .env values; use $$ or single quotes, otherwise the password the app uses and the password the cluster stored differ by a variable expansion.
  • Upgrading the image without pg_upgrade. Starting postgres:18 on a 16 data directory fails with a version mismatch in the log and, with some mount layouts, initialises a new cluster instead. Read the log before assuming the password broke.
  • Healthchecks that pass too early. pg_isready returns "accepting connections" during init too; combine it with -U "$POSTGRES_USER" -d "$POSTGRES_DB" so a dependency does not connect to a half-initialised cluster.
  • Locale and encoding are init-only. Changing POSTGRES_INITDB_ARGS later does nothing, and a database created with C collation cannot be changed in place — a new cluster and a dump are the only route.
  • pg_hba.conf edited inside the volume while the image regenerates it. The image writes pg_hba.conf during init; edits to a copied file are lost on the next init. Put persistent rules in a mounted pg_hba.conf or apply them with SQL.

Related tools. When two compose files or two .env variants disagree about credentials, paste both into the text diff tool to see which value the container actually receives, and format a dumped pg_authid-adjacent JSON export (roles, database list) with the JSON formatter before comparing environments.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.