以下是在 Debian 上搭建 MongoDB 集群的指南:
更新系统软件包,添加 MongoDB 官方仓库并安装:
sudo apt update && sudo apt upgrade -y
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian bullseye/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt update
sudo apt install -y mongodb-org
在每个节点上创建或编辑 /etc/mongod.conf,示例配置如下:
net:
port: 27017
bindIp: 0.0.0.0
replication:
replSetName: rs0
storage:
dbPath: /data/db
journal:
enabled: true
启动并启用服务:
sudo systemctl start mongod
sudo systemctl enable mongod
在其中一个节点上初始化副本集,以一主两副本为例:
mongo --host <node1_ip> --port 27017
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "<node1_ip>:27017" },
{ _id: 1, host: "<node2_ip>:27017" },
{ _id: 2, host: "<node3_ip>:27017" }
]
})
在其他节点上使用 rs.add 命令添加节点。
若要搭建分片集群,需配置 Config Server 和 mongos:
sharding.clusterRole: configsvr 等参数,初始化副本集,如 rs.initiate({_id: "configRs", members: [...]})。sharding.clusterRole: shardsvr 的副本集,初始化后通过 sh.addShard 添加到集群,再用 sh.enableSharding 启用分片。使用 sh.status() 命令查看集群状态。