How to Spin Up a Postgres Service for Tests in GitHub Actions
A Postgres service container runs as a sidecar your job reaches over localhost:5432, so tests hit a real database instead of a mock.
Declare postgres under services: with the official postgres image, set POSTGRES_PASSWORD, map port 5432, and add a pg_isready health check so steps wait until the server accepts connections.
Steps
- Add a
services.postgresblock withimage: postgres:16. - Set
env.POSTGRES_PASSWORD(and optionallyPOSTGRES_DB). - Map
ports: [5432:5432]and add apg_isreadyhealth check. - Point your test
DATABASE_URLatlocalhost:5432.
Workflow
.github/workflows/ci.yml
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/app_test
steps:
- uses: actions/checkout@v4
- run: npm ci && npm testGotchas
- Without a health check, the job can start before Postgres accepts connections and tests fail with
connection refused. - When the job itself runs in a container, connect by the service name
postgres, notlocalhost.
Related guides
How to Spin Up a MySQL Service for Tests in GitHub ActionsRun MySQL as a GitHub Actions service container with a mysqladmin ping health check and a connection string o…
How to Wait for a Database to Be Ready in GitHub ActionsMake GitHub Actions wait until a database accepts connections using service health checks or a pg_isready ret…
How to Use Service Containers in GitHub ActionsSpin up Postgres or Redis alongside a GitHub Actions job with services, including health checks and port mapp…