How to Run a Postgres Service in CircleCI
In CircleCI, extra images listed under a job's docker: key become service containers reachable on localhost.
The first image in the docker: list is your primary execution environment; each additional image runs as a service container that binds to localhost.
Primary + Postgres service
List Postgres as a second image; it is reachable at localhost:5432 from your steps.
.circleci/config.yml
jobs:
test:
docker:
- image: cimg/node:20.11
- image: cimg/postgres:16.2
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_test
environment:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/app_test
steps:
- checkout
- run: dockerize -wait tcp://localhost:5432 -timeout 1m
- run: npm ci && npm testGotchas
- Secondary images bind to
localhost, not a service hostname - uselocalhost:5432. - Add a wait (e.g.
dockerize -wait) before connecting; the DB may not be ready immediately. - Service containers only work on the
dockerexecutor, notmachineormacosthe same way.
Related guides
How to Run a Postgres Service Container in GitHub ActionsRun a Postgres (or Redis) service container in GitHub Actions with services:, health checks, and port mapping…
How to Store Build Artifacts in CircleCIStore build artifacts in CircleCI with store_artifacts, and hand files to later jobs with persist_to_workspac…