Multi-stage dockerfile for Next.js
The backend phase taught you multi-stage Docker builds for a Node service. Next.js follows the exact same pattern with one twist: instead of copying dist, you copy the standalone output plus the static and public folders. The result is a tiny, production-ready image.
# Stage 1: builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: runner
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Next.js standalone output puts everything needed in .next/standalone
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
USER node
EXPOSE 3000
CMD ["node", "server.js"]Builder stage compiles, runner stage runs. Same shape as the backend Dockerfile.
Three COPY lines in the runner stage. First, the standalone bundle which includes the server and its deps. Second, the static assets Next.js produces for optimized images and scripts. Third, the public folder for anything you store there manually. Nothing else gets shipped.
Multi-stage Docker build
The builder has every dev dependency. The runner has only what the server needs to start.
Quiz: Quiz
Loading practice…