温馨提示×

Debian MongoDB如何设置密码

小樊
59
2026-08-02 05:09:53
栏目: 云计算

Debian 上给 MongoDB 设置密码,通常是启用 鉴权(Authentication) 并创建用户。下面按 最常见、可操作 的方式一步一步来(适用于 MongoDB 4.x / 5.x / 6.x)。


一、安装 MongoDB(如已安装可跳过)

sudo apt update
sudo apt install -y mongodb-org

启动服务:

sudo systemctl start mongod
sudo systemctl enable mongod

检查状态:

sudo systemctl status mongod

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

重要:先不要开启认证,否则可能进不去。

进入 MongoDB Shell:

mongosh
# 或老版本
# mongo

切换到 admin 数据库,创建管理员:

use admin

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

退出:

exit

三、启用 MongoDB 认证

编辑配置文件:

sudo nano /etc/mongod.conf

找到并修改或添加:

security:
  authorization: enabled

✅ 注意缩进(YAML 格式)

保存后重启 MongoDB:

sudo systemctl restart mongod

四、使用密码登录测试

mongosh -u admin -p --authenticationDatabase admin

输入密码后成功进入即表示密码生效 ✅


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

例如给 mydb 数据库创建读写用户:

mongosh -u admin -p --authenticationDatabase admin
use mydb

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

连接示例:

mongosh -u myuser -p --authenticationDatabase mydb

或在 URI 中:

mongodb://myuser:MyUserPassword@localhost:27017/mydb

六、常见问题

1️⃣ 忘记 admin 密码怎么办?

  1. 停止 MongoDB:
sudo systemctl stop mongod
  1. 无认证启动:
mongod --dbpath /var/lib/mongodb --noauth
  1. 重新创建用户后恢复配置

2️⃣ 远程连接还需要做什么?

/etc/mongod.conf 中:

net:
  bindIp: 0.0.0.0

⚠️ 一定要开启密码认证,否则非常危险


七、推荐角色速查

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

如果你愿意,可以告诉我:

  • ✅ MongoDB 版本
  • ✅ 是否远程访问
  • ✅ 是单机还是副本集

我可以给你 更精确 的安全配置方案。

0