RAPID INCIDENT TRIAGE & ACTION PLAN•Performance
01. Error Signature
PostgreSQL Localhost 5432 Connection Refused
02. Root Cause Vector

PostgreSQL is not running or not bound to localhost:5432, killing all application database connections instantly.

03. Rapid Prescription

Enforce consistent lock order (e.g. ORDER BY id FOR UPDATE) or use non-blocking SKIP LOCKED.

Zero-Trust Client IDE/ Performance

PostgreSQL Localhost 5432 Connection Refused

PostgreSQL is not running or not bound to localhost:5432, killing all application database connections instantly.

SYSTEM STATUS
CREDITS: 0 / 3
source.yaml(70L)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# legacy-app/docker-compose.yaml
# TODO: This config is a mess, but it's been working in prod for 2 years. Don't touch unless you have to.
# PCI-secure-zone deployment for legacy-api-v3

version: '3.7'

services:
  # Main API service - my-registry.internal/legacy-api:stable
  api:
    image: my-registry.internal/legacy-api:stable
    container_name: legacy-api-pci
    # VULNERABILITY: The network_mode override here silently breaks the postgres service dependency.
    network_mode: host  # Workaround for the PCI scanner's false positives on bridge networking. TODO: Revert after audit.
    environment:
      - AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
      - AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
      - STRIPE_LIVE_SECRET_KEY=sk_live_51H7sF2Kp9LxM3nR9vC8aB4dF6gH7jKl0zXyQwErT1uIoNmPqRs
      - DATABASE_URL=postgresql://app_user:SuperSecretP@ssw0rd123!@localhost:5432/legacy_pci_db?sslmode=disable
      - REDIS_URL=redis://pci-redis.internal:6379
      # Old config kept for rollback - DO NOT DELETE
      # - DB_HOST=postgres
    depends_on:
      - postgres
      - redis
    # Healthcheck disabled due to race condition with DB init. TODO: Fix properly.
    # healthcheck:
    #   test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
    #   interval: 30s
    #   timeout: 10s
    #   retries: 3

  # PostgreSQL service - internal legacy DB
  postgres:
    image: postgres:12-alpine
    container_name: pci-postgres-12
    environment:
      - POSTGRES_USER=app_user
      - POSTGRES_PASSWORD=SuperSecretP@ssw0rd123!
      - POSTGRES_DB=legacy_pci_db
    ports:
      - "5432:5432"  # Exposed for the legacy batch job that still runs on the host. TODO: Migrate to container.
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
      - postgres_data:/var/lib/postgresql/data
    # This network config is overridden by api's network_mode=host, making this service unreachable on 'localhost' from api.
    networks:
      - pci-backend

  # Redis cache - using old image for compatibility
  redis:
    image: redis:5-alpine
    container_name: pci-redis
    command: redis-server --requirepass "AnotherSecretRedisPass!987"
    networks:
      - pci-backend
    ports:
      - "6379:6379"

# Volume for DB persistence
volumes:
  postgres_data:
    driver: local

# Networks - partially used due to the host network workaround.
networks:
  pci-backend:
    driver: bridge
    # Internal flag removed to allow host access for the batch job. Security exception ID: PCI-EX-2023-445
    # internal: true
AI Audit Console
> Waiting for pre-flight audit...
HybridRedactor Engine: Active
TECHNICAL WHITEPAPER & ARCHITECTURE SPEC•Updated 2026

How to Fix PostgreSQL 'Connection Refused' on localhost Port 5432

Threat/Impact Level: HIGH | Downtime Risk: HIGH | Time to Fix: 5–15 mins

TL;DR

  • What broke: PostgreSQL is either not running, not listening on 127.0.0.1:5432, or pg_hba.conf is rejecting the connection before it starts.
  • How to fix it: Confirm the service is active, verify listen_addresses in postgresql.conf, and check pg_hba.conf allows the connecting user/host.
  • Use our Client-Side Sandbox below to paste your postgresql.conf or connection string and auto-generate the corrected config — no data leaves your browser.

▼ 🔍 Root Cause Breakdown & Kernel Diagnostics [Click to Expand Deep Dive]

The Incident (What Does This Error Mean?)

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?

This is a TCP-layer rejection — the OS itself is refusing the connection. The PostgreSQL process either isn't running, is listening on a Unix socket only (not TCP), or is bound to a different interface. Your application is dead in the water. Every query, migration, and health check is failing right now.


▼ 🔍 Detailed Impact & Blast Radius Analysis [Click to Expand Deep Dive]

The Attack Vector / Blast Radius

This is a full application outage scenario, not a degraded state. Cascading failures include:

  • Connection pool exhaustion: App servers keep retrying, spawning threads that never resolve, eventually OOM-killing the app process.
  • Data integrity risk: If this hit mid-transaction during a deployment or failover, uncommitted transactions may have been lost.
  • Monitoring blind spots: Many APM tools report this as an app-layer 500, masking the real infrastructure root cause and delaying MTTR.
  • Secondary services: Any service depending on this DB (auth, billing, queues) fails silently or loudly depending on circuit breaker configuration.

If this is a shared database host, every tenant/application on it is affected simultaneously.


How to Fix It

Step 1 — Confirm PostgreSQL is Actually Running

# systemd
sudo systemctl status postgresql

# or for versioned installs
sudo systemctl status postgresql@14-main

# If stopped:
sudo systemctl start postgresql

If the service fails to start, check logs immediately:

sudo journalctl -u postgresql --since "10 minutes ago"
# or
tail -100 /var/log/postgresql/postgresql-14-main.log

