使用 PM2 和 Nginx 在 VPS 上部署 Next.js 应用

Next.js 是目前最流行的 React 框架之一,专为构建现代 Web 应用而设计。虽然 Vercel 提供了便捷的免费套餐,但许多开发者和团队仍选择将应用部署到自己的 VPS 上,以获得完全的控制权、降低成本并拥有更大的灵活性。本指南将带您从一台全新的 Ubuntu 服务器出发,一步步搭建一个通过 HTTPS 运行的 Next.js 生产环境。

为什么选择 VPS 部署 Next.js 而非 Vercel

Vercel 是一个上手快速的优秀平台,但随着项目规模扩大,以下几个因素会促使团队转向自托管的 VPS 部署:

准备工作

在开始之前,请确认您已备妥以下条件:

通过 NodeSource 安装 Node.js 20 LTS

推荐使用 NodeSource 仓库,它能提供最新版本的 Node.js 并保持持续更新:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - sudo apt-get install -y nodejs node --version # Should output v20.x.x npm --version

如果需要管理多个 Node.js 版本,也可以使用 NVM(Node 版本管理器):

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.bashrc nvm install 20 nvm use 20 nvm alias default 20

克隆项目并构建

通过 SSH 登录您的 VPS,从 Git 仓库拉取代码:

cd /var/www git clone https://github.com/youruser/your-nextjs-app.git cd your-nextjs-app # Install dependencies npm install --production=false # Create production environment file cp .env.example .env.local nano .env.local # Update with real values # Build for production npm run build

构建成功后,.next/ 目录中将包含静态资源及服务端包,随时可以提供服务。

安装并配置 PM2

PM2 是一款进程管理器,可让您的 Next.js 应用持续运行,即使服务器重启或程序崩溃也能自动恢复:

npm install -g pm2 # Start Next.js with PM2 cd /var/www/your-nextjs-app pm2 start npm --name "nextjs-app" -- start # Check status pm2 status pm2 logs nextjs-app # Configure auto-start on VPS reboot pm2 startup systemd # Run the command PM2 outputs (sudo env PATH=...) pm2 save

Next.js 默认监听 3000 端口。您可以通过环境变量 PORT=8080 指定其他端口。

将 Nginx 配置为反向代理

安装 Nginx 并创建虚拟主机,将来自 80/443 端口的流量转发至运行在 3000 端口的 Next.js 服务:

sudo apt install -y nginx # Create a new virtual host config sudo nano /etc/nginx/sites-available/nextjs-app

粘贴以下配置内容:

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_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; } }
sudo ln -s /etc/nginx/sites-available/nextjs-app /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx

使用 Certbot 和 Let's Encrypt 免费部署 SSL

只需一条命令,即可安装 Certbot 并获取免费的 SSL 证书:

sudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

Certbot 会自动更新 Nginx 配置,添加 HTTPS 监听、将 HTTP 重定向至 HTTPS,并通过 systemd 定时器设置自动续期——全部操作一条命令即可完成。

使用 Git Pull 与 PM2 Reload 实现自动部署

创建一个 Shell 脚本,几秒钟内即可完成应用的重新部署:

#!/bin/bash # /var/www/your-nextjs-app/deploy.sh cd /var/www/your-nextjs-app git pull origin main npm install --production=false npm run build pm2 reload nextjs-app --update-env echo "Deploy complete at $(date)"
chmod +x /var/www/your-nextjs-app/deploy.sh # Run deployment with a single command ./deploy.sh

您还可以将此脚本与 GitHub Actions、GitLab CI 或任意 Webhook 集成,构建全自动的 CD 流水线。

在 PM2 中管理环境变量

对于无需重新构建即可变更的环境变量,可使用 PM2 的 ecosystem 配置文件来管理:

// ecosystem.config.js module.exports = { apps: [{ name: 'nextjs-app', script: 'node_modules/.bin/next', args: 'start', env_production: { NODE_ENV: 'production', PORT: 3000 } }] }

