[英]Express can't connect to mongodb replica set when local mongo is stoped
I have a mongodb replica set
with the following config: 我有一个具有以下配置的mongodb replica set
:
Here is my Express code to connect to db (I use mongoose
as the ODM): 这是我连接到数据库的Express代码(我使用mongoose
作为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: 当M1发生故障时,M2或M3被选为primary
App3
, App2
和App3
仍然正常工作,但是App1
无法连接到replica set
并显示错误消息:
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
: 这是我在App1
上的mongodb配置:
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. 您不能在一个配置文件中混合多个节点的IP地址。
Your bindIp string 您的bindIp字符串
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. 依此类推...因此,您可以让localhost绑定和属于该节点的其他地址。
My initial answer was wrong because I thought that it has something to do with mongooos, what I don't know. 我最初的回答是错误的,因为我认为这与mongooos有关,这是我所不知道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.