在 CentOS 上设置 MongoDB 权限,通常分为 启用鉴权(auth) 和 创建用户/分配角色 两部分。下面以 MongoDB 4.x / 5.x / 6.x 为例,步骤通用。
systemctl status mongod
如果没启动:
systemctl start mongod
mongo
# 或(新版本)
mongosh
use admin
db.createUser({
user: "root",
pwd: "StrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
vi /etc/mongod.conf
找到或添加:
security:
authorization: enabled
⚠️ 注意缩进(YAML 格式)
systemctl restart mongod
mongo -u root -p StrongPassword --authenticationDatabase admin
testdb 创建读写用户use testdb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [
{ role: "readWrite", db: "testdb" }
]
})
登录方式:
mongo -u appuser -p AppPassword --authenticationDatabase testdb
| 角色 | 说明 |
|---|---|
| root | 超级权限 |
| read | 只读 |
| readWrite | 读写 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
如果远程连接:
firewall-cmd --permanent --add-port=27017/tcp
firewall-cmd --reload
并建议 绑定内网 IP:
net:
bindIp: 127.0.0.1,192.168.1.100
✅ 不使用默认端口
✅ 不暴露公网
✅ 使用复杂密码
✅ 定期备份
如果你告诉我:
我可以给你 更精确的配置示例。