温馨提示×

centos mongodb怎么开认证

小樊
42
2026-10-08 18:43:48
栏目: 云计算

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


一、修改 MongoDB 配置文件

MongoDB 的配置文件通常是:

/etc/mongod.conf

用 vim 编辑:

vim /etc/mongod.conf

在文件中添加或确认以下内容(注意缩进,YAML 格式严格):

security:
  authorization: enabled

如果是老版本(2.6 之前),可能是:

auth = true

二、重启 MongoDB

systemctl restart mongod

查看状态:

systemctl status mongod

三、先创建管理员账号(重要)

在开启认证前或刚开启后,必须有一个管理员账号,否则无法管理。

1. 进入 mongo shell

mongo

2. 切换到 admin 库

use admin

3. 创建管理员用户

db.createUser({
  user: "admin",
  pwd: "YourStrongPassword",
  roles: [ { role: "root", db: "admin" } ]
})

四、使用认证登录

方式一:命令行登录

mongo -u admin -p --authenticationDatabase admin

方式二:进入后认证

use admin
db.auth("admin","YourStrongPassword")

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

use testdb
db.createUser({
  user: "testuser",
  pwd: "testpass",
  roles: [ { role: "readWrite", db: "testdb" } ]
})

六、防火墙(可选)

如果远程连接:

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

七、验证是否生效

未认证时执行:

show dbs

应报错 not authorized


常见问题

  • ❌ 配置文件缩进错误 → mongod 启动失败
  • ❌ 没建 admin 用户就开认证 → 无法登录
  • ✅ 推荐角色:root / readWrite / read

如果你用的是 MongoDB 4.x / 5.x / 6.x 或 Docker 版,可以告诉我,我可以给你对应版本的具体命令。

0 踩