温馨提示×

ubuntu如何配置mongodb用户

小樊
40
2026-10-01 19:47:26
栏目: 云计算

在 Ubuntu 上配置 MongoDB 用户,通常包含以下几个步骤:安装 MongoDB → 启动服务 → 连接 MongoDB → 创建用户 → 开启认证 → 使用用户登录。

下面以 Ubuntu 20.04 / 22.04 + MongoDB 6.x / 7.x 为例说明。


一、安装 MongoDB(如果还没装)

sudo apt update
sudo apt install -y mongodb-org

启动并设置开机自启:

sudo systemctl start mongod
sudo systemctl enable mongod

查看状态:

sudo systemctl status mongod

二、连接 MongoDB(默认无认证)

mongosh

或老版本:

mongo

三、创建管理员用户(推荐)

在 admin 数据库中创建超级管理员:

use admin

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

✅ root 权限最大,适合管理用户和数据库。


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

比如给 testdb 创建一个读写用户:

use testdb

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

常用角色说明:

  • read:只读
  • readWrite:读写
  • dbAdmin:数据库管理
  • root:超级管理员

五、开启 MongoDB 认证

编辑配置文件:

sudo vim /etc/mongod.conf

找到 security 部分,改为:

security:
  authorization: enabled

如果原本没有,就直接加上。

重启 MongoDB:

sudo systemctl restart mongod

六、使用用户登录 MongoDB

方式一:命令行登录

mongosh -u admin -p --authenticationDatabase admin

方式二:连接后认证

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

方式三:指定数据库用户

mongosh -u testuser -p --authenticationDatabase testdb

七、验证用户是否生效

show users

或:

db.runCommand({ connectionStatus: 1 })

八、常见问题

1. 忘了管理员密码?

  • 临时关闭 authorization
  • 用本地连接删除用户或重置密码
  • 再开启认证

2. 远程连接

在 /etc/mongod.conf 中:

net:
  bindIp: 0.0.0.0

⚠️ 公网一定要加防火墙 + 强密码。


如果你需要 Docker 方式、MongoDB 副本集用户配置 或 Spring / Node 连接示例,可以继续问我。

0 踩