以下是在Debian上配置MongoDB集群的步骤,包含副本集和分片集群两种场景:
安装MongoDB
sudo apt update && sudo apt install -y mongodb-org
(需提前导入公钥并添加官方源,参考)
创建数据、日志目录
sudo mkdir -p /data/db /var/log/mongodb
sudo chown -R mongodb:mongodb /data /var/log/mongodb
修改配置文件
编辑 /etc/mongod.conf,添加以下内容(所有节点需一致):
storage:
dbPath: /data/db
net:
port: 27017
bindIp: 0.0.0.0
replication:
replSetName: rs0 # 副本集名称
security:
keyFile: /etc/mongodb-keyfile # 密钥文件路径(用于节点间认证)
(参考)
生成并分发密钥文件
openssl rand -base64 756 > /etc/mongodb-keyfile
chmod 600 /etc/mongodb-keyfile
scp /etc/mongodb-keyfile user@其他节点:/etc/mongodb-keyfile
初始化副本集
在主节点执行:
mongo --port 27017
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "node1:27017" },
{ _id: 1, host: "node2:27017" },
{ _id: 2, host: "node3:27017", arbiterOnly: true } # 可选仲裁节点
]
})
(参考)
添加其他节点
在主节点执行:
rs.add("node2:27017")
rs.add("node3:27017")
(参考)
验证副本集状态
rs.status()
(参考)
部署配置服务器副本集
storage:
dbPath: /data/configdb
net:
port: 27019
replication:
replSetName: configReplSet
rs.initiate({
_id: "configReplSet",
members: [
{ _id: 0, host: "config1:27019" },
{ _id: 1, host: "config2:27019" },
{ _id: 2, host: "config3:27019" }
]
})
部署分片服务器副本集
rs.initiate({
_id: "shard1",
members: [
{ _id: 0, host: "shard1-node1:27017" },
{ _id: 1, host: "shard1-node2:27017" }
]
})
启动mongos路由器
mongos --configdb configReplSet/config1:27019,config2:27019,config3:27019 --port 27017
添加分片到集群
sh.addShard("shard1/shard1-node1:27017,shard1-node2:27017")
启用分片
sh.enableSharding("数据库名")
sh.shardCollection("数据库名.集合名", { "_id": "hashed" })
rs.status()sh.status()systemctl管理MongoDB服务,确保开机自启。参考来源: