官方dockerfile
https://nextjs.org/docs/deployment#docker-image
# Install dependencies only when needed
FROM node:alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
# Rebuild the source code only when needed
FROM node:alpine AS builder
WORKDIR /app
COPY . .
COPY --from=deps /app/node_modules ./node_modules
RUN yarn build && yarn install --production --ignore-scripts --prefer-offline
# Production image, copy all the files and run next
FROM node:alpine AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
USER nextjs
EXPOSE 3000
ENV PORT 3000
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1
CMD ["node_modules/.bin/next", "start"]
node:alpine—最小化的nodejs运行环境
https://nodejs.org/en/download/
https://hub.docker.com/_/node/
RUN apk add —no-cache libc6-compat
https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine
清理缓存 —no—cache
修改镜像
切换node镜像跳过网络问题
经常卡在libc6-compat安装失败
jeknes构建日志
我本地构建时没问题的,怀疑是网络问题
为了跳过安装,所以选择 node:16.13.1-slim作为依赖,跳过安装libc6-compat
因为是分阶段构建,第一阶段deps, node镜像并不会影响到最终生成的镜像大小
切换yarn安装包到国内淘宝镜像
next/image安装sharp失败
参考:https://www.jianshu.com/p/02a7d52bf696
https://sharp.pixelplumbing.com/install#chinese-mirror
sharp又需要下载sharp-libvips,要去github下载,但是网络环境,偶然成功一次
网上看了写文章,可以用npmrc配置国内镜像
参考以下配置
https://github.com/SolidZORO/mkn/blob/master/.npmrc
考虑到用的yarn,所以使用了yarnrc,但是还是失败。最后使用npmrc,解决问题
后续修改
next12.1版本新特性—减少镜像大小
- Self-Hosting Improvements: ~80% smaller Docker images
https://nextjs.org/blog/next-12-1#self-hosted-nextjs-improvements
先升级到next版本到12.1, 配置next.config.js, 修改dockerfile
构建镜像前后对比:924M 减少到 227M,效果明显
启动失败
参考:
https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile
解决