当本地 mongo 停止时,Express 无法连接到 mongodb 副本集 [英] Express can't connect to mongodb replica set when local mongo is stoped

查看:43
本文介绍了当本地 mongo 停止时,Express 无法连接到 mongodb 副本集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下配置的 mongodb 副本集:

I have a mongodb replica set with the following config:

  • M1 (192.168.77.3) 主(宿主 App1)
  • M2 (192.168.77.4) 辅助(宿主 App2)
  • M3 (192.168.77.5) 辅助(宿主 App3)
  • M4 仲裁员

这是我连接到数据库的 Express 代码(我使用 mongoose 作为 ODM):

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()
})

应用程序按预期运行.当 M1 宕机时,M2 或 M3 被选为 primaryApp2App3 仍在工作,但 App1 无法连接到副本集,错误消息:

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]

这是我在 App1 上的 mongodb 配置:

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

我的配置有问题吗?

推荐答案

您不能在一个配置文件中混合多个节点的 IP 地址.

You CAN NOT mix IP-addresses of multiple nodes at one single config file.

你的 bindIp 字符串

Your bindIp string

bindIp: [127.0.0.1, 192.168.77.4, 192.168.77.5]

应该是

bindIp: "127.0.0.1,192.168.77.3"

在第一个节点和

bindIp: "127.0.0.1,192.168.77.4"

在第二个节点.依此类推...因此,您可以拥有 localhost 绑定和属于该节点的其他地址.

at second node. And so on... So, you can have localhost bind and other addresses what belong to that node.

我最初的回答是错误的,因为我认为它与 mongooos 有关,而我不知道.

My initial answer was wrong because I thought that it has something to do with mongooos, what I don't know.

这篇关于当本地 mongo 停止时,Express 无法连接到 mongodb 副本集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