配置MongoDB在Debian上的访问控制涉及几个步骤,包括设置管理员用户、启用身份验证和配置网络访问。以下是一个详细的指南:
首先,确保你已经安装了MongoDB。如果没有安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install -y mongodb
确保MongoDB服务正在运行:
sudo systemctl start mongod
sudo systemctl enable mongod
编辑MongoDB的配置文件 /etc/mongod.conf,找到并修改以下部分以启用身份验证:
security:
authorization: enabled
保存配置文件并重启MongoDB服务以应用更改:
sudo systemctl restart mongod
连接到MongoDB shell:
mongo
在MongoDB shell中,创建一个管理员用户。假设你想创建一个用户名为 admin,密码为 password 的管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "password",
roles: ["root"]
})
确保在 /etc/mongod.conf 中启用了访问控制:
security:
authorization: enabled
默认情况下,MongoDB只允许本地连接。如果你想允许远程连接,需要修改 /etc/mongod.conf 中的 bindIp 设置:
net:
port: 27017
bindIp: 0.0.0.0 # 允许所有IP连接,建议只允许特定IP
修改后,重启MongoDB服务:
sudo systemctl restart mongod
使用新创建的管理员用户连接到MongoDB:
mongo -u admin -p password --authenticationDatabase admin
你可以为特定数据库创建用户。例如,为 mydatabase 数据库创建一个用户:
use mydatabase
db.createUser({
user: "myuser",
pwd: "mypassword",
roles: ["readWrite", "dbOwner"]
})
确保新创建的用户具有正确的权限:
use mydatabase
db.auth("myuser", "mypassword")
db.runCommand({ connectionStatus: 1 })
通过以上步骤,你已经成功配置了MongoDB在Debian上的访问控制。确保在生产环境中使用强密码,并根据需要限制网络访问。