插件窝 干货文章 简明教程: 如何在VPS上利用NGINX和PM2提高网站性能

简明教程: 如何在VPS上利用NGINX和PM2提高网站性能

NGINX sudo bash 配置 874    来源:    2025-04-11

在VPS上利用NGINX和PM2提高网站性能简明教程

准备工作

  1. 确保已购买VPS并拥有root权限
  2. 已安装Linux系统(推荐Ubuntu/CentOS)
  3. 基本命令行操作知识

步骤1: 安装必要软件

更新系统

sudo apt update && sudo apt upgrade -y  # Ubuntu/Debian
# 或
sudo yum update -y  # CentOS

安装Node.js和NPM

curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -  # Ubuntu/Debian
sudo apt install -y nodejs

# 或对于CentOS:
curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
sudo yum install -y nodejs

安装NGINX

sudo apt install nginx -y  # Ubuntu/Debian
# 或
sudo yum install nginx -y  # CentOS

安装PM2

sudo npm install -g pm2

步骤2: 配置Node.js应用

启动应用

cd /path/to/your/app
npm install  # 安装依赖
pm2 start app.js --name "my-app"  # 启动应用

设置PM2开机启动

pm2 startup
pm2 save

步骤3: 配置NGINX作为反向代理

创建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应用运行在3000端口
        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;
    }
}

启用配置

sudo ln -s /etc/nginx/sites-available/your-domain.com /etc/nginx/sites-enabled
sudo nginx -t  # 测试配置
sudo systemctl restart nginx

步骤4: 性能优化

启用Gzip压缩

在NGINX配置中添加:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

启用HTTP/2

sudo nano /etc/nginx/sites-available/your-domain.com

修改监听行:

listen 443 ssl http2;  # 需要先配置SSL证书

PM2集群模式(多核利用)

pm2 delete my-app  # 先删除单实例
pm2 start app.js -i max --name "my-app"  # 根据CPU核心数启动多个实例

步骤5: 监控与维护

PM2监控

pm2 monit  # 实时监控
pm2 list   # 查看应用状态

NGINX日志检查

tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

定期维护

# 更新所有npm包
npm update

# 重启服务
pm2 restart all
sudo systemctl restart nginx

可选步骤: 安全加固

  1. 配置防火墙
  2. 安装SSL证书(Let's Encrypt)
  3. 设置SSH密钥登录
  4. 配置fail2ban防止暴力破解

通过以上步骤,您的网站将获得显著的性能提升,并能更好地处理高并发请求。