温馨提示×

Node.js在Debian中的网络配置如何设置

小樊
43
2025-12-20 14:56:28
栏目: 编程语言

Node.js 在 Debian 的网络配置与部署实践

一 系统网络与端口开放

  • 更新系统并安装基础组件:sudo apt update && sudo apt install nodejs npm。若需特定版本,可用 nvm 安装与切换。
  • 开放访问端口与防火墙:例如开放 80/443(配合 Nginx)或应用端口 3000。使用 UFW:sudo ufw allow ‘Nginx Full’ 或 sudo ufw allow 3000/tcp;如使用 firewalld:sudo firewall-cmd --permanent --add-service=http --add-service=https && sudo firewall-cmd --reload。
  • 验证监听与连通:ss -ltnp | grep -E ‘:(80|443|3000)’; curl -I http://127.0.0.1:3000。

二 反向代理与 TLS

  • 安装与启用 Nginx:sudo apt install nginx && sudo systemctl enable --now nginx。
  • 配置反向代理示例(/etc/nginx/sites-available/your_app):
    server {
      listen 80;
      server_name your.domain.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 ln -s /etc/nginx/sites-available/your_app /etc/nginx/sites-enabled/ && sudo nginx -t && sudo systemctl reload nginx。
  • TLS 证书:使用 Certbot 获取 Let’s Encrypt 证书并自动配置 HTTPS(certbot --nginx -d your.domain.com)。
  • 上游 Keepalive(提升长连接复用):在 Nginx 的 upstream 段增加 keepalive(如 keepalive 32),并始终使用 HTTP/1.1 与清除 Connection 头。

三 进程管理与高可用

  • 使用 PM2 守护与自启:npm i -g pm2;pm2 start app.js --name “myapp”;pm2 startup(按提示生成 systemd 服务);pm2 save。
  • 多核利用:pm2 start app.js -i max 启用集群模式,充分利用 CPU 多核

四 内核与 TCP 网络调优

  • 文件描述符限制(提升并发连接能力):
    • 查看:ulimit -n;临时提升:ulimit -n 65535。
    • 永久生效:在 /etc/security/limits.conf 增加
      * soft nofile 65535
      * hard nofile 65535
      
  • TCP 与内核参数(写入 /etc/sysctl.conf 或 /etc/sysctl.d/99-tuning.conf,执行 sysctl -p 生效):
    net.core.somaxconn = 4096
    net.ipv4.tcp_max_syn_backlog = 20480
    net.ipv4.ip_local_port_range = 1024 65000
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_fin_timeout = 15
    net.core.netdev_max_backlog = 4096
    net.core.rmem_max = 16777216
    net.core.wmem_max = 16777216
    net.ipv4.tcp_rmem = 4096 87380 16777216
    net.ipv4.tcp_wmem = 4096 65536 16777216
    net.ipv4.tcp_max_tw_buckets = 400000
    
  • 连接状态观测:ss -s;netstat -tan | awk ‘{print $6}’ | sort | uniq -c。

五 Node.js 应用层网络优化

  • 启用 HTTP/2(需 TLS):使用 http2 模块或让 Nginx 终止 TLS 并启用 HTTP/2,提高多路复用与头部压缩效率。
  • 启用压缩:在 Express 中使用 compression 中间件减少传输体积。
  • 缓存策略:对热点数据使用 Redis/Memcached 或响应缓存(如 apicache),降低后端压力。
  • WebSocket:优先使用二进制帧、合理压缩与分包策略,必要时配置 Nginx 的 WebSocket 反向代理参数(Upgrade/Connection)。

0