Mogodb server: connect ECONNREFUSED 127.0.0.1:27017

I’m trying to connect to a new mongodb server from my node app but I get this error.

I am sure that the server is running because,
when I’m trying to connect from Compass, I have no problems.

App.mjs

import { MongoClient, AuthMechanism, Db } from "mongodb";


const uri ="mongodb://localhost:27017/";

const client = new MongoClient(uri);

async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();
    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

const print_dir = (msg) => {
  return console.dir(msg, {depth: null})
}

run().catch(print_dir);


Error message
  MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
      at Timeout._onTimeout (/home/USER/PATH/node_modules/mongodb/lib/sdam/topology.js:277:38)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7) {
    reason: TopologyDescription {
      type: 'Unknown',
      servers: Map(1) {
        'localhost:27017' => ServerDescription {
          address: 'localhost:27017',
          type: 'Unknown',
          hosts: [],
          passives: [],
          arbiters: [],
          tags: {},
          minWireVersion: 0,
          maxWireVersion: 0,
          roundTripTime: -1,
          lastUpdateTime: 456323,
          lastWriteDate: 0,
          error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
              at connectionFailureError (/home/USER/PATH/node_modules/mongodb/lib/cmap/connect.js:383:20)
              at Socket.<anonymous> (/home/USER/PATH/node_modules/mongodb/lib/cmap/connect.js:307:22)
              at Object.onceWrapper (node:events:628:26)
              at Socket.emit (node:events:513:28)
              at emitErrorNT (node:internal/streams/destroy:157:8)
              at emitErrorCloseNT (node:internal/streams/destroy:122:3)
              at processTicksAndRejections (node:internal/process/task_queues:83:21) {
            cause: Error: connect ECONNREFUSED 127.0.0.1:27017
                at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
              errno: -111,
              code: 'ECONNREFUSED',
              syscall: 'connect',
              address: '127.0.0.1',
              port: 27017
            },
            [Symbol(errorLabels)]: Set(1) { 'ResetPool' }
          },
          topologyVersion: null,
          setName: null,
          setVersion: null,
          electionId: null,
          logicalSessionTimeoutMinutes: null,
          primary: null,
          me: null,
          '$clusterTime': null
        }
      },
      stale: false,
      compatible: true,
      heartbeatFrequencyMS: 10000,
      localThresholdMS: 15,
      setName: null,
      maxElectionId: null,
      maxSetVersion: null,
      commonWireVersion: 0,
      logicalSessionTimeoutMinutes: null
    },
    code: undefined,
    [Symbol(errorLabels)]: Set(0) {}
  }

Dev OS: Ubuntu 20.04.5 LTS (WSL 2)
Node: v16.17.0
mongodb node driver: v5.0.0

OS: Windows 10
MongoServer: 6.0 (default config)

The fact that you mentioned 2 OS

and

makes me think that you do not understand localhost correctly.

If mongod is running on Windows 10 and you try to connect from your node application running on Ubuntu, localhost is definitively note the way you should connect. Your localhost in Windows that let you connect to your Windows’ mongod is not the same localhost as your Ubuntu machine running your host.

The host localhost is really your local host. It means localhost on Windows is Windows and localhost on Ubuntu is Ubuntu. If you want to connect to mongod running on Windows from your app running on Ubuntu you will need to specify something else than localhost. The host name of your Windows machine is a likely candidate.

Since I could access Linux apps running on localhost from Windows,
I thought, I could also do the inverse, access Windows apps from Linux.
I believed the were sharing the same localhost, a mistake as you said.

To solve the problem, I followed the steps by sylvix on this github issue:

1 Like

The connection stopped working again, after converting to a Replica Set following the guide here.

The database is running and I’m able to connect with Compass.

I have also allowed mongos.exe and mongod.exe to Firewall through 'Panel\System and Security\Windows Defender Firewall\Allowed apps'.

When I try to connect from WSL I get MongoServerSelectionError: connect ECONNREFUSED 127.0.1.1:27017, but, the mongod.log has the followng lines when trying to connect from WSL:

