Skip to content

Next.js 构建和部署 🚀

🎯 概述

Next.js 支持多种部署方式,包括 Vercel、自托管服务器、Docker 等。

📦 构建应用

生产构建

bash
npm run build
npm run start

构建输出

.next/
  ├── cache/          # 构建缓存
  ├── server/         # 服务端代码
  ├── static/         # 静态资源
  └── standalone/     # 独立部署文件

🚀 Vercel 部署

自动部署

  1. 推送代码到 GitHub
  2. 在 Vercel 导入项目
  3. 自动构建和部署

环境变量

bash
# Vercel Dashboard
DATABASE_URL=postgresql://...
JWT_SECRET=your-secret

📝 Docker 部署

Dockerfile

dockerfile
FROM node:18-alpine AS base

# 依赖阶段
FROM base AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

# 构建阶段
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# 运行阶段
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production

COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

EXPOSE 3000
CMD ["node", "server.js"]

docker-compose.yml

yaml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://...
    depends_on:
      - db
  
  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

🎨 自托管部署

PM2

bash
npm install -g pm2
pm2 start npm --name "nextjs-app" -- start
pm2 save
pm2 startup

Nginx 配置

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

📊 性能优化

next.config.js

js
module.exports = {
  output: 'standalone',
  compress: true,
  images: {
    domains: ['example.com'],
    formats: ['image/avif', 'image/webp'],
  },
  experimental: {
    optimizeCss: true,
  },
}

📚 最佳实践

1. 环境变量

bash
# .env.production
DATABASE_URL=production-url
API_URL=https://api.example.com

2. 健康检查

tsx
// app/api/health/route.ts
export async function GET() {
  return Response.json({ status: 'ok' })
}

3. 日志记录

tsx
// lib/logger.ts
export function log(message: string, data?: any) {
  if (process.env.NODE_ENV === 'production') {
    // 发送到日志服务
  } else {
    console.log(message, data)
  }
}

🔗 相关资源


下一步:学习 Next.js Vercel 部署