在 CentOS 上给 MongoDB 开启认证(用户名密码登录),一般步骤如下:
MongoDB 的配置文件通常是:
/etc/mongod.conf
编辑它:
vi /etc/mongod.conf
在文件中添加或确认以下内容:
security:
authorization: enabled
注意:yaml 格式严格,缩进必须是空格,不能是 Tab
示例完整片段:
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1
security:
authorization: enabled
在开启认证前或刚开启后,必须有一个管理员账号
如果你还没开认证:
mongo
use admin
db.createUser({
user: "admin",
pwd: "YourStrongPassword",
roles: [{ role: "root", db: "admin" }]
})
systemctl restart mongod
或(老版本):
service mongod restart
mongo -u admin -p YourStrongPassword --authenticationDatabase admin
mongo
use admin
db.auth("admin","YourStrongPassword")
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [{ role: "readWrite", db: "mydb" }]
})
连接:
mongo -u appuser -p AppPassword --authenticationDatabase mydb
27017 到公网bindIp: 127.0.0.1 或内网 IPauthenticationDatabase 用错tail -n 50 /var/log/mongodb/mongod.log
如果你告诉我:
我可以给你更精确的操作命令。