参考:

官方dockerfile

https://nextjs.org/docs/deployment#docker-image

  1. # Install dependencies only when needed
  2. FROM node:alpine AS deps
  3. # Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
  4. RUN apk add --no-cache libc6-compat
  5. WORKDIR /app
  6. COPY package.json yarn.lock ./
  7. RUN yarn install --frozen-lockfile
  8. # Rebuild the source code only when needed
  9. FROM node:alpine AS builder
  10. WORKDIR /app
  11. COPY . .
  12. COPY --from=deps /app/node_modules ./node_modules
  13. RUN yarn build && yarn install --production --ignore-scripts --prefer-offline
  14. # Production image, copy all the files and run next
  15. FROM node:alpine AS runner
  16. WORKDIR /app
  17. ENV NODE_ENV production
  18. RUN addgroup -g 1001 -S nodejs
  19. RUN adduser -S nextjs -u 1001
  20. # You only need to copy next.config.js if you are NOT using the default configuration
  21. # COPY --from=builder /app/next.config.js ./
  22. COPY --from=builder /app/public ./public
  23. COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
  24. COPY --from=builder /app/node_modules ./node_modules
  25. COPY --from=builder /app/package.json ./package.json
  26. USER nextjs
  27. EXPOSE 3000
  28. ENV PORT 3000
  29. # Next.js collects completely anonymous telemetry data about general usage.
  30. # Learn more here: https://nextjs.org/telemetry
  31. # Uncomment the following line in case you want to disable telemetry.
  32. # ENV NEXT_TELEMETRY_DISABLED 1
  33. CMD ["node_modules/.bin/next", "start"]

node:alpine—最小化的nodejs运行环境

https://nodejs.org/en/download/
https://hub.docker.com/_/node/
image.png

RUN apk add —no-cache libc6-compat

https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine
image.png

清理缓存 —no—cache

image.png

修改镜像

切换node镜像跳过网络问题

经常卡在libc6-compat安装失败
jeknes构建日志

image.png
我本地构建时没问题的,怀疑是网络问题
image.png
为了跳过安装,所以选择 node:16.13.1-slim作为依赖,跳过安装libc6-compat
因为是分阶段构建,第一阶段deps, node镜像并不会影响到最终生成的镜像大小
image.png

切换yarn安装包到国内淘宝镜像

image.png

next/image安装sharp失败

参考:https://www.jianshu.com/p/02a7d52bf696
https://sharp.pixelplumbing.com/install#chinese-mirror
image.png
sharp又需要下载sharp-libvips,要去github下载,但是网络环境,偶然成功一次
网上看了写文章,可以用npmrc配置国内镜像
参考以下配置
https://github.com/SolidZORO/mkn/blob/master/.npmrc
考虑到用的yarn,所以使用了yarnrc,但是还是失败。最后使用npmrc,解决问题

后续修改

3 部署阶段问题

next12.1版本新特性—减少镜像大小

https://nextjs.org/blog/next-12-1#self-hosted-nextjs-improvements
先升级到next版本到12.1, 配置next.config.js, 修改dockerfile
image.png
image.png
image.png
构建镜像前后对比:924M 减少到 227M,效果明显
image.png

启动失败

image.png
参考:
https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile
image.png
解决
image.png