Skip to content
Latchkey

MongoDB "MongoNetworkError ... ECONNREFUSED" before the container is ready in CI

The MongoDB container is starting but mongod is not yet listening on 27017 when your step connects, so the driver throws ECONNREFUSED. A mongosh ping healthcheck or wait loop fixes this readiness race.

What this error means

The first connection fails with "MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017", then succeeds once the container has warmed up.

Terminal
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

Common causes

The step connects before mongod is listening

After the container exists there is a window during which mongod initializes storage and is not yet accepting connections, so the connect is refused.

No healthcheck gates the dependent steps

Without a health command that runs a ping, GitHub Actions starts steps before Mongo is ready.

How to fix it

Add a mongosh ping healthcheck

Hold steps until a ping admin command succeeds.

.github/workflows/ci.yml
services:
  mongo:
    image: mongo:7
    ports: ['27017:27017']
    options: >-
      --health-cmd "mongosh --eval 'db.adminCommand({ ping: 1 })' --quiet"
      --health-interval 5s
      --health-timeout 5s
      --health-retries 10

Wait for the ping in a loop

For docker-compose, poll until the admin ping returns ok.

Terminal
until mongosh --host 127.0.0.1:27017 --quiet \
  --eval 'db.adminCommand({ ping: 1 }).ok' | grep -q 1; do
  echo "waiting for mongodb"; sleep 1
done

How to prevent it

  • Add a mongosh ping healthcheck to the Mongo service.
  • Connect to the mapped 127.0.0.1:27017 from steps.
  • Allow enough retries on slow runners for storage init.

Frequently asked questions

What causes "MongoDB "MongoNetworkError ECONNREFUSED""?
After the container exists there is a window during which mongod initializes storage and is not yet accepting connections, so the connect is refused.
How do I fix MongoDB "MongoNetworkError ECONNREFUSED"?
Hold steps until a ping admin command succeeds.

Related guides

References

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