在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权 和 创建用户 两步。下面以 MongoDB 6.x / 7.x(deb 包安装) 为例说明。
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
⚠ 注意缩进(YAML 对空格敏感)
重启 MongoDB:
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
authorizationuse admin → db.changeUserPassword("admin", "新密码")如果你要从远程连:
sudo ufw allow 27017
并修改 bindIp
如果你告诉我:
我可以给你更精确的配置。