在Debian上配置MongoDB的副本集认证需要以下几个步骤:
首先,确保你已经在Debian上安装了MongoDB。你可以使用以下命令来安装:
sudo apt update
sudo apt install -y mongodb
编辑每个MongoDB实例的配置文件(通常位于 /etc/mongod.conf
),确保它们监听相同的端口,并且配置副本集名称。
例如,假设你有三个MongoDB实例,分别运行在不同的服务器上,配置文件可能如下所示:
服务器1:
net:
port: 27017
bindIp: 192.168.1.1
replication:
replSetName: rs0
security:
authorization: enabled
服务器2:
net:
port: 27017
bindIp: 192.168.1.2
replication:
replSetName: rs0
security:
authorization: enabled
服务器3:
net:
port: 27017
bindIp: 192.168.1.3
replication:
replSetName: rs0
security:
authorization: enabled
启动每个MongoDB实例:
sudo systemctl start mongod
连接到其中一个MongoDB实例并初始化副本集:
mongo --host 192.168.1.1 --port 27017
在Mongo shell中执行以下命令:
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" }
]
}
)
在MongoDB shell中创建一个管理用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["root"]
})
然后,为副本集中的每个成员创建一个用户:
use your_database
db.createUser({
user: "replicaUser",
pwd: "replica_password",
roles: ["readWrite", "dbAdmin"]
})
编辑每个MongoDB实例的配置文件,添加身份验证相关的配置:
服务器1:
security:
authorization: enabled
keyFile: /var/lib/mongodb/keyfile
服务器2:
security:
authorization: enabled
keyFile: /var/lib/mongodb/keyfile
服务器3:
security:
authorization: enabled
keyFile: /var/lib/mongodb/keyfile
生成密钥文件并分发到所有服务器:
sudo dd if=/dev/urandom of=/var/lib/mongodb/keyfile bs=512 count=1
sudo chmod 400 /var/lib/mongodb/keyfile
sudo chown mongodb:mongodb /var/lib/mongodb/keyfile
将密钥文件复制到所有服务器的相同路径:
sudo scp /var/lib/mongodb/keyfile mongodb@192.168.1.2:/var/lib/mongodb/
sudo scp /var/lib/mongodb/keyfile mongodb@192.168.1.3:/var/lib/mongodb/
重启每个MongoDB实例以应用配置更改:
sudo systemctl restart mongod
再次连接到MongoDB shell并验证副本集状态:
mongo --host 192.168.1.1 --port 27017 -u admin -p your_password --authenticationDatabase admin
rs.status()
你应该看到副本集的状态为 SECONDARY
或 PRIMARY
,并且所有成员都已正确连接。
通过以上步骤,你就可以在Debian上成功配置MongoDB的副本集认证。