Fixing the “Role ‘Postgres’ Does Not Exist” Error in PostgreSQL Docker
When deploying a PostgreSQL instance inside a Docker container, one of the most common startup failures is:
psql: FATAL: role "postgres" does not existThis error typically indicates that the initialization scripts did not create the default postgres superuser. Below we explore the causes and the correct fixes.
1. Why the Error Occurs
1.1 Your data volume already has an old database
PostgreSQL only creates users when the data directory is empty.
If you reuse a volume, the postgres role may simply not exist.
1.2 You changed the default POSTGRES_USER
POSTGRES_USER=myuserThis makes myuser the superuser — not postgres.
1.3 Incorrect filesystem permissions
If PostgreSQL cannot write to /var/lib/postgresql/data, initialization may silently fail.
2. Solutions
A. Delete the old volume (recommended)
docker compose down -v
docker compose up -dB. Explicitly set POSTGRES_USER
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: secret123Restart:
docker compose down
docker compose up -dC. Manually create the missing role
docker exec -it <container> bash
psql -U myuserInside PostgreSQL:
CREATE ROLE postgres WITH SUPERUSER LOGIN PASSWORD 'changeme';D. Fix permissions
sudo chown -R 999:999 /path/to/volume
docker compose restart3. Best Practices
- Always specify
POSTGRES_USERandPOSTGRES_PASSWORD. - Prefer named volumes over bind mounts.
- Add healthchecks:
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 54. Conclusion
This error happens because the container is using an already-initialized volume or the default superuser was changed. Resetting the volume, correcting your environment variables, or creating the role manually will resolve the problem.
If you want extended troubleshooting for specific platforms (Railway, Render, Fly.io, Docker Swarm), I can add that too.