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.
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
listener 1883
allow_anonymous trueWait for the broker before the client connects
Poll until 1883 accepts a connection, then run the MQTT client.
until nc -z localhost 1883; do echo "waiting for mosquitto"; sleep 2; doneHow 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.