Skip to content

第14章:部署与上线

在本章中,我们将学习如何将 Next.js 应用部署到生产环境,包括项目打包、部署方式选择、常见问题排查以及域名配置等内容。

14.1 项目打包

14.1.1 打包命令

在部署之前,我们需要先构建项目,生成生产环境的静态文件:

bash
npm run build

这个命令会执行以下操作:

  1. 编译 React 代码
  2. 优化资源(图片、CSS、JavaScript)
  3. 生成静态 HTML 文件(对于静态生成的页面)
  4. 构建服务端代码

14.1.2 打包产物解析

构建完成后,会在 .next 目录中生成以下文件:

  • .next/static:静态资源文件(CSS、JavaScript、图片等)
  • .next/server:服务端代码
  • .next/prerendered:预渲染的页面
  • .next/BUILD_ID:构建 ID,用于缓存管理

14.1.3 检查打包结果

构建完成后,我们可以使用以下命令启动生产服务器,检查打包结果:

bash
npm run start

这会启动一个生产环境的服务器,让我们可以在部署前测试应用。

14.2 部署方式详解

14.2.1 方式1:云平台部署(Vercel 推荐)

Vercel 是 Next.js 的官方推荐部署平台,与 Next.js 深度集成,提供了最佳的部署体验。

14.2.1.1 部署步骤

  1. 创建 Vercel 账户:访问 Vercel 并创建账户
  2. 连接 GitHub 仓库:在 Vercel 控制台中,点击 "New Project",选择你的 Next.js 项目仓库
  3. 配置部署:Vercel 会自动检测 Next.js 项目,无需额外配置
  4. 部署项目:点击 "Deploy" 按钮,Vercel 会自动构建和部署你的应用
  5. 获取部署 URL:部署完成后,Vercel 会提供一个 URL,你可以通过这个 URL 访问你的应用

14.2.1.2 Vercel 优势

  • 零配置部署:Vercel 会自动检测 Next.js 项目并进行配置
  • 自动 HTTPS:所有 Vercel 部署的应用都自动启用 HTTPS
  • 全球 CDN:Vercel 使用全球 CDN 加速静态资源
  • Serverless 函数:支持 Next.js 的 API 路由和 Serverless 函数
  • 自动分支部署:为每个 Git 分支创建预览环境

14.2.2 方式2:服务器部署(Nginx + PM2)

如果需要部署到自己的服务器,可以使用 Nginx 作为反向代理,PM2 管理 Node.js 进程。

14.2.2.1 部署步骤

  1. 准备服务器:购买或使用现有的服务器,安装 Node.js 18+
  2. 上传代码:使用 Git 或 FTP 将代码上传到服务器
  3. 安装依赖:在服务器上运行 npm install
  4. 构建项目:运行 npm run build
  5. 安装 PM2npm install -g pm2
  6. 启动应用pm2 start npm --name "next-app" -- run start
  7. 配置 Nginx
nginx
# /etc/nginx/sites-available/next-app
server {
  listen 80;
  server_name example.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;
  }
}
  1. 启用 Nginx 配置
bash
ln -s /etc/nginx/sites-available/next-app /etc/nginx/sites-enabled/
systemctl restart nginx

14.2.3 方式3:容器化部署(Docker)

使用 Docker 容器化部署可以提供更好的环境一致性和可移植性。

14.2.3.1 部署步骤

  1. 创建 Dockerfile
dockerfile
# Dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .
RUN npm run build

EXPOSE 3000

CMD ["npm", "run", "start"]
  1. 构建 Docker 镜像
bash
docker build -t next-app .
  1. 运行 Docker 容器
bash
docker run -p 3000:3000 --name next-app-container next-app
  1. 使用 Docker Compose(可选):
yaml
# docker-compose.yml
version: '3'
services:
  next-app:
    build: .
    ports:
      - "3000:3000"
    restart: always

运行:

bash
docker-compose up -d

14.3 部署常见问题排查

14.3.1 端口占用

问题:启动应用时出现端口占用错误。

解决方案

  • 检查端口是否被其他进程占用:lsof -i :3000
  • 终止占用端口的进程:kill <PID>
  • 修改应用端口:在 next.config.js 中配置 serverPort

14.3.2 跨域问题

问题:前端应用无法访问后端 API,出现 CORS 错误。

