How do you run PostgreSQL in Docker with persistent data and an init script?

IntermediateHands-onPostgreSQL
Answer

Short answer

Run the official postgres image with POSTGRES_PASSWORD (and optionally POSTGRES_USER/POSTGRES_DB), mount a volume at /var/lib/postgresql/data, and put .sql or .sh files in /docker-entrypoint-initdb.d/ to run on first start.

Example

docker run -d --name postgres \
  -e POSTGRES_PASSWORD=rootpass \
  -e POSTGRES_DB=shop \
  -p 5432:5432 \
  -v pgdata:/var/lib/postgresql/data \
  -v $(pwd)/init:/docker-entrypoint-initdb.d:ro \
  postgres:16
-- init/01-app-user.sql
CREATE ROLE shop_app LOGIN PASSWORD 'apppass';
GRANT CONNECT ON DATABASE shop TO shop_app;

Compose health check

healthcheck:
  test: ["CMD-SHELL", "pg_isready -U postgres -d shop"]
  interval: 5s
  retries: 10

Remember

  • Init scripts and POSTGRES_* env vars only apply when the data directory is empty.
  • Upgrading major versions (15 → 16) can't just switch the image tag on an existing volume — use pg_dump/pg_restore or pg_upgrade.

What to say in the interview

"Official image with POSTGRES_PASSWORD, a volume for the data directory, init SQL in docker-entrypoint-initdb.d for first-run setup and pg_isready as the health check. Major version upgrades need dump/restore or pg_upgrade, not just a new tag."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL