在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权(authentication) 和 创建管理员用户 两步。下面以 MongoDB 6.x / 7.x(官方 APT 安装) 为例说明,适用于大多数 Debian 10/11/12。
# 导入 MongoDB 公钥
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
# 添加源(Debian 12 bookworm 示例)
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/debian bookworm/mongodb-org/7.0 main" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update
sudo apt install -y mongodb-org
启动 MongoDB:
sudo systemctl start mongod
sudo systemctl enable mongod
mongosh
(老版本是 mongo)
use admin
db.createUser({
user: "admin",
pwd: "StrongAdminPassword",
roles: [ { role: "root", db: "admin" } ]
})
✅ root 权限是 MongoDB 中最高权限
退出:
exit
sudo nano /etc/mongod.conf
找到并修改:
security:
authorization: enabled
⚠️ 注意:
authorization 前面有两个空格sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码即可。
mongosh "mongodb://admin:StrongAdminPassword@localhost:27017/?authSource=admin"
例如给 mydb 数据库创建用户:
use mydb
db.createUser({
user: "myuser",
pwd: "MyUserPassword",
roles: [ { role: "readWrite", db: "mydb" } ]
})
登录:
mongosh -u myuser -p --authenticationDatabase mydb
| 角色 | 说明 |
|---|---|
root |
超级管理员 |
readWrite |
读写 |
read |
只读 |
dbAdmin |
数据库管理 |
userAdmin |
用户管理 |
authorizationuse admin
db.changeUserPassword("admin", "NewPassword")
authorizationsudo ufw allow from 你的IP to any port 27017
生产环境 不要 直接暴露 27017 到公网。
如果你愿意,可以告诉我:
我可以给你更精确的配置方案 ✅