温馨提示×

DebianMongoDB怎么分片

小樊
38
2026-10-11 07:53:58
栏目: 云计算

在 Debian 上部署 MongoDB 分片集群(Sharded Cluster),核心组件包括:

  • Config Server(配置服务器):存储集群元数据
  • Mongos(路由):客户端访问入口
  • Shard(分片):实际存储数据的 mongod 实例

下面以 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 可多台

二、安装 MongoDB(所有节点)

sudo apt update
sudo apt install -y mongodb-org

验证:

mongod --version

三、部署 Config Server(3 台)

1. 修改配置文件

/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

2. 启动

sudo systemctl restart mongod

3. 初始化副本集(任意一台)

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" }
  ]
})

四、部署 Shard(每个分片是副本集)

1. Shard 配置文件

/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

2. 启动

sudo systemctl restart mongod

3. 初始化副本集

mongosh --port 27018
rs.initiate({
  _id: "shard1",
  members: [
    { _id: 0, host: "192.168.1.11:27018" }
  ]
})

如有多个节点,加入 members 即可


五、部署 Mongos(路由)

1. 新建 mongos 配置

/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

2. 启动 mongos

mongos -f /etc/mongos.conf

六、添加 Shard 到集群

连接 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)
✅ 生产环境务必使用副本集
✅ 分片键选择非常关键(避免热点)


如果你愿意,我可以:

  • 给你 单机模拟分片方案
  • 或 Docker / Debian 实战配置
  • 或 按你服务器数量定制拓扑

你现在是测试环境还是生产环境?

0 踩