🚢

Next.js 도커 이미지 크기 줄이기

다음은 next.js 공식 코드베이스에 공개되어 있는 Dockerfile 이다. dependency 설치, 빌드, 실행 스테이지로 나누고 node:alpine를 베이스 이미지로 사용한 모범적인 모습이다.
 
하지만 조금이라도 컨테이너 이미지 크기를 줄여보려면 다음의 코드 두 줄을 next build 이후에 추가할 수 있다.
RUN yarn install --frozen-lockfile --production RUN rm -rf ./.next/cache
 
간단한 next.js 앱으로 before & after 를 비교해보면 572.15MB vs 250.39.MB 로 두 배 이상의 극적인 이미지 크기 축소를 볼 수 있다.
notion image
 
해당 코드를 추가한 Dockerfile 예제
# Install dependencies only when needed FROM node:alpine AS deps RUN apk add --no-cache libc6-compat python3 build-base 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 RUN yarn install --frozen-lockfile --production RUN rm -rf ./.next/cache # Production image, copy all the files and run next FROM node:alpine AS runner WORKDIR /app ENV NODE_ENV=production ENV SHOULD_PROFILE=true ENV SHOULD_TRACE=true RUN addgroup -g 1001 -S nodejs RUN adduser -S nextjs -u 1001 COPY --from=builder /app/package.json ./package.json COPY --from=builder /app/node_modules ./node_modules COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next COPY --from=builder /app/public ./public COPY --from=builder /app/next.config.js ./next.config.js COPY --from=builder /app/server-preload.js ./server-preload.js USER nextjs EXPOSE 3000 CMD ["yarn", "start"]