How to Provide a Postgres Fixture With Compose in CI
A throwaway Postgres in Compose gives tests a real database with a known schema, seeded once and torn down after the job.
Define a postgres service with a pg_isready healthcheck and mount an init SQL script so the schema is ready the moment the service reports healthy.
Steps
- Set
POSTGRES_PASSWORDand a healthcheck usingpg_isready. - Mount
*.sqlinto/docker-entrypoint-initdb.dto seed on first boot. - Gate tests on
--waitordepends_on: service_healthy.
Compose file
docker-compose.yml
services:
postgres:
image: postgres:16
environment:
POSTGRES_PASSWORD: test
POSTGRES_DB: app
volumes:
- ./ci/seed.sql:/docker-entrypoint-initdb.d/seed.sql:ro
ports: ["5432:5432"]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d app"]
interval: 5s
retries: 10Gotchas
- Init scripts run only when the data directory is empty, so a reused named volume skips them; use a fresh volume or
down -vbetween runs. - Match the client library major version to the server to avoid protocol surprises.
Related guides
How to Provide a Redis Fixture With Compose in CIRun a disposable Redis for CI with docker compose, gate tests on a redis-cli ping healthcheck, and connect th…
How to Provide a MySQL Fixture With Compose in CISpin up a throwaway MySQL for CI tests with docker compose, gate the suite on a mysqladmin ping healthcheck,…
How to Add Compose Healthchecks and Gate CI on ThemDefine healthcheck blocks in docker-compose.yml with test, interval, and retries so docker compose up --wait…