# 🚀 优化版 Dockerfile for Next.js with pnpm (目标: <200MB) # 第一阶段:安装依赖 FROM node:22-alpine AS deps WORKDIR /app # 查看 https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine 以了解为什么可能需要 libc6-compat RUN apk add --no-cache libc6-compat COPY package.json pnpm-lock.yaml ./ RUN npm install -g pnpm && pnpm i --frozen-lockfile # 第二阶段:构建应用 FROM node:22-alpine AS builder WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . # 在构建期间禁用遥测 ENV NEXT_TELEMETRY_DISABLED=1 RUN npm install -g pnpm && pnpm run build # 第三阶段:生产镜像,复制所有文件并运行 next FROM node:22-alpine AS runner WORKDIR /app ENV NODE_ENV=production # 在运行时禁用遥测 ENV NEXT_TELEMETRY_DISABLED=1 RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nextjs # 复制 public 文件夹 COPY --from=builder /app/public ./public # 自动利用输出追踪来减小镜像大小 # https://nextjs.org/docs/advanced-features/output-file-tracing COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static USER nextjs EXPOSE 3000 ENV PORT=3000 # 设置主机名为 0.0.0.0 以便外部访问 ENV HOSTNAME="0.0.0.0" CMD ["node", "server.js"]PORT=3000 \ HOSTNAME="0.0.0.0" \ NODE_ENV=production # 启动应用 (standalone模式直接运行server.js) CMD ["node", "server.js"]