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.
# 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
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;How it works & gotchas
- 01
output: "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. - 02
publicand.next/staticare not included in the standalone folder. Copy them explicitly, or serve them from a CDN. - 03Add a
.dockerignorewithnode_modules,.nextand.git, orCOPY . .sends them to the builder and busts the cache. - 04
NEXT_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/healthroute. 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.
More code helpers
GitHub Actions CI: lint, test, build and push to GHCR
Run checks on every pull request, and on main build a Docker image and push it to GitHub Container Registry with layer caching. No long-lived registry credentials needed.
Kubernetes Deployment with probes and zero-downtime rollouts
A production-ready baseline for a stateless HTTP service: readiness, liveness and startup probes, resource limits, a non-root security context and rolling updates that never drop capacity.
Stream LLM responses from a Next.js route handler
Send tokens to the browser as the model produces them instead of making users wait for the full completion. Uses a plain ReadableStream, so it works with any client that can read a fetch body.