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.
nats: dial tcp 127.0.0.1:4222: connect: connection refusedCommon 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.
until nc -z localhost 4222; do echo "waiting for nats"; sleep 2; doneUse the correct service host
On the Docker network, connect by service name; from the runner host, use the mapped localhost port.
env:
NATS_URL: nats://localhost:4222How 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.