温馨提示×

centos mongodb如何设置账号

小樊
35
2026-10-20 10:08:33
栏目: 云计算

在 CentOS 上给 MongoDB 设置账号,一般分为以下几个步骤:启用鉴权 → 创建管理员账号 → 创建业务数据库账号 → 用账号登录。

下面以 MongoDB 4.x / 5.x / 6.x 为例(CentOS 7/8 通用)。


一、确认 MongoDB 已安装并运行

systemctl status mongod

如果没启动:

systemctl start mongod
systemctl enable mongod

二、先不开启鉴权,创建管理员账号

1. 进入 MongoDB

mongo

(MongoDB 6+ 可能是 mongosh)


2. 切换到 admin 库

use admin

3. 创建超级管理员

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

✅ root 权限最高,仅用于管理


三、开启账号密码鉴权

编辑配置文件:

vi /etc/mongod.conf

找到 security 部分,改成:

security:
  authorization: enabled

如果是 CentOS 的旧版本,可能写成:

auth = true

保存后重启:

systemctl restart mongod

四、用管理员账号登录

mongo -u root -p YourStrongPassword --authenticationDatabase admin

五、为某个业务库创建专用账号(推荐)

例如给 testdb 建一个读写账号:

use testdb

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

六、使用业务账号连接

mongo -u testuser -p TestPassword123 --authenticationDatabase testdb

或远程连接:

mongo "mongodb://testuser:TestPassword123@localhost:27017/testdb"

七、常用角色说明

角色 说明
root 超级管理员
read 只读
readWrite 读写
dbAdmin 数据库管理
userAdmin 用户管理

八、常见坑提醒

  1. 一定要指定 --authenticationDatabase
  2. 修改密码:
db.updateUser("testuser", { pwd: "NewPassword" })
  1. 删除用户:
db.dropUser("testuser")

如果你告诉我:

  • MongoDB 版本
  • 是否远程连接
  • 单机还是副本集

我可以给你更精确的配置示例(包括 防火墙 / bindIp / 副本集鉴权)。

0 踩