温馨提示×

Node.js应用在Debian上如何进行负载均衡

小樊
35
2025-12-21 02:14:43
栏目: 云计算

在 Debian 上为 Node.js 应用做负载均衡

一、方案总览

  • 进程级并发:使用 Node.js ClusterPM2 启动多个进程,充分利用多核 CPU,适合单机多实例的并发提升。
  • 反向代理/四层七层负载均衡:使用 NginxHAProxy 将请求分发到多个 Node.js 实例,适合横向扩展与高可用。
  • 建议组合:多实例(Cluster/PM2)+ 外部负载均衡(Nginx/HAProxy),既提升单机吞吐又便于横向扩容与故障转移。

二、使用 Nginx 作为反向代理

  • 安装与启用
    • 执行:sudo apt update && sudo apt install nginx
    • 启用开机启动:sudo systemctl enable --now nginx
  • 配置示例(/etc/nginx/sites-available/default 或 /etc/nginx/nginx.conf 的 http 块内)
    • 示例要点:定义 upstream 指向多个实例(如 3000/3001/3002),开启 HTTP/1.1 与 WebSocket 升级,透传关键请求头。
    • 参考配置:
      http {
        upstream node_app {
          server 127.0.0.1:3000;
          server 127.0.0.1:3001;
          server 127.0.0.1:3002;
        }
      
        server {
          listen 80;
          server_name your_domain_or_ip;
      
          location / {
            proxy_pass http://node_app;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            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;
            proxy_cache_bypass $http_upgrade;
          }
        }
      }
      
  • 校验与生效
    • 语法检查:sudo nginx -t
    • 热重载:sudo systemctl reload nginx
  • 说明
    • 默认负载算法为 轮询(round-robin);可按需调整为 least_connip_hash 等(Nginx 支持多种算法)。

三、使用 HAProxy 作为负载均衡器

  • 安装与启用
    • 执行:sudo apt update && sudo apt install haproxy
    • 启用服务:sudo systemctl enable --now haproxy
  • 配置示例(/etc/haproxy/haproxy.cfg)
    • 示例要点:定义 frontend 监听 80,backend 使用 roundrobin 分发到多个实例,并开启 check 健康检查。
    • 参考配置:
      global
        log /dev/log local0
        log /dev/log local1 notice
        daemon
      
      defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 5000ms
        timeout client  50000ms
        timeout server  50000ms
      
      frontend http_front
        bind *:80
        default_backend http_back
      
      backend http_back
        balance roundrobin
        server node1 127.0.0.1:3000 check
        server node2 127.0.0.1:3001 check
        server node3 127.0.0.1:3002 check
      
  • 校验与生效
    • 语法检查:sudo haproxy -c -f /etc/haproxy/haproxy.cfg
    • 热重载:sudo systemctl reload haproxy
  • 说明
    • 可扩展开启管理统计页面(如 stats uri /haproxy?stats)以便观测与排障。

四、进程级并发与进程管理

  • Node.js Cluster 模式(示例)
    • 作用:主进程 fork 多个工作进程共享同一端口,提升单机并发与容错。
    • 示例:
      const cluster = require('cluster');
      const http = require('http');
      const numCPUs = require('os').cpus().length;
      
      if (cluster.isMaster) {
        for (let i = 0; i < numCPUs; i++) cluster.fork();
        cluster.on('exit', (worker) => console.log(`worker ${worker.process.pid} died`));
      } else {
        http.createServer((req, res) => {
          res.writeHead(200);
          res.end('hello world\n');
        }).listen(3000);
      }
      
  • PM2 进程管理
    • 安装:sudo npm install pm2 -g
    • 启动:pm2 start app.js -i max(按 CPU 核数启动多个实例)
    • 优势:进程守护、日志聚合、零停机重启、易与集群模式配合。

五、验证与运维要点

  • 基础验证
    • 访问负载均衡器地址(如 http://服务器IP/),确认请求被分发到不同实例;配合日志或返回体标记核对分布。
  • 防火墙与安全组
    • 放行 80/443(HTTP/HTTPS);如启用 UFWsudo ufw allow 80,443/tcp;云上安全组同样需要放通。
  • 健康检查与高可用
    • HAProxy/Nginx 均支持后端健康检查(示例已启用 check);生产建议部署 多个负载均衡器 并配合 主备浮动 IP 提升可用性。
  • 监控与日志
    • 建议开启 访问/错误日志、启用 HAProxy 统计页面,并接入 Prometheus + Grafana 等监控体系,持续观测吞吐、延迟与错误率。

0