以下是在Ubuntu上配置MongoDB集群的步骤:
配置副本集
- 安装MongoDB:在所有节点上执行
sudo apt update,sudo apt install -y mongodb-org。 - 修改配置文件:在每台服务器上编辑
/etc/mongod.conf,添加replication: replSetName: "rs0"(rs0为副本集名称,可自定义)。 - 重启服务:在每个节点上执行
sudo systemctl restart mongod。 - 初始化副本集:在其中一台服务器上,通过
mongo命令连接数据库,执行rs.initiate(),再添加其他节点rs.add("节点IP:27017")。 - 验证状态:在
mongoshell中执行rs.status()查看副本集状态。
配置分片集群(可选)
- 配置配置服务器:至少准备三台服务器,创建配置目录,编辑配置文件设置
sharding.clusterRole: configsvr等参数,启动服务并初始化副本集。 - 配置分片服务器:为每个分片创建目录,编辑配置文件设置
sharding.clusterRole: shardsvr等参数,启动服务并初始化副本集。 - 配置Mongos路由器:编辑配置文件设置
sharding.configdb为配置服务器副本集地址,启动mongos。 - 添加分片:连接到
mongos,使用sh.addShard()添加分片。