在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权 和 创建用户/密码 两步。下面以 MongoDB 6.x / 7.x(apt 安装) 为例说明。
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 部分,改为:
security:
authorization: enabled
(注意 YAML 缩进)
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: enabledmongosh 删除/重建用户如果远程连接:
sudo ufw allow 27017
并修改 bindIp:
net:
bindIp: 0.0.0.0
如果你用的是 MongoDB 4.x 老版本 或 Docker 版本,可以告诉我,我给你对应方案。