在Ubuntu上搭建MongoDB分片集群涉及多个步骤,包括配置配置服务器、分片服务器和路由服务器(mongos)。以下是一个基本的指南:
1. 准备工作
确保你已经安装了MongoDB,并且所有节点都可以通过网络互相通信。
2. 配置配置服务器
配置服务器存储集群的元数据。通常需要至少三个配置服务器以实现高可用性。
启动配置服务器
mongod --configsvr --replSet <configReplSetName> --dbpath <configDBPath> --port <configPort>
例如:
mongod --configsvr --replSet configReplSet --dbpath /data/configdb --port 27019
初始化配置服务器副本集
连接到其中一个配置服务器并初始化副本集:
mongo --port 27019
在mongo shell中执行:
rs.initiate(
{
_id: "configReplSetName",
configsvr: true,
members: [
{ _id : 0, host : "cfg1.example.com:27019" },
{ _id : 1, host : "cfg2.example.com:27019" },
{ _id : 2, host : "cfg3.example.com:27019" }
]
}
)
3. 配置分片服务器
分片服务器存储实际的数据。
启动分片服务器
mongod --shardsvr --replSet <shardReplSetName> --dbpath <shardDBPath> --port <shardPort>
例如:
mongod --shardsvr --replSet shardReplSet --dbpath /data/shard1 --port 27018
初始化分片服务器副本集
连接到其中一个分片服务器并初始化副本集:
mongo --port 27018
在mongo shell中执行:
rs.initiate(
{
_id: "shardReplSetName",
members: [
{ _id : 0, host : "shard1.example.com:27018" },
{ _id : 1, host : "shard2.example.com:27018" },
{ _id : 2, host : "shard3.example.com:27018" }
]
}
)
4. 配置路由服务器(mongos)
路由服务器是应用程序与分片集群之间的接口。
启动mongos
mongos --configdb <configReplSetName>/<configServer1>:<configPort>,<configServer2>:<configPort>,<configServer3>:<configPort> --port <mongosPort>
例如:
mongos --configdb configReplSet/cfg1.example.com:27019,cfg2.example.com:27019,cfg3.example.com:27019 --port 27017
5. 添加分片到集群
连接到mongos并添加分片:
mongo --port 27017
在mongo shell中执行:
sh.addShard("shardReplSetName/shard1.example.com:27018,shard2.example.com:27018,shard3.example.com:27018")
6. 启用数据库和集合分片
连接到mongos并启用数据库和集合分片:
sh.enableSharding("<databaseName>")
sh.shardCollection("<databaseName>.<collectionName>", { "<shardKey>": 1 })
例如:
sh.enableSharding("mydatabase")
sh.shardCollection("mydatabase.mycollection", { "userId": 1 })
7. 验证分片集群
连接到mongos并查看分片状态:
sh.status()
注意事项
- 确保所有节点的时间同步。
- 配置防火墙以允许MongoDB端口通信。
- 根据实际需求调整配置,例如增加更多的分片或配置服务器。
通过以上步骤,你应该能够在Ubuntu上成功搭建一个MongoDB分片集群。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1344281.html