文章
Nextjs 生产部署
一、先明确你的部署形态(很重要)
Next.js 生产部署通常有 3 种模式,你现在属于 第 2 种:
| 模式 | 特点 | 适合 |
|---|---|---|
next export | 纯静态 | 博客 / 文档 |
| Node Server(next start) | SSR / API | 你当前 |
| Docker | 封装部署 | 中大型项目 |
👉 你执行的是 npm run start
👉 说明你是 Node Server 模式(SSR)
后面步骤全部按 SSR 生产部署来讲
二、服务器最小要求(确认一下)
服务器需要:
- Linux(Ubuntu / CentOS 都行)
- Node.js(建议 ≥ 18)
- 能开放端口(或配 Nginx)
1️⃣ 安装 Node(服务器)
node -v
如果没有或版本太低(推荐 18 / 20):
# 使用 nvm(强烈推荐)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
nvm use 18
三、把项目代码传到服务器
常见方式(选一个)
✅ 推荐:Git 拉取
git clone https://github.com/xxx/your-nextjs-app.git
cd your-nextjs-app
或 scp / rsync
scp -r your-project user@server:/data/app
四、服务器上安装依赖 + 构建
进入项目目录
cd your-nextjs-app
1️⃣ 安装依赖(生产环境)
npm install
# 或
npm ci
2️⃣ 构建
npm run build
3️⃣ 测试运行(临时)
npm run start
默认监听:
http://localhost:3000
此时在服务器上:
curl http://localhost:3000
没问题就继续 👍
五、生产环境必须做的两件事(核心)
✅ 1. 用 PM2 托管进程(防崩)
❌ 不要裸跑 npm run start
✅ 用 pm2
安装 pm2
npm install -g pm2
启动 Next.js
pm2 start npm --name "nextjs-app" -- start
查看状态:
pm2 status
pm2 logs nextjs-app
设置开机自启:
pm2 startup
pm2 save
✅ 2. 用 Nginx 做反向代理(对外访问)
非常重要:
- 80 / 443 端口
- HTTPS
- 域名
六、Nginx 标准配置(直接可用)
1️⃣ 安装 Nginx
sudo apt update
sudo apt install nginx
2️⃣ 配置站点
sudo nano /etc/nginx/sites-available/nextjs
内容示例(HTTP):
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://127.0.0.1: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/nextjs /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
现在访问:
http://your-domain.com
七、生产环境一定要做的优化项(别忽略)
1️⃣ 环境变量
# .env.production
NODE_ENV=production
NEXT_PUBLIC_API_BASE=https://api.xxx.com
PM2 启动时:
pm2 start npm --name nextjs-app -- start
(Next.js 会自动读取 .env.production)
2️⃣ 端口不要暴露
- 3000 只给 Nginx 用
- 云厂商安全组只开放:
- 80
- 443
八、HTTPS(上线必做)
使用 Let's Encrypt(免费)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
自动生成 HTTPS + 续期 👍
九、最终部署结构(你上线后的状态)
用户浏览器
↓
HTTPS :443
↓
Nginx
↓
localhost:3000
↓
Next.js (pm2)
十、你现在下一步该做什么(明确结论)
你现在 已经 build + start 成功,下一步是:
1️⃣ 把项目放到服务器
2️⃣ 服务器 npm install && npm run build
3️⃣ 用 pm2 启动
4️⃣ 用 Nginx 对外暴露
5️⃣ 加 HTTPS