Next.js Dockerfile Generator: Complete Guide
Why Multi-Stage Builds Matter for Next.js
A naive Dockerfile that copies your entire project and runs npm install produces images exceeding 1GB. Multi-stage builds separate the build environment from the runtime environment. The builder stage installs devDependencies and compiles your Next.js app, while the runner stage copies only the compiled standalone output into a minimal Alpine image — typically under 150MB.
# 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
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]Security: Running Next.js Containers as Non-Root
By default, Docker containers run as root. If an attacker exploits a vulnerability in your Next.js application, they gain root access to the container. Always create a dedicated non-root user (e.g., 'nextjs') and switch to it with the USER directive before the CMD instruction.