Skip to content
Latchkey

MQTT "ECONNREFUSED" on port 1883 before Mosquitto ready in CI

The MQTT client could not open a TCP connection to 1883 because nothing is listening there yet. In CI this is normally a readiness race: the client connects before Mosquitto has bound the port, or the broker has no listener configured.

What this error means

The client fails with "Error: connect ECONNREFUSED 127.0.0.1:1883" or "Connection refused" on the first connect, then works once the broker is up.

Terminal
Error: connect ECONNREFUSED 127.0.0.1:1883
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)

Common causes

The broker is still starting

Mosquitto has not bound 1883 yet, so the connect is actively refused during the startup window.

No listener configured for 1883

Newer Mosquitto defaults to local-only unless a listener is configured, so a network client finds nothing on 1883.

How to fix it

Configure a listener and wait for the port

Add a 1883 listener config and poll the port before connecting.

mosquitto.conf
# mosquitto.conf
listener 1883
allow_anonymous true

Wait for the broker before the client connects

Poll until 1883 accepts a connection, then run the MQTT client.

Terminal
until nc -z localhost 1883; do echo "waiting for mosquitto"; sleep 2; done

How to prevent it

  • Configure an explicit 1883 listener for network clients.
  • Wait for the port to accept connections before connecting.
  • Map 1883 from the Mosquitto service to where the client connects.

Frequently asked questions

What causes "MQTT "connect ECONNREFUSED ... 1883""?
Mosquitto has not bound 1883 yet, so the connect is actively refused during the startup window.
How do I fix MQTT "connect ECONNREFUSED ... 1883"?
Add a 1883 listener config and poll the port before connecting.

Related guides

References

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