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.
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017Common 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.
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 10Wait for the ping in a loop
For docker-compose, poll until the admin ping returns ok.
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
doneHow to prevent it
- Add a
mongoshping healthcheck to the Mongo service. - Connect to the mapped
127.0.0.1:27017from steps. - Allow enough retries on slow runners for storage init.