获取VPS服务器
SSH登录
ssh root@your_server_ip
更新系统包
sudo apt update && sudo apt upgrade -y
安装基础工具
sudo apt install -y curl wget git unzip build-essential
使用NodeSource安装Node.js(以LTS版本为例)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
验证安装
node -v
npm -v
安装PM2全局
sudo npm install -g pm2
安装NGINX
sudo apt install -y nginx
启动NGINX并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
检查NGINX状态
sudo systemctl status nginx
上传你的Node.js应用代码到服务器(例如使用SCP或Git克隆)
安装应用依赖
cd /path/to/your/app
npm install
使用PM2启动应用
pm2 start app.js --name "my-app" # 根据你的入口文件名调整
设置PM2开机自启
pm2 startup
pm2 save
创建NGINX配置文件
sudo nano /etc/nginx/sites-available/yourdomain.com
添加以下配置(根据实际情况调整):
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;
}
}
启用配置
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled
测试NGINX配置
sudo nginx -t
重启NGINX
sudo systemctl restart nginx
设置防火墙
sudo ufw allow ssh
sudo ufw allow 'Nginx Full'
sudo ufw enable
安装SSL证书(使用Let's Encrypt)
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
设置自动续期
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 # 查看错误日志
应用无法访问:
pm2 logs
/var/log/nginx/error.log
netstat -tulnp | grep node
502 Bad Gateway错误:
权限问题:
通过以上步骤,你应该已经成功在VPS上部署了NGINX和PM2,并运行了你的Node.js应用。