本指南将介绍如何在VPS上使用NGINX和PM2搭建高性能的Web服务器。这种组合能够提供强大的静态内容服务、反向代理和Node.js应用管理能力。
# 更新系统
sudo apt update && sudo apt upgrade -y # Ubuntu/Debian
sudo yum update -y # CentOS/RHEL
# 安装基本工具
sudo apt install -y git curl wget # Ubuntu/Debian
sudo yum install -y git curl wget # CentOS/RHEL
# 使用NodeSource仓库安装最新LTS版本
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs # Ubuntu/Debian
# 或者对于CentOS/RHEL
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo yum install -y nodejs
sudo npm install -g pm2
pm2 startup
# 按照提示执行生成的命令
pm2 save
sudo apt install -y nginx # Ubuntu/Debian
sudo yum install -y nginx # CentOS/RHEL
# 启动NGINX并设置开机启动
sudo systemctl start nginx
sudo systemctl enable nginx
# 允许HTTP/HTTPS流量
sudo ufw allow 'Nginx Full' # Ubuntu
# 或
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload # CentOS
cd /path/to/your/app
pm2 start app.js --name "my-app" # 或使用npm脚本: pm2 start npm --name "my-app" -- start
pm2 list # 查看运行中的应用
pm2 monit # 监控应用
pm2 logs # 查看日志
pm2 restart my-app # 重启应用
pm2 stop my-app # 停止应用
pm2 delete my-app # 删除应用
sudo nano /etc/nginx/sites-available/my-app
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location / {
proxy_pass http://localhost:3000; # 假设Node.js运行在3000端口
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/my-app /etc/nginx/sites-enabled
sudo nginx -t # 测试配置
sudo systemctl reload nginx
# 安装Certbot
sudo apt install -y certbot python3-certbot-nginx # Ubuntu
sudo yum install -y certbot python3-certbot-nginx # CentOS
# 获取证书
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
# 设置自动续期
sudo certbot renew --dry-run
upstream node_cluster {
server localhost:3000;
server localhost:3001;
server localhost:3002;
}
server {
location / {
proxy_pass http://node_cluster;
# 其他代理设置...
}
}
location /static/ {
alias /path/to/static/files/;
expires 30d;
add_header Cache-Control "public";
}
# 安装NGINX监控工具
sudo apt install -y nginx-module-njs # Ubuntu
# 设置日志轮转
sudo nano /etc/logrotate.d/nginx-custom
pm2 start app.js -i max
pm2 list
sudo nginx -t
htop
或 top
通过结合NGINX、PM2和VPS,您可以构建一个高性能、可靠的Web服务器环境。NGINX处理静态内容和反向代理,PM2管理Node.js应用进程,VPS提供稳定的基础设施。这种组合特别适合需要高并发处理能力的现代Web应用。
记得定期更新系统和软件,监控服务器性能,并根据应用需求调整配置参数。