{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34488","uuid":"458b6f43-275c-4067-9b01-a39bf657cf6e","connectionId":67,"connectionCount":1}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34490","uuid":"8a3b9610-4bdb-424b-9dd7-5b097eaee1af","connectionId":68,"connectionCount":2}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34492","uuid":"0a23f7f1-be9b-47d9-bd7d-0993c1ac2628","connectionId":69,"connectionCount":3}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34496","uuid":"b7649e80-90ba-4f9f-a602-6314d45c13c0","connectionId":70,"connectionCount":4}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34494","uuid":"efdf35b6-45fe-4ebc-abbf-6ff71dbbe898","connectionId":71,"connectionCount":5}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34498","uuid":"c8ac80e7-4f9c-4d62-9d85-ebe86614ccc6","connectionId":72,"connectionCount":6}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34502","uuid":"6fbe4774-bc6f-4853-89ba-daecb7de3d6d","connectionId":73,"connectionCount":7}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34504","uuid":"0845ebee-8913-4aea-b25f-1b1c5b1d1f12","connectionId":74,"connectionCount":8}}
{"ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.22.36.92:34500","uuid":"4649ce63-a456-4057-8cd1-f3ae6306aa64","connectionId":75,"connectionCount":9}}
{"ctx":"conn67","msg":"client metadata","attr":{"remote":"172.22.36.92:34488","client":"conn67","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn68","msg":"client metadata","attr":{"remote":"172.22.36.92:34490","client":"conn68","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn69","msg":"client metadata","attr":{"remote":"172.22.36.92:34492","client":"conn69","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn71","msg":"client metadata","attr":{"remote":"172.22.36.92:34494","client":"conn71","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn70","msg":"client metadata","attr":{"remote":"172.22.36.92:34496","client":"conn70","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn72","msg":"client metadata","attr":{"remote":"172.22.36.92:34498","client":"conn72","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn75","msg":"client metadata","attr":{"remote":"172.22.36.92:34500","client":"conn75","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn73","msg":"client metadata","attr":{"remote":"172.22.36.92:34502","client":"conn73","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn74","msg":"client metadata","attr":{"remote":"172.22.36.92:34504","client":"conn74","doc":{"driver":{"name":"nodejs","version":"4.13.0"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"5.10.102.1-microsoft-standard-WSL2"},"platform":"Node.js v16.17.0, LE (unified)|Node.js v16.17.0, LE (unified)"}}}
{"ctx":"conn67","msg":"Connection ended","attr":{"remote":"172.22.36.92:34488","uuid":"458b6f43-275c-4067-9b01-a39bf657cf6e","connectionId":67,"connectionCount":8}}
{"ctx":"conn68","msg":"Connection ended","attr":{"remote":"172.22.36.92:34490","uuid":"8a3b9610-4bdb-424b-9dd7-5b097eaee1af","connectionId":68,"connectionCount":7}}
{"ctx":"conn69","msg":"Connection ended","attr":{"remote":"172.22.36.92:34492","uuid":"0a23f7f1-be9b-47d9-bd7d-0993c1ac2628","connectionId":69,"connectionCount":6}}
{"ctx":"conn71","msg":"Connection ended","attr":{"remote":"172.22.36.92:34494","uuid":"efdf35b6-45fe-4ebc-abbf-6ff71dbbe898","connectionId":71,"connectionCount":5}}
{"ctx":"conn70","msg":"Connection ended","attr":{"remote":"172.22.36.92:34496","uuid":"b7649e80-90ba-4f9f-a602-6314d45c13c0","connectionId":70,"connectionCount":4}}
{"ctx":"conn72","msg":"Connection ended","attr":{"remote":"172.22.36.92:34498","uuid":"c8ac80e7-4f9c-4d62-9d85-ebe86614ccc6","connectionId":72,"connectionCount":3}}
{"ctx":"conn75","msg":"Connection ended","attr":{"remote":"172.22.36.92:34500","uuid":"4649ce63-a456-4057-8cd1-f3ae6306aa64","connectionId":75,"connectionCount":2}}
{"ctx":"conn73","msg":"Connection ended","attr":{"remote":"172.22.36.92:34502","uuid":"6fbe4774-bc6f-4853-89ba-daecb7de3d6d","connectionId":73,"connectionCount":1}}
{"ctx":"conn74","msg":"Connection ended","attr":{"remote":"172.22.36.92:34504","uuid":"0845ebee-8913-4aea-b25f-1b1c5b1d1f12","connectionId":74,"connectionCount":0}}

So it seems to be a Firewall issue. I don’t know what else I have to do to fix it.

If your application generates

the mongod.log is useless. Your application never connected to the server. The log you share are valid connections, probably the ones made by

Most likely it is not a firewall issue. 127.0.1.1 is probably not the address of your replica set.

Share the connection string you used to connect with Compass. Where is running Compass? Where is running mongod? Where is running the code generating the ECONNREFUSED?

Mongodb Server

mongod and Compass is running on Windows.
the Compass connection string is mongodb://localhost:27017/DB_NAME

the mongod.cfg is this:

storage:
  dbPath: C:\Program Files\MongoDB\Server\6.0\data\db
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path:  C:\Program Files\MongoDB\Server\6.0\log\mongod.log

net:
  port: 27017
  bindIp: 0.0.0.0

replication:
  replSetName: rs0
  enableMajorityReadConcern: true

App

The app I’m trying to connect from, is running on Ubuntu WSL2 on the Windows machine mentioned above.
The app connection string is mongodb://HOST_IP:27017/DB_NAME, where HOST_IP IP is the address of the host machine, obtained by running the command cat /etc/resolv.conf, as shown here.

USER@WINDOWS:~$ cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver [HOST_IP]

Try with 172.22.36.92 for HOST_IP.

The host nameserver is NOT necessarily the IP of the Windows machine. How do you connect to your linux machine from your Windows machine? How do you connect to your Windows machine from your linux machine.

HOST_IP has to be address of the Windows machine where mongod is running.

I was trying with 172.22.36.92 and did not work.
the database was receiving the connection request from the app,
as you can see from the mongod.log I provided before,
but the app was not receiving the reply from the mongodb.

172.22.36.92 is not static it changes with every reboot and to find the new IP have to run cat /etc/resolv.conf from the WSL shell.

What are the IP addresses of your Windows machine?

from ipconfig:
IPv4 Address. . . . . . . . . . . : 192.168.100.6

That is the address that should work for your application on Linux that wants to connect to your Windows’ mongod.

But I am surprise that you do not have a second IP address in the 172.22.36.0 network.