Step 2 — Confirm It's Listening on TCP Port 5432

sudo ss -tlnp | grep 5432
# Expected output:
# LISTEN  0  128  127.0.0.1:5432  0.0.0.0:*  users:(("postgres",pid=1234,fd=5))

If you see nothing, PostgreSQL is running but bound to a Unix socket only.

Basic Fix — Enable TCP Listening in `postgresql.conf`

# /etc/postgresql/14/main/postgresql.conf

- listen_addresses = ''
+ listen_addresses = 'localhost'

# For remote access (use with firewall rules):
+ listen_addresses = '*'

After editing:

sudo systemctl restart postgresql

Step 3 — Verify `pg_hba.conf` Allows the Connection

# /etc/postgresql/14/main/pg_hba.conf

# Bad: no entry for local TCP connections
- local   all   all                peer

# Good: allow local TCP connections with password auth
+ host    all   all   127.0.0.1/32  scram-sha-256
+ host    all   all   ::1/128        scram-sha-256

Reload after pg_hba.conf changes (no full restart needed):

sudo systemctl reload postgresql
# or inside psql:
SELECT pg_reload_conf();

Enterprise Best Practice — Dockerized / Kubernetes Environments

If running in Docker, the most common cause is the container not being ready when the app starts:

# docker-compose.yml

services:
  app:
    depends_on:
-     - postgres
+     - postgres
+   condition: service_healthy

  postgres:
    image: postgres:15
+   healthcheck:
+     test: ["CMD-SHELL", "pg_isready -U $POSTGRES_USER -d $POSTGRES_DB"]
+     interval: 5s
+     timeout: 5s
+     retries: 10

For Kubernetes, ensure the Service targetPort matches the container port and the pod is Running/Ready:

kubectl get pods -l app=postgres
kubectl describe svc postgres-service
kubectl exec -it <app-pod> -- pg_isready -h postgres-service -p 5432

💡 Tired of pasting proprietary infrastructure configs into public LLMs? Generic AI interfaces log your company's ARNs, connection strings, and private keys. StackEngine enforces client-side zero-trust boundaries—the sandbox above executes 100% locally in your browser. Drop your broken manifest above to redact secrets locally and synthesize deterministic patch drafts with your own API key.

(For CI/CD pipeline automation, install via npm i -g stackengine).


▼ 🔍 Continuous Pipeline Governance & CI/CD Guardrails [Click to Expand Deep Dive]

Prevention in CI/CD

1. Add pg_isready to your deployment health gates:

# In your deploy script or GitHub Actions step
until pg_isready -h $DB_HOST -p 5432 -U $DB_USER; do
  echo "Waiting for PostgreSQL..."
  sleep 2
done

2. Checkov / Terraform — enforce listen_addresses is not wildcard without firewall:

# If using RDS or Cloud SQL, enforce VPC-only access
resource "aws_db_instance" "postgres" {
  publicly_accessible = false  # Checkov: CKV_AWS_17
}

3. Integration test your DB connection in CI before deploying:

# .github/workflows/ci.yml
services:
  postgres:
    image: postgres:15
    env:
      POSTGRES_PASSWORD: testpass
    options: >-
      --health-cmd pg_isready
      --health-interval 5s
      --health-timeout 5s
      --health-retries 10

4. OPA Policy — flag any app deployment missing a DB readiness probe in Kubernetes:

deny[msg] {
  input.kind == "Deployment"
  container := input.spec.template.spec.containers[_]
  not container.readinessProbe
  msg := sprintf("Container '%v' is missing a readinessProbe — DB race condition risk.", [container.name])
}

Official Grounding & Normative Specifications

The technical diagnostics, error recovery protocols, and prevention patterns in this specification are grounded in official vendor documentation and standards:

Diagnostic & Architectural FAQ

Q1.Why does PostgreSQL refuse connections even when the service is running?
PostgreSQL may be running but listening only on a Unix domain socket, not on TCP. Check `listen_addresses` in `postgresql.conf` — if it's empty or set to an interface that doesn't include `localhost`/`127.0.0.1`, TCP connections will be refused at the OS level regardless of service status. This is a classic misconfiguration where the service is technically 'up' but operationally dead for network clients, a critical visibility gap that StackEngine's runtime analysis would flag and correlate in real-time.
Q2.How do I check what port and address PostgreSQL is actually listening on?
Run `sudo ss -tlnp | grep 5432` on Linux. If nothing returns, PostgreSQL is not listening on TCP at all. You can also query from inside psql with `SHOW listen_addresses;` and `SHOW port;` if you can connect via Unix socket using `sudo -u postgres psql`. Manually executing these commands across environments is error-prone and introduces security risk by requiring elevated privileges on production nodes. Instead, drop the broken manifest into the StackEngine Local Sandbox above to automatically compile a zero-trust fix that diagnoses the listening state without shell access and generates a secure, audited remediation patch.
Q3.Do I need to restart or just reload PostgreSQL after changing pg_hba.conf vs postgresql.conf?
`pg_hba.conf` changes only require a **reload** (`systemctl reload postgresql` or `SELECT pg_reload_conf();`). Changes to `listen_addresses` in `postgresql.conf` require a full **restart** because the server must rebind its network sockets. Managing this lifecycle manually across large mono-repos or at scale is a compliance nightmare, leading to configuration drift and audit failures. Deploy the StackEngine CI/CD Automator (Team Edition) for on-prem, automated pull request generation with Maker-Checker review that enforces restart/reload policies and generates provable compliance artifacts for every change.