Skip to content
Latchkey

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 test

Gotchas

  • Secondary images bind to localhost, not a service hostname - use localhost:5432.
  • Add a wait (e.g. dockerize -wait) before connecting; the DB may not be ready immediately.
  • Service containers only work on the docker executor, not machine or macos the same way.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →