I have a mongodb replica set with the following config:
- M1 (192.168.77.3) primary (host App1)
- M2 (192.168.77.4) secondary (host App2)
- M3 (192.168.77.5) secondary (host App3)
- M4 arbitrator
Here is my Express code to connect to db (I use mongoose as the ODM):
const config = {
db: `mongodb://192.168.77.3,192.168.77.4,192.168.77.5/mydb`,
dbOptions: {
useMongoClient: true,
reconnectTries: Number.MAX_VALUE,
replicaSet: process.env.REPLICA_SET,
poolSize: 100,
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS: 300000,
w: 1
}
}
mongoose.connect(config.db, config.dbOptions, (error) => {
if (error) {
console.log('Error on connecting to th db: ', error)
console.log('\x1b[31m', '*** PLEASE CONNECT TO DATABASE BEFORE RUN SERVER', '\x1b[0m')
process.exit(1)
}
callback()
})
The app works as expected.
When M1 get down, either M2 or M3 get elected to be the primary, the App2 and App3 still working, BUT the App1 CAN'T connect to the replica set with the error message:
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
This is my mongodb config on App1:
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: [127.0.0.1, 192.168.77.3]
replication:
oplogSizeMB: 3000
replSetName: my_rs
Is there any wrong in my config?
You CAN NOT mix IP-addresses of multiple nodes at one single config file.
Your bindIp string
bindIp: [127.0.0.1, 192.168.77.4, 192.168.77.5]should be
bindIp: "127.0.0.1,192.168.77.3"at first node and
bindIp: "127.0.0.1,192.168.77.4"at second node. And so on... So, you can have localhost bind and other addresses what belong to that node.
My initial answer was wrong because I thought that it has something to do with mongooos, what I don't know.