Skip to content
Latchkey

Node.js "ECONNREFUSED 127.0.0.1" - Fix Local Service Not Ready in CI

Node tried to connect to a local service - Postgres, Redis, a mock server - but nothing was listening on that port yet. In CI this is usually a startup race: the service container is still booting when the test connects.

What this error means

Tests or a script fail with connect ECONNREFUSED 127.0.0.1:<port>. Re-running often passes because the service had time to start. The hallmark is that the same job is green when the dependency happens to be ready in time.

Node output
Error: connect ECONNREFUSED 127.0.0.1:5432
    at TCPConnectWrap.afterConnect (node:net:1595:16)
  errno: -111,
  code: 'ECONNREFUSED',
  address: '127.0.0.1',
  port: 5432

Common causes

The service has not started yet

A database or service container in CI is still initialising when the test connects. The port is not open, so the connection is refused. It is timing, not a wrong address.

Wrong host or port

Less often, the service is reachable under a different host (a service container hostname, not 127.0.0.1) or port, so the connection is genuinely refused.

How to fix it

Wait for readiness before connecting

Poll the port (or a health endpoint) until it accepts connections, then run the tests. This removes the race.

Terminal
# wait for the port to open (up to 30s)
for i in $(seq 1 30); do
  nc -z 127.0.0.1 5432 && break
  sleep 1
done
npm test

Use service health checks

On GitHub Actions, give the service container a health check so the job only proceeds once it is ready.

.github/workflows/ci.yml
services:
  postgres:
    image: postgres:16
    options: >-
      --health-cmd pg_isready
      --health-interval 5s
      --health-retries 5

How to prevent it

  • Add a readiness wait or health check before tests touch a service.
  • Confirm the correct host/port for service containers in your CI system.
  • Retry the initial connection with backoff to absorb slow starts.

Frequently asked questions

What causes ""ECONNREFUSED 127.0.0.1""?
A database or service container in CI is still initialising when the test connects. The port is not open, so the connection is refused. It is timing, not a wrong address.
How do I fix "ECONNREFUSED 127.0.0.1"?
Poll the port (or a health endpoint) until it accepts connections, then run the tests. This removes the race.
Can Latchkey fix this automatically?
Yes. Latchkey runs your GitHub Actions on managed runners that detect this failure, apply the fix, and retry the job automatically - self-healing is on by default.

Related guides

References

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