解决方案

  • 在后端 API 中添加 CORS 头
  • 使用 Next.js 的 API 路由作为代理
  • next.config.js 中配置 rewrites:
javascript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'https://api.example.com/:path*',
      },
    ];
  },
};

module.exports = nextConfig;

14.3.3 静态资源访问失败

问题:部署后静态资源(图片、CSS、JavaScript)无法访问。

解决方案

  • 检查 assetPrefix 配置是否正确
  • 确保静态资源路径使用相对路径
  • 检查 CDN 配置是否正确

14.3.4 缓存问题

问题:部署后页面内容没有更新,仍然显示旧内容。

解决方案

  • 清除浏览器缓存
  • 检查 CDN 缓存配置
  • next.config.js 中配置缓存策略
  • 使用版本化的静态资源文件名

14.4 域名配置与 HTTPS 部署

14.4.1 域名配置

  1. 购买域名:从域名注册商(如 GoDaddy、阿里云、腾讯云等)购买域名
  2. DNS 配置
    • 登录域名管理控制台
    • 添加 A 记录,指向服务器 IP 地址
    • 或添加 CNAME 记录,指向 Vercel 提供的域名

14.4.2 HTTPS 部署

14.4.2.1 Vercel 自动 HTTPS

Vercel 会自动为所有部署的应用提供 HTTPS 证书,无需额外配置。

14.4.2.2 服务器 HTTPS 配置

使用 Let's Encrypt 免费证书:

  1. 安装 Certbot
bash
apt update
apt install certbot python3-certbot-nginx
  1. 获取证书
bash
certbot --nginx -d example.com -d www.example.com
  1. 自动续期
bash
certbot renew --dry-run
  1. 配置 Nginx
nginx
# /etc/nginx/sites-available/next-app
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://$server_name$request_uri;
}

server {
  listen 443 ssl http2;
  server_name example.com www.example.com;

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
  ssl_prefer_server_ciphers off;
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 10m;

  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;
  }
}

14.4.3 域名重定向

配置域名重定向,将 www 域名重定向到非 www 域名,或反之:

nginx
# 非 www 重定向到 www
server {
  listen 80;
  server_name example.com;
  return 301 https://www.example.com$request_uri;
}

# www 重定向到非 www
server {
  listen 80;
  server_name www.example.com;
  return 301 https://example.com$request_uri;
}

14.5 部署最佳实践

  1. 环境变量管理:使用 .env.local 文件管理环境变量,不要将敏感信息提交到版本控制
  2. 构建优化:使用 next/imagenext/font 等优化资源加载
  3. 监控:设置应用监控,及时发现和解决问题
  4. 备份:定期备份应用数据和配置
  5. CI/CD:配置持续集成和持续部署,自动化部署流程
  6. 回滚策略:准备回滚方案,以便在部署失败时快速恢复

14.6 实战部署示例

14.6.1 Vercel 部署示例

  1. 创建 Vercel 项目

    • 访问 Vercel
    • 点击 "New Project"
    • 选择你的 GitHub 仓库
    • 点击 "Deploy"
  2. 配置环境变量

    • 在 Vercel 项目设置中,点击 "Environment Variables"
    • 添加所需的环境变量,如 API_URLDATABASE_URL
  3. 部署完成

    • Vercel 会自动构建和部署你的应用
    • 部署完成后,你会收到一个部署 URL

14.6.2 服务器部署示例

  1. 准备服务器

    • 购买一台云服务器,如阿里云 ECS、腾讯云 CVM 等
    • 安装 Node.js 18+
  2. 部署步骤

    • 克隆代码:git clone https://github.com/your-username/your-next-app.git
    • 安装依赖:npm install
    • 构建项目:npm run build
    • 启动应用:pm2 start npm --name "next-app" -- run start
    • 配置 Nginx:创建 Nginx 配置文件并启动 Nginx
    • 配置 HTTPS:使用 Let's Encrypt 获取 SSL 证书

通过本章的学习,你已经掌握了 Next.js 应用的部署方法和常见问题的解决方案。在实际部署过程中,你应该根据项目的具体需求和服务器环境,选择合适的部署方式,并遵循最佳实践,确保应用的稳定运行。

© 2026 编程马·菜鸟教程 版权所有