MongoDB "MongoNetworkError: connect ECONNREFUSED" in CI
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
doneAdd a healthcheck to the service
.github/workflows/ci.yml
services:
mongo:
image: mongo:7
ports: ['27017:27017']
options: >-
--health-cmd "mongosh --eval 'db.runCommand({ping:1})'"
--health-interval 5s --health-retries 10How to prevent it
- Gate Mongo usage on a ping healthcheck.
- 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.
Related guides
MongoDB "MongoServerError: Authentication failed" in CIFix "MongoServerError: Authentication failed" in CI - MongoDB was reached but rejected the credentials or aut…
Redis "Connection refused" on 127.0.0.1:6379 in CIFix Redis "connect ECONNREFUSED 127.0.0.1:6379" in CI - the Redis service is not ready or not reachable on th…
Postgres "could not connect to server: Connection refused" in CIFix libpq "could not connect to server: Connection refused" in CI - the client could not reach Postgres, usua…