在 Debian 上开启 MongoDB 的认证(Authentication),一般步骤如下(以 MongoDB 官方 deb 包、systemd 管理为例,常见版本 4.x / 5.x / 6.x 通用):
sudo systemctl status mongod
如果没启动:
sudo systemctl start mongod
在开启认证前,先连上 MongoDB 创建用户:
mongo
# 或新版本
mongosh
在 mongo shell 中执行:
use admin
db.createUser({
user: "admin",
pwd: "你的强密码",
roles: [{ role: "root", db: "admin" }]
})
退出:
exit
编辑配置文件(Debian 默认路径):
sudo nano /etc/mongod.conf
找到或添加:
security:
authorization: enabled
示例片段:
storage:
dbPath: /var/lib/mongodb
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
net:
bindIp: 127.0.0.1
security:
authorization: enabled
保存后退出。
sudo systemctl restart mongod
mongo -u admin -p --authenticationDatabase admin
输入密码后成功登录即说明认证已开启。
或在 shell 中:
use admin
db.auth("admin", "你的强密码")
use mydb
db.createUser({
user: "appuser",
pwd: "apppass",
roles: [{ role: "readWrite", db: "mydb" }]
})
连接:
mongo -u appuser -p --authenticationDatabase mydb
✅ 忘记管理员密码
authorization: enabled✅ 远程连接
bindIp 改为 0.0.0.0(不推荐公网)✅ MongoDB 6+
mongosh如果你告诉我:
我可以给你更精确的配置示例。