[客户端]
↓
[NGINX负载均衡器]
↓ ↓
[VPS1: PM2集群] ↔ [VPS2: PM2集群]
↓ ↓
[共享数据库/缓存]
# 更新系统
sudo apt update && sudo apt upgrade -y
# 安装基础工具
sudo apt install -y git curl wget build-essential
# 安装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;
}
}
# 安装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
# 安装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"
}
}]
}
# 防火墙配置
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
日志管理:
pm2 logs
性能监控:
pm2 monit
自动化部署:
数据库分离:
对象存储:
CDN集成:
自动扩展:
通过这套架构,您可以构建一个能够处理高流量、具备故障自动恢复能力的Web应用服务器集群,确保业务持续稳定运行。