以下是在Ubuntu上设置MongoDB权限的步骤:
安装MongoDB:
sudo apt update
sudo apt install -y mongodb
创建专用数据目录并设置权限:
sudo mkdir -p /data/db
sudo chown -R mongodb:mongodb /data/db
sudo chmod -R 700 /data/db
启用身份验证:
编辑配置文件 /etc/mongod.conf
,在 security
部分添加:
authorization: enabled
重启服务:
sudo systemctl restart mongod
创建管理员用户:
连接MongoDB并切换到 admin
数据库:
mongo
use admin
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
创建普通用户并分配权限:
切换到目标数据库(如 myDatabase
),创建用户并指定角色(如 readWrite
):
use myDatabase
db.createUser({
user: "appUser",
pwd: "appPassword",
roles: [{ role: "readWrite", db: "myDatabase" }]
})
远程访问配置(可选):
bindIp
为 0.0.0.0
允许远程连接(需在安全组中开放端口):sudo nano /etc/mongod.conf
net:
bindIp: 0.0.0.0
重启服务:sudo systemctl restart mongod
sudo ufw allow from trusted_ip/32 port 27017
sudo ufw reload
使用认证连接:
通过命令行或工具(如MongoDB Compass)连接时需指定用户名、密码及认证数据库:
mongo -u appUser -p appPassword --authenticationDatabase myDatabase
说明:
read
(只读)、dbAdmin
(数据库管理)、clusterAdmin
(集群管理)等。