如何配置Linux上Node.js的网络设置
小樊
39
2025-12-20 09:48:23
Linux上Node.js网络设置实操指南
一 系统网络与防火墙先行
- 确认监听端口与进程:使用ss -tulpen | grep 端口或lsof -iTCP:端口 -sTCP:LISTEN查看服务是否在期望端口监听,避免“服务已起但端口未监听”的误判。
- 放行防火墙端口(按系统选择其一):
- firewalld(CentOS/RHEL/Fedora):
- 开放端口:sudo firewall-cmd --zone=public --add-port=3000/tcp --permanent
- 使生效:sudo firewall-cmd --reload
- ufw(Ubuntu/Debian):sudo ufw allow 3000
- 云服务器安全组:在控制台放行对应TCP/UDP端口(如3000)。
- 绑定地址建议:对外服务绑定0.0.0.0(而非127.0.0.1),例如:app.listen(3000, ‘0.0.0.0’)。
- 端口连通性自检:本机curl http://127.0.0.1:3000;局域网其他主机curl http://服务器IP:3000;必要时用nc -vz 服务器IP 3000测试。
以上端口检查与防火墙放行是外部可达的前提,务必优先完成。
二 应用层网络配置要点
- 代理环境变量(最简便):在运行Node前导出
- 设置:export HTTP_PROXY=http://代理地址:端口 与 HTTPS_PROXY=http://代理地址:端口
- 例外:export NO_PROXY=localhost,127.0.0.1,.internal
- 大多数HTTP客户端(含axios、node-fetch、https)会自动读取。
- 代码内指定代理(精细控制):
- HTTP/HTTPS请求:使用http.Agent/https.Agent并在options.agent指定代理;如需认证,设置Proxy-Authorization头。
- 示例(HTTP):
- const http = require(‘http’);
const https = require(‘https’);
const HttpsProxyAgent = require(‘https-proxy-agent’);
const agent = new HttpsProxyAgent(‘http://user:pass@代理:端口’);
http.get(‘http://example.com’, { agent }, res => { /* … */ });
- 自定义证书与CA(内网/自签名):
- 在https.request/https.createServer中传入key/cert/ca文件路径,用于客户端或服务端校验。
- DNS解析控制:
- 使用**dns.lookup(‘域名’, (err, address, family) => { … })**按系统解析器解析;
- 使用dns.resolve系列进行更细粒度控制(如仅A/AAAA)。
- TCP层参数:
- 通过net.Socket设置setTimeout、setKeepAlive等,控制连接超时与保活。
以上做法覆盖“出网代理、证书信任、DNS与TCP参数”等常见需求,可按需组合。
三 反向代理与域名发布
- 使用Nginx承载域名与静态资源(生产推荐):
- 安装与启动:sudo yum install -y nginx && sudo systemctl start nginx && sudo systemctl enable nginx
- 站点配置(/etc/nginx/conf.d/myapp.conf):
- server {
- listen 80; server_name example.com www.example.com;
- location / {
- proxy_pass http://127.0.0.1:3000;
- proxy_http_version 1.1;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- }
- }
- 校验与生效:sudo nginx -t && sudo systemctl reload nginx
- DNS:在域名DNS提供商处添加A记录指向服务器公网IP。
- 纯Node.js实现反向代理(多项目共用80/443时可选):
- 使用http-proxy-middleware(配合Express)或node-http-proxy按Host或路径分发到不同后端端口,支持WebSocket与负载均衡。
Nginx方案成熟、性能与可运维性更好;Node.js自写代理更灵活,适合内网编排或特殊路由场景。
四 快速排障清单
- 服务是否监听:ss/lsof确认进程与端口,且监听地址为0.0.0.0。
- 本机与跨机连通:curl/nc分别测试127.0.0.1与服务器IP。
- 防火墙与安全组:firewalld/ufw规则与云安全组已放行对应端口。
- 代理可达:在Node内用HttpsProxyAgent或环境变量验证出网。
- 证书信任:自签名场景下客户端需正确配置ca,服务端需提供key/cert。
- 路由与头信息:Nginx反代需传递Host/X-Real-IP/X-Forwarded-For/X-Forwarded-Proto,后端据此生成正确URL与协议。
- 资源占用:检查CPU/内存/文件描述符限制(如ulimit -n),必要时调优。
按上述顺序定位,通常可快速发现“监听、连通、代理、证书、路由”五类常见问题。