温馨提示×

MongoDB分片集群在CentOS上如何搭建

小樊
32
2025-03-05 11:24:42
栏目: 云计算
GO开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上搭建MongoDB分片集群涉及多个步骤,包括配置服务器、配置分片、配置副本集等。以下是一个基本的指南:

1. 准备工作

  • 安装MongoDB

    sudo yum install -y mongodb-org
    
  • 启动MongoDB服务

    sudo systemctl start mongod
    sudo systemctl enable mongod
    

2. 配置服务器

你需要配置多个服务器来组成分片集群。假设我们有三个服务器:shard1, shard2, shard3

2.1 配置文件示例 (/etc/mongod.conf)

sharding:
  clusterRole: shardsvr

net:
  port: 27018
  bindIp: <服务器IP地址>

storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

2.2 启动每个服务器

sudo mongod --config /etc/mongod.conf

3. 配置副本集

每个分片应该是一个副本集。以下是配置副本集的步骤:

3.1 连接到MongoDB

mongo --port 27018

3.2 初始化副本集

rs.initiate(
  {
    _id: "shard1",
    members: [
      { _id: 0, host: "shard1_ip:27018" },
      { _id: 1, host: "shard1_ip:27019" },
      { _id: 2, host: "shard1_ip:27020" }
    ]
  }
)

重复上述步骤为shard2shard3配置副本集。

4. 配置配置服务器

配置服务器存储集群的元数据。

4.1 启动配置服务器

mongod --configsvr --replSet configReplSet --dbpath /var/lib/configdb --port 27019 --bind_ip <服务器IP地址>

4.2 初始化配置服务器副本集

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

5. 配置分片

将分片添加到集群中。

5.1 连接到mongos

mongos --configdb configReplSet/config_server_ip:27019 --port 27017

5.2 添加分片

sh.addShard("shard1/shard1_ip:27018,shard1_ip:27019,shard1_ip:27020")
sh.addShard("shard2/shard2_ip:27018,shard2_ip:27019,shard2_ip:27020")
sh.addShard("shard3/shard3_ip:27018,shard3_ip:27019,shard3_ip:27020")

6. 启用数据库和集合分片

sh.enableSharding("yourDatabaseName")
sh.shardCollection("yourDatabaseName.yourCollectionName", { "shardKey": 1 })

7. 验证配置

sh.status()

注意事项

  • 确保所有服务器之间的网络连接正常。
  • 配置文件中的IP地址和端口号要正确。
  • 根据实际需求调整副本集和分片的数量。

通过以上步骤,你可以在CentOS上搭建一个基本的MongoDB分片集群。根据实际需求,可能还需要进行更多的配置和优化。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在centos上搭建mongodb集群

0