在 Linux 上配置 MongoDB 认证(用户名/密码登录),一般步骤如下(以 MongoDB 4.x / 5.x / 6.x 为例,使用 mongod 服务方式):
MongoDB 配置文件通常位于:
/etc/mongod.conf
编辑配置文件:
sudo vi /etc/mongod.conf
在 security 部分启用认证:
security:
authorization: enabled
如果是 YAML 格式,注意缩进(2 个空格)
示例完整片段:
net:
port: 27017
bindIp: 127.0.0.1
security:
authorization: enabled
sudo systemctl restart mongod
查看状态:
sudo systemctl status mongod
如果 还没启用过认证,请先按下面操作:
注释掉:
# authorization: enabled
然后重启:
sudo systemctl restart mongod
mongo
或(新版本)
mongosh
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [{ role: "root", db: "admin" }]
})
security:
authorization: enabled
sudo systemctl restart mongod
mongo -u admin -p --authenticationDatabase admin
或:
mongosh -u admin -p --authenticationDatabase admin
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [{ role: "readWrite", db: "mydb" }]
})
登录方式:
mongo -u appuser -p --authenticationDatabase mydb
mongodb://appuser:AppPassword@localhost:27017/mydb
authorizationuse admin
db.changeUserPassword("admin", "NewPassword")
修改:
bindIp: 0.0.0.0
并配置防火墙 / 安全组
如果你用的是 Docker / CentOS / Ubuntu / MongoDB 7,可以告诉我,我可以给你对应版本的具体配置。