插件窝 干货文章 NGINX PM2 VPS: 构建高可靠性的Web应用服务器集群

NGINX PM2 VPS: 构建高可靠性的Web应用服务器集群

配置 PM2 集群 NGINX 939    来源:    2025-04-11

构建高可靠性的Web应用服务器集群:NGINX + PM2 + VPS方案

核心组件概述

1. VPS (虚拟专用服务器)

  • 提供可扩展的计算资源
  • 建议选择至少2台以上VPS实现高可用
  • 推荐配置:2-4核CPU,4-8GB内存,SSD存储

2. NGINX

  • 作为反向代理和负载均衡器
  • 处理静态内容、SSL终端和请求分发
  • 支持HTTP/2和WebSocket

3. PM2

  • Node.js应用进程管理器
  • 提供应用监控、日志管理和自动重启
  • 支持集群模式运行Node应用

架构设计

[客户端] 
   ↓
[NGINX负载均衡器] 
   ↓       ↓
[VPS1: PM2集群] ↔ [VPS2: PM2集群]
   ↓       ↓
[共享数据库/缓存]

实施步骤

1. VPS基础配置

# 更新系统
sudo apt update && sudo apt upgrade -y

# 安装基础工具
sudo apt install -y git curl wget build-essential

2. NGINX安装与配置

# 安装NGINX
sudo apt install -y nginx

# 配置负载均衡 (在/etc/nginx/conf.d/load-balancer.conf)
upstream node_app {
    least_conn;
    server vps1_ip:3000;
    server vps2_ip:3000;
    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;
    }
}

3. Node.js与PM2安装

# 安装Node.js (使用nvm)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm install --lts

# 安装PM2
npm install pm2@latest -g

# 启动PM2集群模式 (假设4核CPU)
pm2 start app.js -i 4 --name "node-app"

# 设置开机启动
pm2 startup
pm2 save

4. 高可用性配置

4.1 NGINX高可用

  • 设置Keepalived实现NGINX主备切换
  • 配置健康检查自动剔除故障节点

4.2 PM2监控

# 安装PM2监控模块
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30

# 设置自动重启策略
pm2 ecosystem
# 在配置文件中添加:
module.exports = {
  apps: [{
    name: "app",
    script: "app.js",
    instances: "max",
    exec_mode: "cluster",
    autorestart: true,
    watch: false,
    max_memory_restart: "1G",
    env: {
      NODE_ENV: "production"
    }
  }]
}

5. 安全加固

# 防火墙配置
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

# 设置SSH密钥登录
sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config
sudo systemctl restart sshd

监控与维护

  1. 日志管理:

    • 使用PM2日志管理: pm2 logs
    • 配置ELK或Grafana+Loki进行集中日志分析
  2. 性能监控:

    • PM2内置监控: pm2 monit
    • 使用Prometheus+Grafana监控系统指标
  3. 自动化部署:

    • 配置GitHub Actions或Jenkins实现CI/CD
    • 使用Ansible进行多服务器配置管理

扩展建议

  1. 数据库分离:

    • 将数据库迁移到专用服务器或使用云数据库服务
  2. 对象存储:

    • 使用S3兼容存储处理静态文件和上传内容
  3. CDN集成:

    • 配置Cloudflare或其他CDN服务缓存静态内容
  4. 自动扩展:

    • 在云平台上配置自动扩展组
    • 基于CPU/内存使用率自动增减实例

通过这套架构,您可以构建一个能够处理高流量、具备故障自动恢复能力的Web应用服务器集群,确保业务持续稳定运行。