在 Debian 上给 MongoDB 开启认证(用户名/密码登录),一般按下面步骤来(以 MongoDB 5.x / 6.x / 7.x 为例,使用 systemd)。
sudo systemctl status mongod
如果没启动:
sudo systemctl start mongod
mongosh
(老版本可能是 mongo)
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
退出:
exit
编辑配置文件:
sudo nano /etc/mongod.conf
找到 security 部分,修改为:
security:
authorization: enabled
⚠️ 注意:
authorization 前面有两个空格sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码后登录成功即可。
mongodb://admin:StrongPassword@localhost:27017/admin
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
连接:
mongodb://appuser:AppPassword@localhost:27017/mydb
authorization: enabled--authenticationDatabase adminMongoDB 默认端口:
sudo ufw allow 27017
(如对外网开放需谨慎)
如果你用的是 Docker / 旧版本 mongo / 特定 Debian 版本,可以告诉我,我可以给你对应方案。