获取VPS服务器
基本服务器设置
# 更新系统包
sudo apt update && sudo apt upgrade -y # Ubuntu/Debian
sudo yum update -y # CentOS/RHEL
# 创建非root用户
sudo adduser deploy
sudo usermod -aG sudo deploy
# 使用NodeSource仓库安装Node.js
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - # 选择所需版本
sudo apt install -y nodejs
# 验证安装
node -v
npm -v
sudo npm install -g pm2
sudo apt install -y nginx # Ubuntu/Debian
sudo yum install -y nginx # CentOS/RHEL
# 启动并启用开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
部署应用代码
# 示例:克隆你的应用代码
git clone https://github.com/yourusername/your-app.git
cd your-app
npm install
使用PM2管理应用
# 启动应用
pm2 start app.js --name "your-app" # 或你的入口文件
# 设置开机自启
pm2 startup
pm2 save
# 常用PM2命令
pm2 list # 查看运行中的应用
pm2 monit # 监控应用
pm2 logs # 查看日志
创建NGINX配置文件
sudo nano /etc/nginx/sites-available/your-domain.com
配置内容示例
server {
listen 80;
server_name your-domain.com www.your-domain.com;
location / {
proxy_pass http://localhost:3000; # 你的Node.js应用端口
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_cache_bypass $http_upgrade;
}
}
启用配置
sudo ln -s /etc/nginx/sites-available/your-domain.com /etc/nginx/sites-enabled/
sudo nginx -t # 测试配置
sudo systemctl reload nginx
设置防火墙
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
安装SSL证书(使用Let's Encrypt)
sudo apt install -y certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install -y certbot python3-certbot-nginx # CentOS/RHEL
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
# 设置自动续期
sudo certbot renew --dry-run
优化PM2日志管理
# 安装PM2日志轮转模块
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30
负载均衡配置
upstream node_servers {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
# 添加更多实例
}
server {
location / {
proxy_pass http://node_servers;
# 其他代理设置...
}
}
静态文件服务优化
location /static/ {
alias /path/to/your/static/files/;
expires 30d;
access_log off;
}
启用Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
安装PM2监控面板
pm2 install pm2-monitor
设置日志轮转
# 安装logrotate
sudo apt install -y logrotate
# 为PM2日志创建配置
sudo nano /etc/logrotate.d/pm2
定期维护脚本
# 示例清理脚本
sudo nano /usr/local/bin/cleanup.sh
PM2应用崩溃
pm2 logs your-app
pm2 monit
NGINX 502 Bad Gateway
sudo tail -f /var/log/nginx/error.log
性能优化
pm2 start app.js -i max
通过以上步骤,你应该已经成功在VPS上使用NGINX和PM2配置好了Node.js应用的生产环境。记得根据你的具体应用需求调整配置参数。