温馨提示×

DebianMongoDB怎么设密码

小樊
33
2026-10-11 07:40:54
栏目: 云计算

在 Debian 上给 MongoDB 设置密码,通常分为 启用鉴权(auth) 和 创建用户 两步。下面以 MongoDB 6.x / 7.x(apt 安装) 为例说明。


一、先确认 MongoDB 已安装并运行

sudo systemctl status mongod

如果没启动:

sudo systemctl start mongod

二、连接 MongoDB(未开启鉴权时)

mongosh

或旧版本:

mongo

三、创建管理员用户(重要)

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

use admin

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

退出:

exit

四、开启 MongoDB 鉴权

编辑配置文件:

sudo nano /etc/mongod.conf

找到并修改为:

security:
  authorization: enabled

⚠️ 注意 YAML 格式(缩进是空格,不是 Tab)

重启 MongoDB:

sudo systemctl restart mongod

五、使用密码登录测试

mongosh -u admin -p --authenticationDatabase admin

输入密码后成功登录即说明配置正确。


六、给某个数据库单独建用户(推荐)

例如给 mydb 建读写用户:

use mydb

db.createUser({
  user: "myuser",
  pwd: "mypassword",
  roles: [{ role: "readWrite", db: "mydb" }]
})

连接:

mongosh -u myuser -p --authenticationDatabase mydb

七、常见问题

1. 忘记管理员密码

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

2. Debian 防火墙

如果是远程访问:

sudo ufw allow 27017

并修改 bindIp:

net:
  bindIp: 0.0.0.0

如果你用的是 Docker / MongoDB 4.x / 特定 Debian 版本,可以告诉我,我给你对应方案。

0 踩