温馨提示×

centos mongodb怎么配分片

小樊
35
2026-10-14 16:00:20
栏目: 云计算

下面给你一个在 CentOS 上配置 MongoDB 分片(Sharded Cluster)的实战步骤示例,适合学习和测试环境(生产环境会更复杂,比如鉴权、TLS、高可用等)。


一、MongoDB 分片集群架构说明

一个标准分片集群包含三类角色:

  1. Config Server(配置服务器):存储集群元数据
  2. Mongos(路由):客户端访问入口
  3. Shard(分片):真正存数据的 mongod

示例规划(单台 CentOS 测试):

角色 端口
Config Server 27019
Mongos 27017
Shard1 27018

生产环境建议:

  • Config Server 至少 3 个节点
  • 每个 Shard 是副本集(Replica Set)

二、安装 MongoDB(CentOS 7/8)

# 添加 yum 源
cat > /etc/yum.repos.d/mongodb-org.repo <<EOF
[mongodb-org]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
EOF

yum install -y mongodb-org

三、配置 Config Server

1. 创建目录

mkdir -p /data/configdb

2. 配置文件 /etc/mongod-config.conf

storage:
  dbPath: /data/configdb
net:
  port: 27019
  bindIp: 0.0.0.0
sharding:
  role: configsvr
replication:
  replSetName: configReplSet

3. 启动

mongod -f /etc/mongod-config.conf --fork

4. 初始化副本集

mongo --port 27019
rs.initiate({
  _id: "configReplSet",
  configsvr: true,
  members: [{ _id: 0, host: "localhost:27019" }]
})

四、配置 Shard(分片节点)

1. 创建目录

mkdir -p /data/shard1

2. 配置文件 /etc/mongod-shard1.conf

storage:
  dbPath: /data/shard1
net:
  port: 27018
  bindIp: 0.0.0.0
sharding:
  role: shardsvr
replication:
  replSetName: shard1ReplSet

3. 启动

mongod -f /etc/mongod-shard1.conf --fork

4. 初始化副本集

mongo --port 27018
rs.initiate({
  _id: "shard1ReplSet",
  members: [{ _id: 0, host: "localhost:27018" }]
})

五、启动 Mongos(路由)

配置文件 /etc/mongos.conf

net:
  port: 27017
  bindIp: 0.0.0.0
sharding:
  configDB: configReplSet/localhost:27019

启动

mongos -f /etc/mongos.conf --fork

六、添加 Shard 到集群

mongo --port 27017
sh.addShard("shard1ReplSet/localhost:27018")

查看状态:

sh.status()

七、启用数据库和集合分片

sh.enableSharding("testdb")

sh.shardCollection(
  "testdb.user",
  { user_id: "hashed" }
)

八、测试写入

use testdb
for (let i=0;i<10000;i++){
  db.user.insert({user_id:i, name:"user"+i})
}

查看数据分布:

db.user.getShardDistribution()

九、常用命令

sh.status()
sh.enableSharding("db")
sh.shardCollection("db.coll", {key:1})
sh.addShard("rsName/host:port")

十、生产建议(重要)

  • ✅ Config Server 必须 3 节点
  • ✅ Shard 使用 副本集
  • ✅ 开启 鉴权(auth)
  • ✅ 使用 防火墙 + 内网
  • ✅ 避免单点 Mongos(可多实例 + LB)

如果你需要:

  • ✅ 多机真实分片拓扑
  • ✅ 带账号密码的集群
  • ✅ Docker / Kubernetes 部署
  • ✅ 副本集 + 分片完整示例

告诉我你的环境,我可以直接给你一套可复制的配置。

0 踩