CentOS MongoDB网络配置要点
bindIp是MongoDB网络配置的核心参数,决定服务监听的网络接口。默认情况下,MongoDB仅绑定到本地回环地址(127.0.0.1),仅允许本地访问。
bindIp: 127.0.0.1(默认配置,无需修改);bindIp: 0.0.0.0(适用于测试环境,但生产环境需谨慎,会增加未授权访问风险);bindIp: 127.0.0.1,192.168.1.100(推荐生产环境使用,仅允许本地和指定IP访问,提升安全性)。/etc/mongod.conf)后,需重启MongoDB服务使更改生效:sudo systemctl restart mongod。CentOS默认使用firewalld作为防火墙管理工具,需开放MongoDB的默认端口(27017)以允许外部连接。
firewall-cmd命令添加永久规则:sudo firewall-cmd --permanent --zone=public --add-port=27017/tcp;sudo firewall-cmd --reload使规则生效;sudo firewall-cmd --list-all查看ports部分,确认27017/tcp已添加。sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.100" port protocol="tcp" port="27017" accept',然后重载防火墙。为防止未授权访问,需启用MongoDB的身份验证机制,并限制访问IP。
/etc/mongod.conf的security部分添加authorization: enabled,重启服务后生效;mongo --host 127.0.0.1 --port 27017
use admin
db.createUser({ user: "admin", pwd: "StrongPassword123", roles: ["userAdminAnyDatabase", "readWriteAnyDatabase"] })
bindIp参数仅允许信任的IP地址访问(如bindIp: 192.168.1.100),避免暴露给公网。MongoDB的主要网络配置文件位于/etc/mongod.conf,需修改该文件中的net部分(包含bindIp、port等参数)。修改后需重启服务:sudo systemctl restart mongod。
sudo systemctl start mongod;sudo systemctl enable mongod;sudo systemctl status mongod(确保服务运行正常)。ss -tuln | grep 27017或netstat -tuln | grep 27017,确认MongoDB正在监听配置的IP和端口;mongo --host <服务器IP> --port 27017 -u admin -p StrongPassword123 --authenticationDatabase admin命令连接,验证网络可达性。若系统启用了SELinux,需调整策略以允许MongoDB的网络访问。
sudo setenforce 0(测试环境使用,重启后失效);/etc/selinux/config文件,将SELINUX=enforcing改为SELINUX=permissive,然后重启系统。