- 首页 >
- 问答 >
-
云计算 >
- CentOS上MongoDB的网络设置指南
CentOS上MongoDB的网络设置指南
小樊
37
2025-12-23 08:57:54
CentOS 上 MongoDB 网络设置指南
一 基础网络参数配置
- 配置文件位置:使用包管理器安装时默认在 /etc/mongod.conf。通过命令行可显式指定:mongod --config /etc/mongod.conf。
- 关键网络项:
- net.port:监听端口,默认 27017(mongod/mongos);分片成员为 27018,配置服务器为 27019。
- net.bindIp / net.bindIpAll:控制监听地址;默认仅 localhost。如需监听所有地址可用 bindIpAll: true,或使用 bindIp: 0.0.0.0(两者互斥)。
- net.maxIncomingConnections:最大并发连接数,默认 65536(受系统内核限制)。
- net.unixDomainSocket.enabled:是否启用 Unix 域套接字,默认 true(仅 Unix/Linux)。
- 安全传输:MongoDB 4.2+ 使用 net.tls 配置 TLS/SSL(替代旧的 ssl 选项)。
- 示例(仅内网监听 + 开启认证):
- 编辑 /etc/mongod.conf:
- net:
- port: 27017
- bindIp: 内网IP,127.0.0.1
- security:
- 重启生效:sudo systemctl restart mongod
- 说明:bindIp 可指定多个地址(逗号分隔);如需监听所有 IPv4 地址,使用 bindIpAll: true。
二 防火墙放行端口
- 使用 firewalld(CentOS 7/8 常用):
- 放行端口:sudo firewall-cmd --permanent --add-port=27017/tcp
- 重新加载:sudo firewall-cmd --reload
- 验证规则:sudo firewall-cmd --list-all(应看到 27017/tcp 被允许)
- 如需临时关闭防火墙(不建议生产):sudo systemctl stop firewalld;禁用开机自启:sudo systemctl disable firewalld。
- 集群/分片场景需放行对应端口,例如示例环境使用 20000、21000、22001~22003/tcp。
三 连接与安全加固
- 本地连接测试:mongo --host 127.0.0.1 --port 27017;远程连接:mongo --host <服务器IP> --port 27017。
- 启用认证后连接:
- 先本地创建管理员:use admin → db.createUser({ user: “admin”, pwd: “强密码”, roles: [“root”] })
- 远程登录:mongo -u admin -p 强密码 --authenticationDatabase admin --host <服务器IP> --port 27017
- 安全建议:
- 仅开放必要端口与来源 IP;避免使用 bindIp: 0.0.0.0 暴露到公网。
- 开启 TLS/SSL(net.tls)以加密传输;为管理口与业务口分别配置证书与访问控制。
- 结合 VPC/安全组 做网络层隔离,优先内网访问。
四 集群与分片的网络要点
- 端口规划(示例):
- mongos:20000/tcp
- config server:21000/tcp
- 每个分片:22001~22003/tcp(示例为 3 个分片)
- 各节点需:
- 在 mongod.conf 中设置正确的 net.port 与 net.bindIp(各节点内网 IP)。
- 防火墙放行上述端口(集群内所有节点互通)。
- 使用 security.keyFile 进行内部认证,并启用 authorization。
五 验证与排错清单
- 服务与端口:
- 查看状态:sudo systemctl status mongod(应为 active (running))
- 监听端口:ss -lntp | grep 27017(应看到 mongod 监听指定 IP:27017)
- 防火墙与连通:
- 规则检查:sudo firewall-cmd --list-all
- 远程连通:nc -vz <服务器IP> 27017 或 telnet <服务器IP> 27017
- 日志与返回码:
- 查看日志:tail -f /var/log/mongodb/mongod.log(常见成功提示:Waiting for connections)
- 连通性验证:db.runCommand({ ping: 1 })(应返回 { “ok” : 1 })
- 常见原因:
- 仅绑定 127.0.0.1 导致远程不可达 → 改为 bindIp: 内网IP,127.0.0.1 或 bindIpAll: true。
- 防火墙未放行 27017/tcp → 使用 firewall-cmd 放行并重载。
- 未启用认证或凭据错误 → 创建用户并以 –authenticationDatabase admin 登录。