在 Debian 上给 MongoDB 设置密码,通常是启用 鉴权(Authentication) 并创建用户。下面按 最常见、可操作 的方式一步一步来(适用于 MongoDB 4.x / 5.x / 6.x)。
sudo apt update
sudo apt install -y mongodb-org
启动服务:
sudo systemctl start mongod
sudo systemctl enable mongod
检查状态:
sudo systemctl status mongod
重要:先不要开启认证,否则可能进不去。
进入 MongoDB Shell:
mongosh
# 或老版本
# mongo
切换到 admin 数据库,创建管理员:
use admin
db.createUser({
user: "admin",
pwd: "AdminStrongPassword",
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
输入密码后成功进入即表示密码生效 ✅
例如给 mydb 数据库创建读写用户:
mongosh -u admin -p --authenticationDatabase admin
use mydb
db.createUser({
user: "myuser",
pwd: "MyUserPassword",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
连接示例:
mongosh -u myuser -p --authenticationDatabase mydb
或在 URI 中:
mongodb://myuser:MyUserPassword@localhost:27017/mydb
sudo systemctl stop mongod
mongod --dbpath /var/lib/mongodb --noauth
在 /etc/mongod.conf 中:
net:
bindIp: 0.0.0.0
⚠️ 一定要开启密码认证,否则非常危险
| 角色 | 说明 |
|---|---|
| root | 超级管理员 |
| readWrite | 读写 |
| read | 只读 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
如果你愿意,可以告诉我:
我可以给你 更精确 的安全配置方案。