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.
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: 5432Common 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.
# 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 testUse service health checks
On GitHub Actions, give the service container a health check so the job only proceeds once it is ready.
services:
postgres:
image: postgres:16
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-retries 5How 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.