在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权 和 创建用户/设置密码 两步。下面以 MongoDB 6.x / 7.x(apt 安装) 为例说明,老版本(如 4.x)也基本通用。
sudo systemctl status mongod
如果没有运行:
sudo systemctl start mongod
mongosh
(老版本可能是 mongo)
在 admin 数据库中创建超级管理员:
use admin
db.createUser({
user: "admin",
pwd: "你的强密码",
roles: [{ role: "root", db: "admin" }]
})
例如给 testdb 设置账号:
use testdb
db.createUser({
user: "testuser",
pwd: "testpass",
roles: [{ role: "readWrite", db: "testdb" }]
})
编辑配置文件:
sudo nano /etc/mongod.conf
找到并修改:
security:
authorization: enabled
注意:yaml 格式严格,缩进用空格,不要 Tab
保存后重启:
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
或连接指定库:
mongosh -u testuser -p --authenticationDatabase testdb
authorization: enableddb.changeUserPassword() 修改在 /etc/mongod.conf 中:
net:
bindIp: 0.0.0.0
⚠️ 公网务必配合防火墙 + 账号密码
如果你告诉我:
我可以给你更精确的配置示例。