在 Debian 上配置 MongoDB 用户(认证用户) 一般分为几个步骤:
1️⃣ 安装 MongoDB
2️⃣ 启用认证
3️⃣ 创建管理员用户
4️⃣ 创建普通数据库用户
5️⃣ 验证登录
下面以 Debian 11 / 12 + MongoDB 6.x / 7.x 为例说明(MongoDB 官方 APT 源方式)。
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
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
Debian 11 把
bookworm换成bullseye
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable mongod
sudo systemctl start mongod
sudo vim /etc/mongod.conf
找到并修改:
security:
authorization: enabled
⚠️ 默认
security:是注释状态,取消注释并加上authorization: enabled
sudo systemctl restart mongod
如果已经启用认证,可先临时关闭 authorization,或:
mongosh
use admin
db.createUser({
user: "admin",
pwd: "AdminStrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
退出:
exit
mongosh -u admin -p --authenticationDatabase admin
例如创建一个 testdb 的读写用户:
use testdb
db.createUser({
user: "testuser",
pwd: "TestUserPassword",
roles: [
{ role: "readWrite", db: "testdb" }
]
})
| 角色 | 说明 |
|---|---|
| root | 超级管理员 |
| readWrite | 读写数据库 |
| read | 只读 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
mongosh -u testuser -p --authenticationDatabase testdb
测试:
use testdb
db.test.insertOne({ name: "hello" })
db.test.find()
Authentication failed
--authenticationDatabase 是否正确db.changeUserPassword("testuser", "NewPassword")
db.dropUser("testuser")
如果你需要:
可以告诉我你的具体场景,我可以给你定制方案。