温馨提示×

debian mongodb怎么开启认证

小樊
38
2026-10-25 23:05:45
栏目: 云计算

在 Debian 上给 MongoDB 开启认证(用户名/密码登录),一般按下面步骤来(以 MongoDB 5.x / 6.x / 7.x 为例,使用 systemd)。


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

sudo systemctl status mongod

如果没启动:

sudo systemctl start mongod

二、先创建管理员用户(未开启认证时)

1. 进入 MongoDB

mongosh

(老版本可能是 mongo)

2. 切换到 admin 库并创建管理员

use admin

db.createUser({
  user: "admin",
  pwd: "StrongPassword",
  roles: [
    { role: "userAdminAnyDatabase", db: "admin" },
    { role: "readWriteAnyDatabase", db: "admin" }
  ]
})

退出:

exit

三、修改 MongoDB 配置文件开启认证

编辑配置文件:

sudo nano /etc/mongod.conf

找到 security 部分,修改为:

security:
  authorization: enabled

⚠️ 注意:

  • YAML 对缩进敏感
  • authorization 前面有两个空格

四、重启 MongoDB

sudo systemctl restart mongod

五、使用账号登录测试

方式 1:命令行登录

mongosh -u admin -p --authenticationDatabase admin

输入密码后登录成功即可。

方式 2:连接 URI

mongodb://admin:StrongPassword@localhost:27017/admin

六、(可选)为业务库创建专用用户

use mydb

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

连接:

mongodb://appuser:AppPassword@localhost:27017/mydb

七、常见问题

1. 开启认证后连不上

  • 确认 authorization: enabled
  • 确认登录时指定了 --authenticationDatabase admin

2. Debian 防火墙

MongoDB 默认端口:

sudo ufw allow 27017

(如对外网开放需谨慎)


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

0 踩