Skip to content
Latchkey

Rails "PG::ConnectionBad: could not connect to server" in CI

ActiveRecord tried to open a Postgres connection and got a refused or unreachable socket. In CI this almost always means the Postgres service container is not started, not ready, or reachable at a different host/port than DATABASE_URL expects.

What this error means

A test or setup step fails with "PG::ConnectionBad: could not connect to server: Connection refused" naming host localhost and port 5432.

Rails
PG::ConnectionBad: could not connect to server: Connection refused
	Is the server running on host "localhost" (127.0.0.1) and accepting
	TCP/IP connections on port 5432?

Common causes

No Postgres service container is defined

The job has no services: postgres block, so nothing is listening on 5432 when Rails connects.

The port or host mapping is wrong

The service container maps a different port, or the connection targets db instead of localhost, so the socket is unreachable.

How to fix it

Add a Postgres service with a health check

  1. Declare a postgres service and map port 5432.
  2. Add a health check so the job waits until Postgres accepts connections.
  3. Point DATABASE_URL at localhost:5432 with the service credentials.
.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    env:
      POSTGRES_PASSWORD: postgres
    ports: ['5432:5432']
    options: >-
      --health-cmd pg_isready --health-interval 10s
      --health-timeout 5s --health-retries 5

Match DATABASE_URL to the service

Set the connection string to the mapped host and port so ActiveRecord reaches the container.

.github/workflows/ci.yml
env:
  DATABASE_URL: postgres://postgres:postgres@localhost:5432/myapp_test

How to prevent it

  • Always add a health check so steps wait for the database to be ready.
  • Keep DATABASE_URL host/port aligned with the service port mapping.
  • Use the same Postgres major version in CI as in production.

Frequently asked questions

What causes ""PG::ConnectionBad""?
The job has no services: postgres block, so nothing is listening on 5432 when Rails connects.
How do I fix "PG::ConnectionBad"?
Add a Postgres service with a health check

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card