MongoDB "MongoNetworkError: connect ECONNREFUSED" in CI
By Kaveh Alemi·Latchkey
The MongoDB driver could not open a TCP connection to 127.0.0.1:27017. Mongo is not listening yet (still starting) or the host/port is wrong. This is a connectivity problem and is frequently transient.
What this error means
A driver call fails at connect time with "MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017". It often passes on retry once the Mongo service container finishes initializing.
psql
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (.../connection.js)
Common causes
Mongo service not ready
The Mongo container is still starting when the driver connects, so the connection is refused. Transient.
Wrong host/port
A port that is not published, or the wrong host for the job type, refuses every attempt the same way.
How to fix it
Wait for Mongo readiness
Ping the server with a quick command before the driver connects.
Terminal
until mongosh --quiet --host 127.0.0.1 --eval 'db.runCommand({ping:1})' >/dev/null 2>&1; do
sleep 1
done
Publish the port and use the right host for the job.
On managed runners (Latchkey), self-healing auto-retries transient failures such as Mongo being briefly slow to accept connections.
Frequently asked questions
What causes ""MongoNetworkError: connect ECONNREFUSED""?
The Mongo container is still starting when the driver connects, so the connection is refused. Transient.
How do I fix "MongoNetworkError: connect ECONNREFUSED"?
Ping the server with a quick command before the driver connects.
Can Latchkey fix this automatically?
Yes. Latchkey runs your GitHub Actions on managed runners that detect this failure, apply the fix, and retry the job automatically - self-healing is on by default.