搭建 MongoDB 副本集

适用场景

需要 MongoDB 自动故障切换、数据冗余和读扩展。副本集是三节点起步的最小生产形态,适合大多数业务;分片集群在数据量更大时再考虑。

前置条件

步骤

  1. 在三台节点生成相同的 Keyfile:
openssl rand -base64 756 > /etc/mongodb/keyfile
chmod 400 /etc/mongodb/keyfile
chown mongodb:mongodb /etc/mongodb/keyfile
  1. 配置 mongod.conf:
cat > /etc/mongod.conf <<'EOF'
storage:
  dbPath: /var/lib/mongodb
systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
net:
  port: 27017
  bindIp: 0.0.0.0
replication:
  replSetName: rs0
security:
  keyFile: /etc/mongodb/keyfile
EOF
  1. 启动三个节点:
systemctl enable --now mongod
systemctl status mongod
  1. 在主节点初始化副本集:
mongosh --host node1:27017
rs.initiate({
  _id: "rs0",
  members: [
    {_id: 0, host: "node1:27017", priority: 2},
    {_id: 1, host: "node2:27017", priority: 1},
    {_id: 2, host: "node3:27017", priority: 1}
  ]
})
rs.status()
  1. 创建管理员和业务用户:
use admin
db.createUser({user: "admin", pwd: "***", roles: ["root"]})
use app
db.createUser({user: "app", pwd: "***", roles: [{role: "readWrite", db: "app"}]})
  1. 应用连接串使用副本集地址:
mongodb://app:***@node1:27017,node2:27017,node3:27017/app?replicaSet=rs0
  1. 配置备份。使用 mongodump 或文件系统快照,备份从节点以减轻主节点压力。

验证

回滚

常见坑

相关命令