Dockerfile.prod 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Stage 1: Dependencies
  2. FROM node:18-alpine AS deps
  3. WORKDIR /app
  4. # 安装 pnpm
  5. RUN npm install -g pnpm
  6. # 安装 bash 和其他必要的工具
  7. RUN apk add --no-cache libc6-compat bash
  8. # 复制 package.json 和 pnpm-lock.yaml(如果有的话)
  9. COPY package.json pnpm-lock.yaml* ./
  10. # 安装依赖
  11. RUN pnpm install --frozen-lockfile
  12. # Stage 2: Builder
  13. FROM node:18-alpine AS builder
  14. WORKDIR /app
  15. # 安装 pnpm 和 bash
  16. RUN npm install -g pnpm
  17. RUN apk add --no-cache bash
  18. # 复制所有文件
  19. COPY . .
  20. # 复制 node_modules
  21. COPY --from=deps /app/node_modules ./node_modules
  22. # 构建应用
  23. RUN pnpm build
  24. # Stage 3: Runner
  25. FROM node:18-alpine AS runner
  26. WORKDIR /app
  27. ENV NODE_ENV production
  28. # 安装 bash
  29. RUN apk add --no-cache bash
  30. # 创建非 root 用户
  31. # RUN addgroup --system --gid 1001 nodejs
  32. # RUN adduser --system --uid 1001 nextjs
  33. # 创建非 root 用户和组
  34. RUN addgroup -S -g 1001 nodejs && adduser -S -u 1001 -G nodejs nextjs
  35. # 复制必要文件
  36. COPY --from=builder /app/public ./public
  37. COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
  38. COPY --from=builder /app/node_modules ./node_modules
  39. COPY --from=builder /app/package.json ./package.json
  40. # 设置权限
  41. RUN mkdir -p /app/public/uploads
  42. RUN chown -R nextjs:nodejs /app/public
  43. RUN chown -R nextjs:nodejs /app/public/uploads
  44. # RUN chmod 2775 /app/public/uploads
  45. # RUN usermod -a -G nodejs nextjs
  46. # 临时提升权限以允许写入上传目录
  47. USER root
  48. RUN chmod 777 /app/public/uploads
  49. # 设置 umask
  50. # RUN echo "umask 0002" >> /home/nextjs/.bashrc
  51. # 设置为非 root 用户
  52. USER nextjs
  53. # 暴露端口
  54. EXPOSE 3000
  55. ENV PORT 3000
  56. # 使用 bash 启动应用
  57. CMD ["/bin/bash", "-c", "node_modules/.bin/next start"]