Skip to content
Latchkey

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
done

Add 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 10

How 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →