在 Ubuntu 上给 MongoDB 开启认证(Authentication),一般步骤如下(以 MongoDB 6.x / 7.x 常见安装方式为例,适用于 apt 安装):
sudo systemctl status mongod
如果没启动:
sudo systemctl start mongod
mongosh
use admin
db.createUser({
user: "admin",
pwd: "你的密码",
roles: [ { role: "root", db: "admin" } ]
})
退出:
exit
编辑配置文件:
sudo nano /etc/mongod.conf
找到或添加以下内容:
security:
authorization: enabled
⚠ 注意:
security: 前面不要有空格authorization: enabled 缩进 2 个空格示例:
security:
authorization: enabled
保存并退出(Ctrl+O,Enter,Ctrl+X)
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
mongosh
use admin
db.auth("admin", "你的密码")
use mydb
db.createUser({
user: "appuser",
pwd: "apppass",
roles: [ { role: "readWrite", db: "mydb" } ]
})
连接:
mongosh -u appuser -p --authenticationDatabase mydb
查看日志:
sudo tail -n 50 /var/log/mongodb/mongod.log
如果远程连接:
sudo ufw allow 27017
在 /etc/mongod.conf:
net:
bindIp: 127.0.0.1
如果你用的是 Docker / MongoDB 4.x / 云服务器,可以告诉我,我可以给你对应版本的具体配置。