在 Debian 上为 Node.js 应用做负载均衡
一、方案总览
二、使用 Nginx 作为反向代理
sudo apt update && sudo apt install nginxsudo systemctl enable --now nginxhttp {
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 -tsudo systemctl reload nginx三、使用 HAProxy 作为负载均衡器
sudo apt update && sudo apt install haproxysudo systemctl enable --now haproxyglobal
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.cfgsudo systemctl reload haproxystats uri /haproxy?stats)以便观测与排障。四、进程级并发与进程管理
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);
}
sudo npm install pm2 -gpm2 start app.js -i max(按 CPU 核数启动多个实例)五、验证与运维要点
sudo ufw allow 80,443/tcp;云上安全组同样需要放通。check);生产建议部署 多个负载均衡器 并配合 主备 或 浮动 IP 提升可用性。