C.W.K.
Stream
Lesson 03 of 08 · published

Docker

~22 min · Docker, standalone, multi-stage

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

The standalone output

Set output: 'standalone' in next.config.ts and next build traces only the files needed at runtime, plus a minimal server.js. The result is a self-contained directory you can ship in a tiny container (typically < 100MB).

Multi-stage Dockerfile

Three stages: deps installs node_modules, builder runs next build, runner copies just the standalone output. Each stage starts from a clean image so the final layer carries only what runs.

Don't forget the static assets

Standalone bundles application code; you still copy .next/static and public/ manually into the runner stage.

Code

Enable standalone output·ts
// next.config.ts
import type { NextConfig } from 'next';
const config: NextConfig = {
  output: 'standalone',
};
export default config;
Multi-stage Dockerfile·text
FROM node:20-alpine AS base

FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

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"]
Build and run·bash
docker build -t my-nextjs-app .
docker run -p 3000:3000 \
  -e DATABASE_URL=postgresql://host/db \
  -e AUTH_SECRET=mysecret \
  my-nextjs-app

External links

Exercise

Containerize a Next.js app with the multi-stage Dockerfile above. Compare image sizes with and without output: 'standalone'. Run it locally and verify env vars are picked up.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.