温馨提示×

ubuntu mongodb如何开启认证

小樊
41
2026-09-20 01:51:59
栏目: 云计算

在 Ubuntu 上给 MongoDB 开启认证(Authentication),一般步骤如下:


一、修改 MongoDB 配置文件

MongoDB 的配置文件通常位于:

/etc/mongod.conf

使用编辑器打开:

sudo vim /etc/mongod.conf

找到或添加 security 配置项,开启认证:

security:
  authorization: enabled

注意 YAML 格式,冒号后面有空格,且使用空格缩进。


二、重启 MongoDB 服务

sudo systemctl restart mongod

查看状态:

sudo systemctl status mongod

三、创建管理员用户(在开启认证前或后均可)

1. 先连接 MongoDB(未开启认证时)

mongo

2. 切换到 admin 数据库

use admin

3. 创建管理员用户

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

四、使用账号登录

方式一:连接时认证

mongo -u admin -p your_password --authenticationDatabase admin

方式二:连接后认证

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

五、为某个数据库创建普通用户(示例)

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

六、常见问题

1. 开启认证后无法登录?

  • 确认已在 admin 库创建用户
  • 登录时指定 --authenticationDatabase admin

2. MongoDB 6+ 使用 mongosh

mongosh -u admin -p your_password --authenticationDatabase admin

3. 修改配置不生效?

  • 检查配置文件路径
  • 确认没有语法错误
  • 查看日志:
sudo tail -n 50 /var/log/mongodb/mongod.log

如果你用的是 Docker / MongoDB 版本不同 / Ubuntu 版本不同,可以告诉我,我可以给你更具体的步骤。

0