在 CentOS 上为 Node.js 做负载均衡的主流做法
方案一 Nginx 反向代理与负载均衡
sudo yum install -y epel-release && sudo yum install -y nginxsudo systemctl start nginx && sudo systemctl enable nginx/etc/nginx/nginx.conf 或 /etc/nginx/conf.d/backend.confhttp {
upstream backend {
server 192.168.1.11:3000;
server 192.168.1.12:3000;
server 192.168.1.13:3000;
# 可选:least_conn; 或 ip_hash;
}
server {
listen 80;
server_name your_domain_or_IP;
location / {
proxy_pass http://backend;
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;
# 如果应用是 WebSocket
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'Upgrade';
}
}
}
sudo nginx -tsudo systemctl reload nginx方案二 HAProxy 负载均衡
sudo yum install -y haproxysudo systemctl start haproxy && sudo systemctl enable haproxy/etc/haproxy/haproxy.cfgglobal
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 192.168.1.11:3000 check
server node2 192.168.1.12:3000 check
server node3 192.168.1.13:3000 check
sudo haproxy -c -f /etc/haproxy/haproxy.cfgsudo systemctl reload haproxy方案三 单机多进程 Node.js 集群与 PM2
sudo npm install -g pm2pm2 start app.js -i 4 --name myapppm2 start app.js -i maxpm2 list、pm2 monit、pm2 logs myapppm2 save && pm2 startup健康检查与会话保持
防火墙与 HTTPS 配置要点
sudo firewall-cmd --permanent --add-service=http && sudo firewall-cmd --permanent --add-service=https && sudo firewall-cmd --reloadsudo yum install -y certbot python3-certbot-nginxsudo certbot --nginx -d your_domain_or_IP