在 Debian 上给 MongoDB 开启认证(Authentication),通常按下面步骤来即可(以 MongoDB 6.x / 7.x + deb 包 为例,适用于 Debian 11/12)。
MongoDB 的配置文件一般在:
/etc/mongod.conf
编辑它:
sudo nano /etc/mongod.conf
找到或添加 security 配置项:
security:
authorization: enabled
⚠️ 注意 YAML 格式,缩进必须是两个空格。
如果你希望远程也能访问(先确认安全):
net:
port: 27017
bindIp: 0.0.0.0
如果只是本机使用:
bindIp: 127.0.0.1
sudo systemctl restart mongod
检查状态:
sudo systemctl status mongod
⚠️ 先不要开启认证,否则你进不去。
临时把:
security:
authorization: enabled
改为:
# security:
# authorization: enabled
重启 MongoDB:
sudo systemctl restart mongod
mongosh
(老版本是 mongo)
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword123",
roles: [
{ role: "root", db: "admin" }
]
})
✅ 推荐角色:
root:超级管理员userAdminAnyDatabase:用户管理readWriteAnyDatabase:读写所有库exit
再次编辑配置文件:
sudo nano /etc/mongod.conf
启用认证:
security:
authorization: enabled
重启 MongoDB:
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码即可。
mongosh "mongodb://admin:StrongPassword123@localhost:27017/admin"
use mydb
db.createUser({
user: "appuser",
pwd: "AppPass456",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
✅ 原因:没有先创建管理员用户
✅ 解决:临时关闭认证,创建用户后再开启
检查:
sudo mongod --config /etc/mongod.conf
或查看日志:
sudo journalctl -u mongod -xe
✅ 不要使用 root 角色给业务程序
✅ 使用强密码
✅ 限制 bindIp
✅ 考虑启用 TLS/SSL
✅ 使用防火墙限制端口
如果你愿意,可以告诉我:
我可以给你一份 生产级安全配置示例。