All code helpers
DevOpsDockerfile

Multi-stage Dockerfile for Next.js standalone output

Build a small production image for a Next.js app that runs as a non-root user and contains only the traced server files, not the full node_modules.

#docker#nextjs#containers#node
Dockerfile
# syntax=docker/dockerfile:1
FROM node:22-alpine AS base
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1

# 1. Install dependencies (cached until the lockfile changes)
FROM base AS deps
RUN apk add --no-cache libc6-compat
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

# 2. Build the app
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# 3. Minimal runtime image
FROM base AS runner
ENV NODE_ENV=production \
    PORT=3000 \
    HOSTNAME=0.0.0.0

RUN addgroup -S -g 1001 nodejs && adduser -S -u 1001 -G nodejs 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

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
  CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1

CMD ["node", "server.js"]

Usage

TypeScript
// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
};

export default nextConfig;

How it works & gotchas

  • 01output: "standalone" makes Next.js trace the files the server actually needs into .next/standalone. The image typically drops from over 1 GB to a few hundred MB.
  • 02public and .next/static are not included in the standalone folder. Copy them explicitly, or serve them from a CDN.
  • 03Add a .dockerignore with node_modules, .next and .git, or COPY . . sends them to the builder and busts the cache.
  • 04NEXT_PUBLIC_* variables are inlined at build time. Pass them as build args; changing them at runtime has no effect.
  • 05The health check assumes an /api/health route. Remove it if your orchestrator already runs its own probes.

Need this wired into a real system?

We build and harden production software end to end.

Talk to an engineer