Skip to content
Latchkey

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.

node
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

  1. Declare a mongo service on the job so a mongod listens on 27017.
  2. Point MONGODB_URI at mongodb://localhost:27017.
  3. Run tests only after the service is reachable.
.github/workflows/ci.yml
services:
  mongo:
    image: mongo:7
    ports:
      - 27017:27017

Start 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.

Terminal
mkdir -p /tmp/mongo-data
mongod --dbpath /tmp/mongo-data --fork --logpath /tmp/mongod.log

How 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.

Frequently asked questions

What causes ""connect ECONNREFUSED 127.0.0.1:27017""?
The job connects to localhost:27017 but never started a mongod service container or a local mongod, so the port is closed.
How do I fix "connect ECONNREFUSED 127.0.0.1:27017"?
Add a mongo service container

Related guides

References

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