温馨提示×

centos mongodb怎么设密码

小樊
34
2026-09-02 20:09:14
栏目: 云计算

在 CentOS 上给 MongoDB 设置密码,通常分为 启用鉴权 → 创建管理员用户 → 用密码登录 几个步骤。下面以 MongoDB 4.x / 5.x / 6.x 为例说明(YUM 安装方式)。


一、确认 MongoDB 已安装并运行

systemctl status mongod

如果没启动:

systemctl start mongod

二、先不开启鉴权,创建管理员用户

1. 进入 MongoDB

mongo

(MongoDB 6+ 可能是 mongosh

2. 切换到 admin 库

use admin

3. 创建管理员用户(最重要)

db.createUser({
  user: "root",
  pwd: "你的密码",
  roles: [{ role: "root", db: "admin" }]
})

三、开启密码鉴权

1. 修改配置文件

vi /etc/mongod.conf

找到或添加:

security:
  authorization: enabled

注意 YAML 格式,缩进必须是空格

2. 重启 MongoDB

systemctl restart mongod

四、使用密码登录

命令行登录

mongo -u root -p --authenticationDatabase admin

或:

mongosh -u root -p --authenticationDatabase admin

五、给某个数据库单独设用户(可选)

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

登录:

mongo -u testuser -p --authenticationDatabase testdb

六、常见问题

1. 忘记管理员密码

  • 注释掉 authorization: enabled
  • 重启 mongod
  • 用 admin 登录后改密码:
db.changeUserPassword("root", "新密码")

2. 远程连接

/etc/mongod.conf 中:

net:
  bindIp: 0.0.0.0

并开放防火墙:

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

如果你用的是 Docker / 特定版本 / 云服务器,可以告诉我,我可以给你对应方案。

0