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.
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
- Declare a
postgresservice and map port 5432. - Add a health check so the job waits until Postgres accepts connections.
- Point DATABASE_URL at localhost:5432 with the service credentials.
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 5Match DATABASE_URL to the service
Set the connection string to the mapped host and port so ActiveRecord reaches the container.
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/myapp_testHow 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.