Skip to content
Latchkey

NATS "connection refused" on port 4222 in CI

The TCP connect to 4222 was actively refused, which means no process is listening there from the client side. Either nats-server has not finished binding the port, or the service port is not published to where the client connects.

What this error means

The client fails with "dial tcp 127.0.0.1:4222: connect: connection refused" or "[Errno 111] Connection refused" on the first connect attempt.

Terminal
nats: dial tcp 127.0.0.1:4222: connect: connection refused

Common causes

The server has not bound 4222 yet

During startup the listener is not yet open, so the connect is refused rather than timing out.

The port is not mapped to the client

The NATS service does not publish 4222 to the host (or the client uses the wrong host), so nothing answers there.

How to fix it

Publish 4222 and wait for the listener

Map the port and poll until the connect succeeds before running tests.

Terminal
until nc -z localhost 4222; do echo "waiting for nats"; sleep 2; done

Use the correct service host

On the Docker network, connect by service name; from the runner host, use the mapped localhost port.

.github/workflows/ci.yml
env:
  NATS_URL: nats://localhost:4222

How to prevent it

  • Map 4222 explicitly and connect on the address you mapped.
  • Wait for the port to accept connections before the first client.
  • Use the service name for in-network clients and localhost from the host.

Frequently asked questions

What causes "NATS "connection refused" (4222)"?
During startup the listener is not yet open, so the connect is refused rather than timing out.
How do I fix NATS "connection refused" (4222)?
Map the port and poll until the connect succeeds before running tests.

Related guides

References

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