在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权 和 创建用户 两步。下面是最常见、最稳妥的做法(以 MongoDB 5.x / 6.x / 7.x 为例,使用 apt 安装)。
sudo systemctl status mongod
如果没启动:
sudo systemctl start mongod
mongosh
(老版本可能是 mongo)
use admin
db.createUser({
user: "admin",
pwd: "你的强密码",
roles: [{ role: "root", db: "admin" }]
})
退出:
exit
sudo nano /etc/mongod.conf
找到 security 部分,改成:
security:
authorization: enabled
注意 YAML 格式,空格不能错
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码后成功进入即说明配置正确。
use mydb
db.createUser({
user: "appuser",
pwd: "app密码",
roles: [{ role: "readWrite", db: "mydb" }]
})
连接:
mongosh -u appuser -p --authenticationDatabase mydb
✅ Debian + apt 安装路径默认是 /etc/mongod.conf
✅ 改配置后必须 restart,不是 reload
✅ 云服务器记得防火墙只开放必要端口
✅ 不要用默认 27017 裸奔公网
如果你用的是 Docker / 旧版本 MongoDB / 特定 Debian 版本,可以告诉我,我可以给你对应的配置示例。