在CentOS上配置MongoDB的认证,可以按照以下步骤进行:
首先,确保你已经安装了MongoDB。如果还没有安装,可以使用以下命令进行安装:
sudo yum install -y mongodb-org
安装完成后,启动MongoDB服务:
sudo systemctl start mongod
并设置MongoDB服务开机自启动:
sudo systemctl enable mongod
编辑MongoDB的配置文件 /etc/mongod.conf,找到 security 部分并启用认证:
security:
authorization: enabled
重启MongoDB服务以应用配置更改:
sudo systemctl restart mongod
然后,使用 mongo shell 连接到MongoDB,并创建一个管理员用户:
mongo
在 mongo shell 中执行以下命令来创建管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
退出 mongo shell 并使用管理员用户重新连接:
mongo -u admin -p your_password --authenticationDatabase admin
然后,创建一个新的数据库用户并分配角色。例如,创建一个名为 mydbuser 的用户,并为其分配对 mydatabase 数据库的读写权限:
use mydatabase
db.createUser({
user: "mydbuser",
pwd: "mydbpassword",
roles: [{ role: "readWrite", db: "mydatabase" }]
})
如果你希望MongoDB监听所有IP地址,可以在 /etc/mongod.conf 文件中修改 bindIp 配置:
net:
port: 27017
bindIp: 0.0.0.0
然后重启MongoDB服务:
sudo systemctl restart mongod
如果你启用了防火墙,确保开放MongoDB的默认端口27017:
sudo firewall-cmd --permanent --zone=public --add-port=27017/tcp
sudo firewall-cmd --reload
最后,使用新创建的用户连接到MongoDB并测试:
mongo -u mydbuser -p mydbpassword --authenticationDatabase mydatabase
如果一切配置正确,你应该能够成功连接到MongoDB并执行数据库操作。
通过以上步骤,你就可以在CentOS上成功配置MongoDB的认证。