Search code examples
node.jsmongodbdockermongoosereplicaset

MongoError: failed to connect to server [<docker-machine>:<port>] on first connect


Trying to connect MongoDB with replicaSet connection string using mongoose library. But didn't connect on the production server, its throw me back an error:

name: 'MongoError',
 message: 'failed to connect to server [test-machine:27018] on first connect [MongoError: getaddrinfo ENOTFOUND test-machine:27018 test-machine:27018]'   
var mongoose = require('mongoose') //version 4.13.6

var options = { "db": {
        "readPreference": "secondaryPreferred"
    },
    "replset": {
        "rs_name": "testReplica",
    }
}

var connection = mongoose.createConnection(`mongodb://localhost:27018/`,options);

connection.on('open', function () {
    console.log('We are connected')
})

connection.on('error', function (err) {
    console.log('Something went wrong')
    console.log(err)
})

Note: the above code working fine with a success message in/with my local machine.


Solution

  • This is a DNS resolution error.

    added test-machine to my /etc/hosts file