next.js项目部署流程
两种部署方式
一、静态部署
如果只需要静态页面展示,可以使用
1. 修改 next.config.js
output: 'export',
// 不加这两个,样式不生效basePath: '/xxx', // 在服务器放out内容的文件夹名assetPrefix: '/xxx',2. 构建并导出
npm run build
npm run export
导出后生成out文件夹
把out/里的文件放到服务器的个人指定的路径下
3.nginx配置
location /a {alias xxx/xxx/a; // 路径index index.html index.htm;error_log /var/log/testqianduan_error.log;try_files $uri $uri/ /a/index.html;
}二、SSR部署
如果需要服务端渲染、API接口、动态数据等,就使用SSR。
1. 要把 完整项目 上传到服务器上
2. 在服务器中安装所需要的工具
需要安装npm和PM2
PM2是用来守护后台进程的
# 用nvm安装 Node.js
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# 让配置生效
source ~/.bashrc
# 验证nvm安装成功
nvm -v
# 安装node.js20
nvm install 20
nvm use 20
# 安装pm2
npm install -g pm2
pm2 -v
2. 部署操作
# 安装依赖、构建
cd 你的项目目录
npm install
npm run build
# 利用PM2管理后台守护进程
pm2 start ecosystem.config.js
pm2 save
# ecosystem.config.js文件
module.exports = {apps: [{name: "shooting-sports-system",cwd: "服务器上的项目路径", script: "node_modules/next/dist/bin/next",args: "start", // 默认监听3000端口//args: "start -p 3001", // 如果想监听其他端口env: {NODE_ENV: "production"}}]
}3.nginx配置
server {listen 80;server_name example.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;}
}
配置完记得重启nginx
nginx -s reload总结:
要在服务器上安装node.js,然后在服务器上跑npm install、npm run build,再用PM2托管。
注意:
最好在服务器上执行npm install、npm run build,本地执行的再拷到服务器,可能会出现依赖不兼容的问题
