Skip to content
Latchkey

MongoDB connects before mongod prints "waiting for connections" in CI

mongod is starting but has not yet logged "waiting for connections on port 27017". Your tests connect during that window and fail intermittently. The fix is to wait for readiness, not to add a fixed sleep.

What this error means

Connection errors that pass on retry, with mongod eventually logging "waiting for connections on port 27017". Failures cluster at the very start of the job.

node
MongoNetworkError: connection <monitor> to 127.0.0.1:27017 closed
# mongod later logs:
{"t":{"$date":"..."},"s":"I","c":"NETWORK","msg":"Waiting for connections","attr":{"port":27017}}

Common causes

The service container is not ready yet

The mongod process is up but still initializing storage and has not opened the listener when the first connection is attempted.

A fixed sleep is too short

A hardcoded sleep 5 sometimes beats mongod startup on a busy runner, so the race reappears.

How to fix it

Add a healthcheck to the service

  1. Give the mongo service a healthcheck that runs a ping.
  2. GitHub Actions waits for the service to be healthy before the job steps run.
  3. Remove any fixed sleep once the healthcheck gates startup.
.github/workflows/ci.yml
services:
  mongo:
    image: mongo:7
    ports: ['27017:27017']
    options: >-
      --health-cmd "mongosh --eval 'db.adminCommand({ping:1})'"
      --health-interval 5s --health-timeout 5s --health-retries 10

Poll for readiness in a step

When you run mongod yourself, loop on a ping until it responds instead of sleeping a fixed time.

Terminal
until mongosh --quiet --eval 'db.adminCommand({ping:1})' >/dev/null 2>&1; do
  echo "waiting for mongod"; sleep 1
done

How to prevent it

  • Gate the job on a service healthcheck instead of a sleep.
  • Poll for a successful ping before connecting from tests.
  • Fail fast with a bounded retry so a stuck mongod is visible.

Related guides

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