Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Node.js cannot connect to MongoDB: ECONNREFUSED on port 27017

ErrorMongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Short answer

ECONNREFUSED means nothing accepted the connection at that address and port. In Docker Compose the usual cause is using localhost inside the app container, where it points at the app itself; use the Mongo service name. Other causes: mongod starting later than the app, localhost resolving to IPv6, or a firewall.

  • Applies to Node.js 22, Mongoose 8, MongoDB 8.0, Docker Compose 2
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Check whether anything listens on 27017 where the app is running. On the host use ss; inside a container, ask Compose which services are up and read the database log.

    sudo ss -ltn | grep 27017
    docker compose ps
    docker compose logs --tail 30 mongo
  2. 2Match what you see, then jump to its fix

    1. 1ECONNREFUSED 127.0.0.1:27017 in a Compose project while the mongo container is healthyThe app container uses localhost, which is the app container itselfFix
    2. 2Fails right after docker compose up, then works if you restart only the appThe app starts before MongoDB is ready to accept connectionsFix
    3. 3The error shows ::1:27017, or works with 127.0.0.1 and fails with localhostlocalhost resolves to IPv6 but MongoDB listens on IPv4Fix
    4. 4Nothing listens on 27017 in the first-step output, or it listens only on the machine that is not yoursmongod is not running, or a firewall blocks the portFix

What does the error look like?

  • MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
  • MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
  • MongoServerSelectionError: connect ECONNREFUSED ::1:27017

Cause 1 of 4

The app container uses localhost, which is the app container itself

1Check

Each container has its own network namespace. Containers on one Compose network reach each other by service name, on the container port, so a connection string with localhost never leaves the app container.

docker compose exec app printenv MONGO_URL
grep -n "mongo" docker-compose.yml compose.yaml 2>/dev/null

2Fix

Use the service name as host and the container port. The host port in a ports mapping only matters for connections from outside the network.

services:
  app:
    environment:
      MONGO_URL: mongodb://mongo:27017/myapp
  mongo:
    image: mongo:8

3Verify

Restart the stack and watch the app log connect.

docker compose up -d
docker compose logs --tail 20 app

Confirmed by docs.docker.com

Did this fix it?

Cause 2 of 4

The app starts before MongoDB is ready to accept connections

1Check

Compose by default waits until a dependency container is running, not until it is ready.

docker compose logs mongo | grep -i "waiting for connections"

2Fix

Give mongo a healthcheck and make the app wait for it to be healthy.

services:
  mongo:
    image: mongo:8
    healthcheck:
      test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ ping: 1 }).ok"]
      interval: 10s
      retries: 5
  app:
    depends_on:
      mongo:
        condition: service_healthy

3Verify

Bring the stack up from stopped; the app connects on the first try.

docker compose down && docker compose up -d
docker compose logs --tail 20 app

Confirmed by docs.docker.com

Did this fix it?

Cause 3 of 4

localhost resolves to IPv6 but MongoDB listens on IPv4

1Check

In Node.js 17 and later, the resolver can return an IPv6 address first. If mongod is on IPv4 only, the client is refused.

node -e "require('dns').lookup('localhost', {all:true}, (e,a)=>console.log(a))"

2Fix

Write 127.0.0.1 in the connection string, or ask the driver for IPv4 with family: 4.

await mongoose.connect('mongodb://127.0.0.1:27017/myapp');
// or: mongoose.connect(uri, { family: 4 })

3Verify

The connect call resolves and queries run.

node -e "require('mongoose').connect('mongodb://127.0.0.1:27017/myapp').then(()=>{console.log('ok');process.exit(0)})"

Confirmed by mongodb.com

Did this fix it?

Cause 4 of 4

mongod is not running, or a firewall blocks the port

1Check

MongoDB uses 27017 by default. A stopped service has no listener, and a firewall between the app and database host drops or refuses the traffic.

sudo systemctl status mongod
sudo ss -ltn | grep 27017

2Fix

Start the service. If the database is on another host, open 27017 only to the app's address, and give it a fail-fast timeout so a bad address shows up quickly.

sudo systemctl start mongod
# in the app
mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });

3Verify

The port is now listening and the app connects.

sudo ss -ltn | grep 27017

Confirmed by mongoosejs.com

Did this fix it?

How do I stop it coming back?

  • Read the MongoDB host from an environment variable and set it to the service name in Compose, 127.0.0.1 on a laptop.
  • Use a healthcheck plus service_healthy for every database your app needs at boot.
  • Wrap the first mongoose.connect in try/catch and exit with a clear message, because the driver does not retry the first connection for you.
  • Open a database port to the network only for the hosts that need it.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.