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_restoreorpg_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."
More on PostgreSQL
How do you set up PostgreSQL and log in with psql?BeginnerHow do you create a database, tables, users and query data in PostgreSQL?BeginnerHow do you back up and restore a PostgreSQL database?BeginnerWhat is PostgreSQL and why is it so popular?BeginnerHow is PostgreSQL organised: cluster, database, schema and table?BeginnerHow do you connect to PostgreSQL from the command line?Beginner