在 CentOS 上给 MongoDB 设置密码,通常分为 启用鉴权 → 创建管理员用户 → 用密码登录 几个步骤。下面以 MongoDB 4.x / 5.x / 6.x 为例说明(YUM 安装方式)。
systemctl status mongod
如果没启动:
systemctl start mongod
mongo
(MongoDB 6+ 可能是 mongosh)
use admin
db.createUser({
user: "root",
pwd: "你的密码",
roles: [{ role: "root", db: "admin" }]
})
vi /etc/mongod.conf
找到或添加:
security:
authorization: enabled
注意 YAML 格式,缩进必须是空格
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
authorization: enableddb.changeUserPassword("root", "新密码")
在 /etc/mongod.conf 中:
net:
bindIp: 0.0.0.0
并开放防火墙:
firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload
如果你用的是 Docker / 特定版本 / 云服务器,可以告诉我,我可以给你对应方案。