# 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?

**Code:** `PG::ConnectionBad: could not connect to server` · **Category:** Ruby / Rails · **Seen on:** Ruby, PostgreSQL

Rails can't reach PostgreSQL — the server is down, wrong host/port/socket, or credentials/pg_hba block it.

## Meaning

Start PostgreSQL (`brew services start postgresql`, `sudo systemctl start postgresql`), check `database.yml`/`DATABASE_URL`, the socket path (`/var/run/postgresql`), and Docker networking (host `db` not `localhost`). For role errors use `createuser`; for "no pg_hba.conf entry" fix `pg_hba.conf`.

## Common causes

- PostgreSQL not running
- Wrong host/port/socket
- Docker: using localhost instead of the service name
- Role/database missing
- `pg_hba.conf` rejecting

## Quick fix

1. Start PostgreSQL and test `psql -h HOST -U USER DB`
2. Fix `host:` in database.yml (service name in Docker)
3. Create role/db: `createuser -s $USER; createdb app_dev`

## Detailed fix by platform

### Linux

1. `pg_isready -h localhost -p 5432; sudo systemctl status postgresql`

## How to diagnose

1. **Server** — pg_isready?
2. **Host** — Correct?
3. **Role** — Exists?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/ruby/activerecord-pg-connectionbad)
