插件窝 干货文章 教你如何在VPS服务器上部署NGINX和PM2

教你如何在VPS服务器上部署NGINX和PM2

NGINX sudo bash 应用 979    来源:    2025-04-11

在VPS服务器上部署NGINX和PM2的完整指南

准备工作

  1. 获取VPS服务器

    • 选择云服务提供商(AWS, DigitalOcean, Linode, Vultr等)
    • 创建Ubuntu/CentOS实例(推荐Ubuntu 20.04/22.04 LTS)
  2. SSH登录

    ssh root@your_server_ip
    

第一步:系统更新与基础配置

  1. 更新系统包

    sudo apt update && sudo apt upgrade -y
    
  2. 安装基础工具

    sudo apt install -y curl wget git unzip build-essential
    

第二步:安装Node.js和NPM

  1. 使用NodeSource安装Node.js(以LTS版本为例)

    curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
    sudo apt install -y nodejs
    
  2. 验证安装

    node -v
    npm -v
    
  3. 安装PM2全局

    sudo npm install -g pm2
    

第三步:安装和配置NGINX

  1. 安装NGINX

    sudo apt install -y nginx
    
  2. 启动NGINX并设置开机自启

    sudo systemctl start nginx
    sudo systemctl enable nginx
    
  3. 检查NGINX状态

    sudo systemctl status nginx
    

第四步:部署Node.js应用

  1. 上传你的Node.js应用代码到服务器(例如使用SCP或Git克隆)

  2. 安装应用依赖

    cd /path/to/your/app
    npm install
    
  3. 使用PM2启动应用

    pm2 start app.js --name "my-app"  # 根据你的入口文件名调整
    
  4. 设置PM2开机自启

    pm2 startup
    pm2 save
    

第五步:配置NGINX反向代理

  1. 创建NGINX配置文件

    sudo nano /etc/nginx/sites-available/yourdomain.com
    
  2. 添加以下配置(根据实际情况调整):

    server {
       listen 80;
       server_name yourdomain.com www.yourdomain.com;
    
       location / {
           proxy_pass http://localhost: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;
       }
    }
    
  3. 启用配置

    sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled
    
  4. 测试NGINX配置

    sudo nginx -t
    
  5. 重启NGINX

    sudo systemctl restart nginx
    

第六步:安全配置(可选但推荐)

  1. 设置防火墙

    sudo ufw allow ssh
    sudo ufw allow 'Nginx Full'
    sudo ufw enable
    
  2. 安装SSL证书(使用Let's Encrypt)

    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
    
  3. 设置自动续期

    sudo certbot renew --dry-run
    

常用命令参考

  • PM2命令:

    pm2 list              # 查看运行中的应用
    pm2 restart app_name  # 重启应用
    pm2 stop app_name     # 停止应用
    pm2 delete app_name   # 删除应用
    pm2 logs              # 查看日志
    
  • NGINX命令:

    sudo systemctl restart nginx  # 重启NGINX
    sudo nginx -t                 # 测试配置
    sudo tail -f /var/log/nginx/error.log  # 查看错误日志
    

故障排除

  1. 应用无法访问:

    • 检查PM2日志: pm2 logs
    • 检查NGINX错误日志: /var/log/nginx/error.log
    • 确保应用在正确端口运行: netstat -tulnp | grep node
  2. 502 Bad Gateway错误:

    • 确保Node.js应用正在运行
    • 检查NGINX配置中的proxy_pass端口是否正确
  3. 权限问题:

    • 确保NGINX用户(www-data)有权访问相关目录

通过以上步骤,你应该已经成功在VPS上部署了NGINX和PM2,并运行了你的Node.js应用。