在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权(auth) 和 创建用户 两步。下面以 MongoDB 6.x / 7.x(apt 安装) 为例说明。
sudo systemctl status mongod
如果没启动:
sudo systemctl start mongod
mongosh
或旧版本:
mongo
在 admin 数据库中创建超级管理员:
use admin
db.createUser({
user: "admin",
pwd: "你的强密码",
roles: [{ role: "root", db: "admin" }]
})
退出:
exit
编辑配置文件:
sudo nano /etc/mongod.conf
找到并修改为:
security:
authorization: enabled
⚠️ 注意 YAML 格式(缩进是空格,不是 Tab)
重启 MongoDB:
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码后成功登录即说明配置正确。
例如给 mydb 建读写用户:
use mydb
db.createUser({
user: "myuser",
pwd: "mypassword",
roles: [{ role: "readWrite", db: "mydb" }]
})
连接:
mongosh -u myuser -p --authenticationDatabase mydb
authorization如果是远程访问:
sudo ufw allow 27017
并修改 bindIp:
net:
bindIp: 0.0.0.0
如果你用的是 Docker / MongoDB 4.x / 特定 Debian 版本,可以告诉我,我给你对应方案。