关于 nextjs-deployment
面向 Next.js 开发者的部署技能,提供生产环境部署模式与代码示例。涵盖 Docker 容器化、GitHub Actions CI/CD、环境配置、健康检查和 OpenTelemetry 监控。
主要功能
- 01配置 standalone 输出
- 02构建多阶段 Docker 镜像
- 03设置 GitHub Actions CI/CD
- 04管理环境变量与运行时配置
- 05配置健康检查和 OpenTelemetry
适用场景
- 01将 Next.js 应用容器化部署
- 02自动化构建和部署流程
- 03为不同环境配置运行时变量
- 04监控生产服务并检查健康状态
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ giuseppe-trisciuoglio/ developer-kit --skill nextjs-deployment安装后在 Claude Code 中输入/nextjs-deployment确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/deployment-platforms.mddocker-patterns.mdgithub-actions.mdmonitoring.md详细介绍
Next.js 部署
使用 Docker、CI/CD 流水线和全面的监控,将 Next.js 应用部署到生产环境。
概述
此技能提供了将 Next.js 应用部署到生产环境的模式和代码示例。内容涵盖使用 Docker 容器化、通过 GitHub Actions 自动执行 CI/CD、环境配置、运行状况检查和生产环境监控。对于容器部署,请使用 standalone 输出模式;使用多阶段 Docker 构建来优化镜像,并通过 OpenTelemetry 实现可观测性。
适用场景
在用户请求涉及以下内容时启用:
- “部署 Next.js”、“Docker 化 Next.js”、“容器化”
- “GitHub Actions”、“CI/CD 流水线”、“自动化部署”
- “环境变量”、“运行时配置”、“NEXT_PUBLIC”
- “预览部署”、“预发布环境”
- “监控”、“OpenTelemetry”、“追踪”、“日志记录”
- “运行状况检查”、“就绪状态”、“存活状态”
- “生产构建”、“standalone 输出”
- “Server Actions 加密密钥”、“NEXT_SERVER_ACTIONS_ENCRYPTION_KEY”
快速参考
输出模式
| 模式 | 使用场景 | 命令 |
|---|---|---|
standalone | Docker/容器部署 | output: 'standalone' |
export | 静态站点(无服务端) | output: 'export' |
| (默认) | Node.js 服务端部署 | next start |
环境变量类型
| 前缀 | 可用范围 | 使用场景 |
|---|---|---|
NEXT_PUBLIC_ | 构建时 + 浏览器 | 公共 API 密钥、功能标志 |
| (无前缀) | 仅服务端 | 数据库 URL、机密信息 |
| 运行时 | 仅服务端 | 不同环境使用不同值 |
关键文件
| 文件 | 用途 |
|---|---|
Dockerfile | 多阶段容器构建 |
.github/workflows/deploy.yml | CI/CD 流水线 |
next.config.ts | 构建配置 |
instrumentation.ts | OpenTelemetry 设置 |
src/app/api/health/route.ts | 运行状况检查端点 |
说明
1. 配置 Standalone 输出
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
output: 'standalone',
poweredByHeader: false,
generateBuildId: async () => process.env.GIT_HASH || 'build',
}
export default nextConfig
2. 创建 Dockerfile
有关完整的多阶段构建、多架构支持和优化,请参阅 references/docker-patterns.md。
# syntax=docker/dockerfile:1
FROM node:20-alpine AS base
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1 NODE_ENV=production
ARG GIT_HASH NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
ENV GIT_HASH=${GIT_HASH} NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=${NEXT_SERVER_ACTIONS_ENCRYPTION_KEY}
RUN npm run build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME="0.0.0.0"
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
USER nextjs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/api/health', (r) => r.statusCode === 200 ? process.exit(0) : process.exit(1))"
CMD ["node", "server.js"]
3. 设置 GitHub Actions
有关包含测试、安全扫描和部署策略的完整工作流,请参阅 references/github-actions.md。
# .github/workflows/deploy.yml
name: Build and Deploy
on:
push:
branches: [main, develop]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- id: generate-key
run: echo "key=$(openssl rand -base64 32)" >> $GITHUB_OUTPUT
- uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
GIT_HASH=${{ github.sha }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=${{ steps.generate-key.outputs.key }}
4. 配置环境变量
// src/lib/env.ts
export function getEnv() {
return {
databaseUrl: process.env.DATABASE_URL!,
apiKey: process.env.API_KEY!,
publicApiUrl: process.env.NEXT_PUBLIC_API_URL!,
}
}
export function validateEnv() {
const required = ['DATABASE_URL', 'API_KEY', 'NEXT_PUBLIC_API_URL']
const missing = required.filter((key) => !process.env[key])
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`)
}
}
5. 实现运行状况检查
// src/app/api/health/route.ts
import { NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export async function GET() {
const checks = {
status: 'healthy',
timestamp: new Date().toISOString(),
version: process.env.npm_package_version || 'unknown',
uptime: process.uptime(),
}
return NextResponse.json(checks)
}
6. 设置监控
有关 OpenTelemetry 配置、日志记录、告警和仪表板,请参阅 references/monitoring.md。
// instrumentation.ts
import { registerOTel } from '@vercel/otel'
export function register() {
registerOTel({
serviceName: process.env.OTEL_SERVICE_NAME || 'next-app',
})
}
7. 处理 Server Actions 加密
重要:为多服务端部署生成并设置一致的加密密钥:
# Generate key
openssl rand -base64 32
# Set in GitHub Actions Secrets as NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
如果没有此密钥,多服务端部署中的 Server Actions 会因“Failed to find Server Action”错误而失败。
最佳实践
- Docker:使用多阶段构建,启用 standalone 输出,设置非 root 用户,并包含运行状况检查
- 安全:切勿提交
.env.local;仅将NEXT_PUBLIC_用于公开值;设置NEXT_SERVER_ACTIONS_ENCRYPTION_KEY - 性能:使用
output: 'standalone',为静态资源启用 CDN,并使用next/image - 环境:在所有环境中使用相同的 Docker 镜像,通过环境变量注入运行时配置
示例
// next.config.ts
const nextConfig = {
output: 'standalone',
poweredByHeader: false,
compress: true,
generateBuildId: async () => process.env.GIT_HASH || 'build',
}
export default nextConfig
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgresql://db:5432/myapp
- NEXT_PUBLIC_API_URL=http://localhost:3000/api
限制和警告
限制
- Standalone 输出要求 Node.js 18+
- 所有实例的 Server Actions 加密密钥必须一致
- 运行时环境变量仅适用于
output: 'standalone' - OpenTelemetry 要求在项目根目录中包含 instrumentation.ts
警告
- 切勿使用
NEXT_PUBLIC_前缀存放敏感值 - 多服务端部署时,务必设置
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY - 如果没有运行状况检查,编排器可能会将流量发送到运行状况不佳的实例
- 运行时环境变量不适用于静态导出(
output: 'export')
参考资料
- references/docker-patterns.md - 高级 Docker 配置、多架构构建、优化
- references/github-actions.md - 完整的 CI/CD 工作流、测试、安全扫描
- references/monitoring.md - OpenTelemetry、日志记录、告警、仪表板
- references/deployment-platforms.md - 特定平台指南(Vercel、AWS、GCP、Azure)
评论
支持 Markdown