在 Debian 上部署 MongoDB 分片集群(Sharded Cluster),核心组件包括:
下面以 MongoDB 6.x / 7.x(Debian 11/12) 为例,讲清楚完整流程和关键配置。
假设 3 台 Debian 服务器:
| 主机 | IP | 角色 |
|---|---|---|
| node1 | 192.168.1.11 | config server + shard1 + mongos |
| node2 | 192.168.1.12 | shard2 |
| node3 | 192.168.1.13 | shard3 |
生产环境建议:
- Config Server 3 台
- 每个 Shard 副本集(推荐)
- Mongos 可多台
sudo apt update
sudo apt install -y mongodb-org
验证:
mongod --version
/etc/mongod.conf
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
bindIp: 0.0.0.0
port: 27019
replication:
replSetName: configReplSet
sharding:
clusterRole: configsvr
sudo systemctl restart mongod
mongosh --port 27019
rs.initiate({
_id: "configReplSet",
configsvr: true,
members: [
{ _id: 0, host: "192.168.1.11:27019" },
{ _id: 1, host: "192.168.1.12:27019" },
{ _id: 2, host: "192.168.1.13:27019" }
]
})
/etc/mongod.conf
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
net:
bindIp: 0.0.0.0
port: 27018
replication:
replSetName: shard1
sharding:
clusterRole: shardsvr
sudo systemctl restart mongod
mongosh --port 27018
rs.initiate({
_id: "shard1",
members: [
{ _id: 0, host: "192.168.1.11:27018" }
]
})
如有多个节点,加入 members 即可
/etc/mongos.conf
systemLog:
destination: file
path: /var/log/mongodb/mongos.log
net:
bindIp: 0.0.0.0
port: 27017
sharding:
configDB: configReplSet/192.168.1.11:27019,192.168.1.12:27019,192.168.1.13:27019
mongos -f /etc/mongos.conf
连接 mongos:
mongosh --port 27017
sh.addShard("shard1/192.168.1.11:27018")
sh.addShard("shard2/192.168.1.12:27018")
sh.addShard("shard3/192.168.1.13:27018")
查看:
sh.status()
sh.enableSharding("testdb")
sh.shardCollection(
"testdb.users",
{ user_id: "hashed" }
)
use testdb
for (let i = 0; i < 10000; i++) {
db.users.insertOne({ user_id: i, name: "user" + i })
}
db.users.getShardDistribution()
✅ 防火墙必须放行端口
✅ 所有节点时间同步(NTP)
✅ 生产环境务必使用副本集
✅ 分片键选择非常关键(避免热点)
如果你愿意,我可以:
你现在是测试环境还是生产环境?