以下是Ubuntu上配置MongoDB网络的关键步骤,涵盖基础设置与安全增强:
修改配置文件
编辑 /etc/mongod.conf
,找到 net
部分,设置 bindIp
:
bindIp: 0.0.0.0
bindIp: 127.0.0.1,192.168.1.100
sudo systemctl restart mongod
配置防火墙
sudo ufw allow 27017
(允许所有IP) 或 sudo ufw allow from <IP> to any port 27017
(限制特定IP)sudo iptables -A INPUT -p tcp -s <IP> --dport 27017 -j ACCEPT
sudo netfilter-persistent save
启用认证
在 mongod.conf
中添加:
security:
authorization: enabled
重启服务后,通过 mongo
shell 创建管理员用户:
use admin
db.createUser({
user: "admin",
pwd: "强密码",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
启用SSL/TLS加密(生产环境必选)
在 mongod.conf
中配置证书路径:
net:
ssl:
mode: requireSSL
sslPEMKeyFile: /etc/ssl/mongodb.pem
重启服务。
从远程机器测试连接:
mongo -h <服务器IP> -u admin -p "密码" --authenticationDatabase admin
0.0.0.0
,应限制为必要IP段。以上步骤参考自。