Optimally dockerizing NextJS application and Lessons Learned
Introduction
I was working on containerizing a Next.js application. At first it seems just a straight forward job. I am not well versed in Javascript or NextJS but I knew what needed to be done and I knew what the requirement was i.e Image size should be small
.
I created a file called Dockerfile
in the project main directory and put the following configuration. Using a multi-stage build process to build in the docker image helped to selectively copy artifacts from one stage into another leaving behind all the unnecessary things which are not required in the final image.
After all the needful was done, the Dockerfile looked like this
# Stage 1
FROM node:16-alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install --production
# Stage 2
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN NODE_ENV=production npm run build
# Stage 3
FROM node:16-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
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…