在 CentOS 上配置 MongoDB 的主从(副本集方式,推荐),步骤如下(以 MongoDB 4.x/5.x 为例,CentOS 7/8 通用)。
假设有 3 台机器(最少 3 台,或 1 主 1 从 1 仲裁):
| 角色 | IP |
|---|---|
| Primary | 192.168.1.10 |
| Secondary | 192.168.1.11 |
| Arbiter(可选) | 192.168.1.12 |
⚠️ MongoDB 已不推荐老式 master-slave,统一使用 Replica Set(副本集)
# 创建 repo
cat > /etc/yum.repos.d/mongodb-org.repo <<EOF
[mongodb-org]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc
EOF
yum install -y mongodb-org
systemctl enable mongod
编辑:
vi /etc/mongod.conf
关键配置:
net:
bindIp: 0.0.0.0
port: 27017
replication:
replSetName: rs0
bindIp至少包含本机 IP 和127.0.0.1
启动:
systemctl start mongod
连接 MongoDB:
mongo
执行:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "192.168.1.10:27017" },
{ _id: 1, host: "192.168.1.11:27017" },
{ _id: 2, host: "192.168.1.12:27017", arbiterOnly: true }
]
})
查看状态:
rs.status()
在 Primary:
use test
db.test.insert({a:1})
在 Secondary:
rs.slaveOk() # 老版本
# 或
rs.secondaryOk() # 新版本
use test
db.test.find()
rs.isMaster()
rs.add("192.168.1.13:27017")
rs.remove("192.168.1.13:27017")
firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload
✅ 推荐方式:Replica Set(一主多从 + 仲裁)
❌ 不推荐:master/slave 模式(已废弃)
如果你只有 1 台 CentOS 服务器,我也可以教你 单机多实例主从配置。