实用技巧:运行 pm2 logs nextjs-app 可实时查看日志流;运行 pm2 monit 则可打开实时仪表盘,查看每个进程的 CPU 用量、内存占用和错误率——对快速排查问题极有帮助。

故障排查参考

遇到问题时,以下命令非常有用:

通过 Nginx 静态资源缓存提升性能

配置 Nginx 直接提供 Next.js 静态资源,可显著减轻 Node.js 进程的负担并加快页面加载速度。Next.js 将所有已编译的静态文件存放在 /_next/static/ 目录下——这些文件经过内容哈希处理,可安全缓存整整一年:

server { listen 443 ssl; server_name yourdomain.com; # Serve Next.js static assets directly from disk location /_next/static/ { alias /var/www/your-nextjs-app/.next/static/; expires 1y; add_header Cache-Control "public, immutable"; } # Cache public images and media files location /images/ { root /var/www/your-nextjs-app/public; expires 30d; add_header Cache-Control "public"; } # Proxy all other requests to Next.js 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; } }

启用 Gzip 压缩以缩减响应体积:

# Add inside the http{} block in /etc/nginx/nginx.conf gzip on; gzip_types text/plain text/css application/json application/javascript text/xml; gzip_min_length 1024; gzip_comp_level 5;

在多核 VPS 上使用 PM2 集群模式横向扩展

拥有 2 个或更多 CPU 核心的 VPS 可以将 Next.js 运行在集群模式下,PM2 会为每个核心创建一个工作进程,并通过轮询(round-robin)负载均衡自动分发请求:

// ecosystem.config.js (updated) module.exports = { apps: [{ name: 'nextjs-app', script: 'node_modules/.bin/next', args: 'start', instances: 'max', // use all available CPU cores exec_mode: 'cluster', // enable cluster mode watch: false, max_memory_restart: '512M', env_production: { NODE_ENV: 'production', PORT: 3000 } }] }
# Start with cluster mode pm2 start ecosystem.config.js --env production pm2 save # Monitor individual workers pm2 list

集群模式注意事项:PM2 集群使用同一端口(3000)并在各工作进程间分发请求。但 Next.js Server Actions 和 WebSocket 连接可能需要配置粘性会话(sticky sessions)——在正式上线前,务必结合 Nginx upstream 配置进行充分测试。

按项目规模选择 VPS 配置

根据 Next.js 应用的流量规模和复杂程度,选择合适的 VPS 规格:

项目规模 内存 CPU PM2 模式 备注
作品集 / 小型博客 1 GB 1 核 fork 适合每日请求量 <1,000 的场景
电商 / 中型 SaaS 2–4 GB 2 核 cluster 可处理每日 1 万–5 万次请求
大型应用 / API 密集型 8 GB+ 4+ 核 cluster max 建议配置独立负载均衡器

监控内存泄漏并配置自动重启策略

Node.js 应用长期运行后可能出现内存泄漏。PM2 的 max_memory_restart 选项可在内存占用超过设定阈值时自动重启进程,无需人工干预即可保持应用稳定运行:

# View real-time memory and CPU usage pm2 monit # Tail the last 200 log lines pm2 logs nextjs-app --lines 200 # View error log only pm2 logs nextjs-app --err # Clear old logs pm2 flush nextjs-app # Set restart threshold in ecosystem.config.js: # max_memory_restart: '400M'

使用以下命令检查 VPS 整体运行状态:

# Available RAM free -h # Disk space in the web root df -h /var/www # CPU load average top -bn1 | head -5

选购适合运行 Next.js 的 VPS

AsiaGB VPS 提供完整 root 权限、SSD 存储及 99% 在线率保障,月费低至 500 泰铢,开箱即支持 Node.js、PM2 和 Nginx。

查看 VPS 套餐

查看泰国VPS主机全部套餐 →