客户端 → NGINX (负载均衡) → PM2集群 → 应用代码
↘
数据库/缓存/存储
upstream node_app {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
keepalive 64;
}
server {
listen 80;
server_name yourdomain.com;
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_cache_bypass $http_upgrade;
}
}
pm2 start app.js -i max --name "api-cluster"
水平扩展(基于资源)
1. 监控CPU/内存使用率
2. 设置扩展阈值(如CPU >70%持续5分钟)
3. 使用PM2动态增减进程: pm2 scale api-cluster +1
垂直扩展(基于队列) 1. 监控消息队列长度 2. 当积压超过阈值时增加工作进程 3. 使用PM2的fork模式处理队列
NGINX端:
location /health {
proxy_pass http://node_app/health;
proxy_intercept_errors on;
error_page 500 502 503 504 =200 /health-fallback;
}
location = /health-fallback {
return 200 "unhealthy";
}
PM2端:
// 在应用中添加健康检查端点
app.get('/health', (req, res) => {
if(healthy) {
res.status(200).send('OK');
} else {
res.status(503).send('Service Unavailable');
}
});
pm2 start app.js --max-memory-restart 500M
pm2 reload api-cluster
# PM2日志管理
pm2 logs --json --log-date-format "YYYY-MM-DD HH:mm:ss"
# NGINX日志配置
log_format json_combined escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status": "$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"request_time":"$request_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
NGINX:
PM2:
pm2 monit
# 调优示例
worker_processes auto;
worker_rlimit_nofile 100000;
events {
worker_connections 4000;
use epoll;
multi_accept on;
}
http {
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 其他优化参数...
}
// ecosystem.config.js
module.exports = {
apps: [{
name: 'app',
script: 'app.js',
instances: 'max',
exec_mode: 'cluster',
max_memory_restart: '1G',
env: {
NODE_ENV: 'production'
},
error_file: '/var/log/pm2/error.log',
out_file: '/var/log/pm2/out.log',
merge_logs: true,
log_date_format: 'YYYY-MM-DD HH:mm:ss',
min_uptime: '60s',
max_restarts: 10,
listen_timeout: 8000,
kill_timeout: 1600
}]
}
通过结合NGINX和PM2的强大功能,您可以构建一个高度弹性、可扩展且可靠的应用服务基础设施,能够适应各种负载条件并确保业务连续性。