mongodb副本集1主2从节点的配置方法示例

发布于:2025-03-01 ⋅ 阅读:(104) ⋅ 点赞:(0)

配置 MongoDB 副本集(1 主节点 + 2 从节点)的步骤如下:

环境准备

  • 3 台服务器,分别运行 MongoDB 实例。
  • 确保服务器之间网络互通。
  • 安装 MongoDB(版本需一致)。

配置步骤

1. 修改 MongoDB 配置文件

在每个节点的 mongod.conf 中启用副本集功能。

主节点配置primary.conf):

storage:
  dbPath: /var/lib/mongodb
replication:
  replSetName: rs0
net:
  bindIp: 0.0.0.0
  port: 27017

从节点 1 配置secondary1.conf):

storage:
  dbPath: /var/lib/mongodb
replication:
  replSetName: rs0
net:
  bindIp: 0.0.0.0
  port: 27017

从节点 2 配置secondary2.conf):

storage:
  dbPath: /var/lib/mongodb
replication:
  replSetName: rs0
net:
  bindIp: 0.0.0.0
  port: 27017

2. 启动 MongoDB 实例

在每个节点上启动 MongoDB 服务。

mongod --config /path/to/primary.conf
mongod --config /path/to/secondary1.conf
mongod --config /path/to/secondary2.conf

3. 初始化副本集

连接到主节点,初始化副本集。

mongo --host <主节点IP> --port 27017

在 MongoDB Shell 中执行:

rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "<主节点IP>:27017" },
    { _id: 1, host: "<从节点1IP>:27017" },
    { _id: 2, host: "<从节点2IP>:27017" }
  ]
})

4. 检查副本集状态

初始化后,检查副本集状态。

rs.status()

输出应显示 1 个 PRIMARY 和 2 个 SECONDARY 节点。

5. 验证数据同步

在主节点插入数据,检查从节点是否同步。

主节点插入数据

use testdb
db.testcollection.insert({ name: "example" })

从节点查询数据

mongo --host <从节点IP> --port 27017

在 MongoDB Shell 中执行:

rs.slaveOk()  # 允许从节点读取
db.testcollection.find()

总结

通过以上步骤,您可以配置一个包含 1 主 2 从的 MongoDB 副本集,确保数据的高可用性和冗余。


网站公告

今日签到

点亮在社区的每一天
去签到