MongoDB "MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017" in CI
The Node.js driver opened a TCP connection to 127.0.0.1:27017 and the OS refused it: no process is listening on that port. In CI this almost always means the mongod service or container is not running, not a driver bug.
What this error means
The MongoDB driver throws "MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017" as soon as your app or tests try to connect, before any query runs.
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (/app/node_modules/mongodb/lib/cmap/connect.js:387:20)Common causes
No mongod is running on the runner
The job connects to localhost:27017 but never started a mongod service container or a local mongod, so the port is closed.
The service container maps a different host or port
A service is defined but the driver points at the wrong host/port, or the container has not published 27017 to the job.
How to fix it
Add a mongo service container
- Declare a
mongoservice on the job so a mongod listens on 27017. - Point
MONGODB_URIatmongodb://localhost:27017. - Run tests only after the service is reachable.
services:
mongo:
image: mongo:7
ports:
- 27017:27017Start a local mongod when not using services
On a runner without a service container, start mongod in the background and give it a data directory.
mkdir -p /tmp/mongo-data
mongod --dbpath /tmp/mongo-data --fork --logpath /tmp/mongod.logHow to prevent it
- Define MongoDB as a service container so it starts with the job.
- Keep the connection host/port in sync with the published service port.
- Wait for the port to accept connections before running tests.