Linux服务器上JS如何进行负载均衡
导读:Linux服务器上 Node.js 负载均衡实战指南 一、常见方案与适用场景 反向代理层:使用 Nginx / HAProxy 在七层分发请求,支持权重、健康检查、会话保持、限流与压缩,适合生产环境稳态运行与统一入口治理。 进程内集群:使...
Linux服务器上 Node.js 负载均衡实战指南
一、常见方案与适用场景
- 反向代理层:使用 Nginx / HAProxy 在七层分发请求,支持权重、健康检查、会话保持、限流与压缩,适合生产环境稳态运行与统一入口治理。
- 进程内集群:使用 Node.js cluster 或 PM2 cluster 充分利用多核 CPU,解决单进程瓶颈,适合单机多实例的水平扩展。
- 容器与编排:使用 Docker Compose / Kubernetes,结合 Service 的 ClusterIP/LoadBalancer 或 Ingress 实现自动扩缩与云厂商负载均衡集成。
- 服务发现与动态路由:结合 Consul 等服务注册与健康检查,实现后端动态上下线与灰度发布。
- 四层高性能转发:在超高性能或特定网络场景,可用 LVS(DR)/NAT 做四层转发,再叠加七层策略。
二、快速上手示例
-
方案A Nginx 反向代理(推荐)
- 安装与启用
sudo apt update & & sudo apt install -y nginx sudo systemctl enable --now nginx- 配置 /etc/nginx/sites-available/default(或 /etc/nginx/nginx.conf 的 http 块内)
upstream node_cluster { server 127.0.0.1:3000 weight=5; server 127.0.0.1:3001 weight=3; server 127.0.0.1:3002 backup; keepalive 32; } server { listen 80; server_name your.domain.com; location / { proxy_pass http://node_cluster; 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; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } }- 校验与生效
sudo nginx -t & & sudo systemctl reload nginx说明:通过 weight 设置权重、backup 定义备用节点,并开启长连接与 WebSocket 升级头。
-
方案B HAProxy 负载均衡
- 安装
sudo apt update & & sudo apt install -y haproxy- 配置 /etc/haproxy/haproxy.cfg
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-in bind *:80 default_backend node_servers backend node_servers balance roundrobin option httpchk GET /health 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 systemctl enable --now haproxy说明:采用 roundrobin 轮询,开启 /health 健康检查,失败自动摘除节点。
-
方案C Node.js 进程内集群(单机多核)
// cluster.js const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${ process.pid} is running`); 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, { 'Content-Type': 'text/plain' } ); res.end(`Hello from worker ${ process.pid} \n`); } ).listen(3000, () => console.log(`Worker ${ process.pid} listening on 3000`)); }运行:node cluster.js
说明:由 Node.js 运行时在多个工作进程间分发连接,适合提升单机吞吐。 -
方案D PM2 集群模式(更易运维)
- 全局安装 PM2
sudo npm i -g pm2- ecosystem.config.js
module.exports = { apps: [{ name: 'node-app', script: 'app.js', instances: 4, // 建议与 CPU 核数一致或略高 exec_mode: 'cluster', // 启用集群模式 env: { NODE_ENV: 'production' } } ] } ;- 启动与热重载
pm2 start ecosystem.config.js pm2 reload node-app pm2 monit说明:PM2 提供进程守护、日志聚合、零停机重启与集群编排。
三、生产级配置要点
- 健康检查与摘除:为 Node 暴露 /health 接口,反向代理或 HAProxy 配置 httpchk,失败自动隔离并恢复。
- 会话保持:有状态服务可用 ip_hash / sticky session / Cookie 插入;无状态优先无会话依赖设计。
- 连接与协议:开启 HTTP/1.1 keepalive、合理设置 proxy_read_timeout / proxy_send_timeout,WebSocket 需设置 Upgrade/Connection 头。
- 静态资源:由 Nginx 直接服务静态文件,减少 Node 压力。
- 缓冲与压缩:启用 gzip/brotli,对上游设置合适的 proxy_buffering。
- 限流与熔断:在 Nginx/HAProxy 或网关层做 rate limiting / circuit breaker,保护后端。
- 日志与观测:集中采集 access/error log 与 metrics,接入 Prometheus/Grafana 与 SLO 告警。
四、容器与编排实践
-
Docker Compose 多实例 + Nginx
version: '3.8' services: nginx: image: nginx:latest ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf depends_on: - node1 - node2 - node3 node1: image: node:18-alpine command: node app.js expose: - "3000" node2: image: node:18-alpine command: node app.js expose: - "3000" node3: image: node:18-alpine command: node app.js expose: - "3000"说明:Compose 管理多容器实例,Nginx 统一入口做负载均衡。
-
Kubernetes Service 与 LoadBalancer
apiVersion: v1 kind: Service metadata: name: node-service spec: selector: app: node-app ports: - protocol: TCP port: 80 targetPort: 3000 type: LoadBalancer externalTrafficPolicy: Local说明:云厂商会为该 Service 分配外部负载均衡器;配合 Deployment 的 replicas 实现弹性伸缩。
五、如何选择
- 追求稳定与功能完备:优先 Nginx/HAProxy 作为入口,后端多实例 + PM2 cluster。
- 极致单机性能与简单部署:使用 Node.js cluster 或 PM2 cluster。
- 弹性伸缩与云原生:采用 Kubernetes Service/Ingress,必要时叠加 Consul 等服务发现。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux服务器上JS如何进行负载均衡
本文地址: https://pptw.com/jishu/786903.html
