温馨提示×

centos mongodb怎么开启认证

小樊
38
2026-10-20 10:04:33
栏目: 云计算

在 CentOS 上给 MongoDB 开启认证(用户名/密码登录),一般步骤如下:


一、修改 MongoDB 配置文件

MongoDB 的配置文件通常位于:

/etc/mongod.conf

编辑配置文件:

vi /etc/mongod.conf

在文件中找到或添加 security 配置:

security:
  authorization: enabled

注意:authorization 前面有两个空格缩进,属于 security 下

保存并退出。


二、重启 MongoDB 服务

systemctl restart mongod

查看状态:

systemctl status mongod

三、创建管理员用户(首次未开启认证时)

如果 还没开启认证,先登录 MongoDB:

mongo

切换到 admin 库并创建管理员:

use admin
db.createUser({
  user: "admin",
  pwd: "yourpassword",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})

退出:

exit

四、使用账号登录 MongoDB

mongo -u admin -p --authenticationDatabase admin

或连接指定库:

mongo -u admin -p yourpassword --authenticationDatabase admin

五、给业务库创建普通用户(示例)

use mydb
db.createUser({
  user: "test",
  pwd: "test123",
  roles: [{ role: "readWrite", db: "mydb" }]
})

登录:

mongo -u test -p test123 --authenticationDatabase mydb

六、防火墙(可选)

如果远程连接:

firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload

常见问题

  1. 修改配置后无法启动
    • 检查 mongod.conf 缩进是否正确(YAML 格式)
  2. 忘记管理员密码
    • 临时注释 authorization: enabled
    • 重启后修改用户密码

如果你用的是 MongoDB 6.x / 7.x(新版本) 或 Docker 安装的 MongoDB,可以告诉我,我给你对应方案。

0 踩