在Ubuntu上配置MongoDB集群(复制集)涉及几个步骤。以下是一个基本的指南,帮助你在Ubuntu上设置一个MongoDB复制集。
MongoDB安装:确保你已经在所有节点上安装了MongoDB。你可以使用以下命令安装MongoDB:
sudo apt update
sudo apt install -y mongodb-org
防火墙设置:确保防火墙允许MongoDB的默认端口(27017)通信。
在每个节点上编辑MongoDB配置文件(通常位于/etc/mongod.conf
),确保以下配置:
net:
port: 27017
bindIp: <节点IP地址>
replication:
replSetName: <复制集名称>
例如,如果你有三个节点,IP地址分别是192.168.1.1
, 192.168.1.2
, 和 192.168.1.3
,并且你想将复制集命名为rs0
,那么配置如下:
节点1 (192.168.1.1
):
net:
port: 27017
bindIp: 192.168.1.1
replication:
replSetName: rs0
节点2 (192.168.1.2
):
net:
port: 27017
bindIp: 192.168.1.2
replication:
replSetName: rs0
节点3 (192.168.1.3
):
net:
port: 27017
bindIp: 192.168.1.3
replication:
replSetName: rs0
重启MongoDB服务以应用更改:
sudo systemctl restart mongod
连接到任意一个MongoDB实例并初始化复制集:
mongo --host <节点IP地址> --port 27017
在mongo shell中运行以下命令:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "<节点IP地址>:27017" },
{ _id: 1, host: "<节点IP地址>:27017" },
{ _id: 2, host: "<节点IP地址>:27017" }
]
})
例如,对于节点1:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "192.168.1.1:27017" },
{ _id: 1, host: "192.168.1.2:27017" },
{ _id: 2, host: "192.168.1.3:27017" }
]
})
在mongo shell中运行以下命令来验证复制集的状态:
rs.status()
你应该看到所有节点都正常运行并且状态为SECONDARY
或PRIMARY
。
通过以上步骤,你应该能够在Ubuntu上成功配置一个MongoDB复制集。