Next.js 应用的 Kubernetes 完整部署指南

从 Dockerfile 到 Helm Chart,一步步将 Next.js 应用部署到生产 Kubernetes 集群
## 概述
将 Next.js 应用部署到 Kubernetes 涉及多个步骤:容器化、镜像构建、K8s 资源定义。本文给出一个完整的生产级方案。
## Dockerfile 多阶段构建
```dockerfile
# 构建阶段
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# 运行阶段
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]
```
## Kubernetes Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nextjs-app
spec:
replicas: 3
selector:
matchLabels:
app: nextjs
template:
spec:
containers:
- name: nextjs
image: your-registry/nextjs-app:latest
ports:
- containerPort: 3000
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 30
```
这个配置包括了资源限制和健康检查,是生产环境的最佳实践。
将 Next.js 应用部署到 Kubernetes 涉及多个步骤:容器化、镜像构建、K8s 资源定义。本文给出一个完整的生产级方案。
## Dockerfile 多阶段构建
```dockerfile
# 构建阶段
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# 运行阶段
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]
```
## Kubernetes Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nextjs-app
spec:
replicas: 3
selector:
matchLabels:
app: nextjs
template:
spec:
containers:
- name: nextjs
image: your-registry/nextjs-app:latest
ports:
- containerPort: 3000
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 30
```
这个配置包括了资源限制和健康检查,是生产环境的最佳实践。