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.

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:
- No
$PGDATA/PG_VERSION→initdbwithPOSTGRES_INITDB_ARGS, createPOSTGRES_USERas superuser (defaultpostgres), createPOSTGRES_DB(default = user), set the password fromPOSTGRES_PASSWORDorPOSTGRES_PASSWORD_FILE. $PGDATA/PG_VERSIONexists → skip all of the above, start the server.- In both cases, files in
/docker-entrypoint-initdb.d/run only on a fresh cluster.
A reproducer that shows the behaviour in four commands:
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 passwordThe 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:
| Variable | Fresh cluster | Existing cluster | Notes |
|---|---|---|---|
POSTGRES_PASSWORD | Applied | Ignored | Use ALTER ROLE afterwards |
POSTGRES_USER | Creates superuser | Ignored | Role must exist already |
POSTGRES_DB | Creates database | Ignored | createdb manually |
POSTGRES_INITDB_ARGS | Applied | Ignored | Encoding, locale, checksums fixed at init |
POSTGRES_HOST_AUTH_METHOD | Writes pg_hba.conf | Ignored | trust disables password checks entirely |
PGDATA | Chooses directory | Chooses directory | A different path looks like a fresh cluster |
POSTGRES_PASSWORD_FILE | Applied | Ignored | Same rules, value read from a file |
/docker-entrypoint-initdb.d/* | Executed | Ignored | Scripts are one-shot |
The four failure messages and what they actually mean:
| Message | Real cause | Fix |
|---|---|---|
password authentication failed | Old hash in pg_authid | ALTER ROLE, or recreate the volume |
role "app" does not exist | POSTGRES_USER changed after init | CREATE ROLE app LOGIN PASSWORD … |
database "app" does not exist | POSTGRES_DB changed after init | CREATE DATABASE app OWNER app |
Database is uninitialized and superuser password is not specified | No password on a fresh volume | Set 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:
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:
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/dockerAlways 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:
volumes:
- ./init/01-roles.sql:/docker-entrypoint-initdb.d/01-roles.sql:roUse 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:
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:
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:
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 restartafter changing the password. A restart reuses the same container and cluster; only the data directory decides, and it already exists.down -von a shared environment.-vremoves named volumes. Rundocker compose config --volumesfirst and confirm the volume is not the one holding real data.POSTGRES_PASSWORDwith special characters and$. Compose interpolates$in.envvalues; 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. Startingpostgres:18on 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_isreadyreturns "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_ARGSlater does nothing, and a database created withCcollation cannot be changed in place — a new cluster and a dump are the only route. pg_hba.confedited inside the volume while the image regenerates it. The image writespg_hba.confduring init; edits to a copied file are lost on the next init. Put persistent rules in a mountedpg_hba.confor 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 toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesPostgres RLS 42P17: infinite recursion detected in policy
A policy on members that reads members re-enters itself. One security definer function with a pinned search_path ends the recursion and leaves the rest of the policy intact.
Postgres permission denied for sequence: GRANT USAGE and nextval
Sequences carry their own ACL, so table grants never cover nextval. The USAGE grant, default privileges, and why identity columns behave differently.
PgBouncer Transaction vs Session Pooling: What Breaks
Port 6543 hands out a server connection per transaction, so prepared statements, SET, LISTEN and cursors stop behaving. Driver-level settings for each stack.
Zero-Downtime Postgres Migrations: lock_timeout and NOT VALID
One ALTER TABLE waiting behind a slow SELECT blocks every query that arrives after it. The timeout-retry loop, NOT VALID constraints and CONCURRENTLY index rules.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.