Search code examples
node.jsdatabasemongodberror-handlingconnection

Strange MongoDB connection issue only on localhost


I have 3 servers which run a MongoDB replicaset, 1 primary, 1 secondary, 1 arbiter. And I have problem connecting to this replicaset. Tested with a test.js file which runs on localhost and a spare server.

  • Connect from localhost, node 6.5.0: OK
  • Connect from localhost, node 10.15.1: FAILED
  • Connect from the spare server, node 6.5.0: OK
  • Connect from the spare server, node 10.15.1: OK

Here's my test.js file:

const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://root:password"+
"@mgdb1.mydomain,mgdb2.mydomain/vApp?replicaSet=rs0&authSource=admin";

console.log("Connecting...");
MongoClient.connect(url,(err,client)=>{
  if (err!=null){
    console.log("Error:",err);
    return;
  }

  console.log("Connected.");
  process.exit();
});

The strange thing is that it shows ECONNREFUSED error, but not at the IP of the 3 servers in the replicaset, it's the IP in range of my ISP. So why does it fail afterConnect? It shows TCPConnectWrap.afterConnect, does it mean the connection is already made?

The error is this way:

Connecting...
(node:1412) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Error: { Error: connect ECONNREFUSED 125.235.4.59:27017
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '125.235.4.59',
  port: 27017 }

Edit:

My current work-around is connecting directly to the primary server without replicaset=rs0, however, this is not the desired manner.


Solution

  • I found out the problem. When created the replica set on a group of machines on cloud, the addresses to the servers are server names which are known only by other machines on the same server LAN. On localhost in office, there are no such server names.

    Work-around 1:

    • Connect only to the primary or secondary server

    Work-around 2:

    • Edit /etc/hosts file (or c:\windows\system32\drivers\etc\hosts)
    • Point the name of the servers to their appropriate IPs