Dockerizing Next.js Apps for Seamless Cloud Deployments
Docker containerization ensures that your Next.js application runs consistently across development, staging, and production environments. By packing your application with all its dependencies, you eliminate the classic "it works on my machine" problem.
1. Writing a Multi-Stage Dockerfile
A standard build of a Next.js application yields a large folder size due to development dependencies. Multi-stage Docker builds allow you to compile the project in a build stage and copy only the runtime artifacts into the final production image.Here is a highly optimized, production-ready Dockerfile for Next.js:
# Stage 1: Install dependencies
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci# Stage 2: Build the source code
FROM node:18-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
# Stage 3: Runner
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["node", "server.js"]
2. Output Standalone Mode
To make this optimized Dockerfile work, you must enable standalone outputs in yournext.config.js or next.config.mjs:const nextConfig = {
output: 'standalone',
};This tells Next.js to trace your page dependencies and bundle only the code actually needed to run in production, reducing the final image size from 1GB+ down to less than 150MB!