Explain it simply
Explain it simply
A container image is like packing a cooked meal in a box that can be reheated on any stove. The box should contain the meal and what you need to heat it, not the pots you cooked with or the vegetable peelings.
A multi-stage Docker build works the same way: the early stages install dependencies and build the app, and the final stage copies in only the files needed to run it. Running on your own server instead of a platform such as Vercel gives you more freedom, but HTTPS, restarts and security patches become your job.
Problem → Why → Solution
The problem: a 1 GB image, a root user and vanishing uploads
A developer writing their first Dockerfile copies the whole project, installs, builds and runs next start. The image ends up holding every dev dependency, the source code, the .git folder and, by accident, the .env.local file, and it runs as root.
Users' uploaded images are stored in an uploads folder inside the container, so every new deploy wipes them all. Port 3000 is also exposed straight to the internet, with no HTTPS.
FROM node:22
WORKDIR /app
COPY . . # also copies .env.local, .git and node_modules
RUN npm install && npm run build
EXPOSE 3000
CMD ["npm", "start"] # runs as root, with every dev dependency insideWhy is this image a problem?
Every file in the image adds download size and more packages for security scans to worry about. Anyone who gets the image can read the secrets in .env.local. Running as root means an attacker who finds a flaw in the app gets full privileges inside the container. Containers must be treated as disposable: they can be destroyed and recreated at any time.
Core concept: standalone output and multi-stage builds
Adding output: "standalone" to next.config.ts makes next build produce a folder called .next/standalone. Next.js traces the files your code actually imports and includes only the production parts of node_modules plus a small server called server.js. You can then run node server.js directly, without installing the whole next package to use next start.
The catch is that the standalone folder does not include the public folder or .next/static (CSS and client JavaScript chunks), because some teams serve those from a CDN. If one container serves everything, you must copy those two folders next to the standalone output yourself; otherwise the HTML appears but styles and scripts return 404.
| Stage | Job | In the final image? |
|---|---|---|
| deps | Install dependencies from the lockfile | No |
| builder | Copy the source and run next build | No |
| runner | Copy only standalone, static and public, then run | Only this |
Separate stages also make good use of Docker's layer cache. Because package.json and the lockfile are copied and installed first, a change to source code alone reuses the cached install step, and builds get much faster.
In production, the Next.js self-hosting guide recommends putting the Next.js server behind a reverse proxy such as nginx, Caddy or a cloud load balancer instead of exposing it directly. The proxy handles HTTPS certificates, compression, request size limits, rate limiting and slow clients, leaving the Node process to focus on the app itself.
Self-hosting also moves the operational chores onto your plate. Something must restart the container when it crashes (Docker's restart policy, systemd or an orchestrator such as Kubernetes). Someone must rebuild the image when Node.js or Alpine ships a security fix. And someone must decide where logs go once the container's own output disappears with it.
- deps installs from the lockfile
- builder runs next build
- runner copies only what it needs
- Run as non-root behind a proxy
Treat the container as something you can throw away at any moment. Anything worth keeping lives in a database or object storage.
General pattern: a multi-stage Dockerfile
FROM <base-image> AS deps
COPY <package manifest and lockfile> ./
RUN <install dependencies from the lockfile>
FROM <base-image> AS builder
COPY --from=deps <installed dependencies> ./
COPY <source> .
RUN <build command>
FROM <base-image> AS runner
COPY --from=builder <only the runtime output> ./
CMD ["<start command>"]Each FROM starts a new stage. COPY --from=<stage> picks files out of an earlier stage, and only the last stage becomes the image.
Example: a Dockerfile for Myanmar Notes
This Dockerfile follows the shape of Next.js's official with-docker example and uses pnpm. First, output: "standalone" must be enabled in next.config.ts. Put a .dockerignore file in the project root that excludes node_modules, .next, .git and .env* files from the build context. If the project has no public folder, that COPY line fails, so create an empty one.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;# Requires output: "standalone" in next.config.ts
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable pnpm && pnpm install --frozen-lockfile
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Public values are inlined into browser JS here, at build time
ARG NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
RUN corepack enable pnpm && pnpm build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs && 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 HOSTNAME=0.0.0.0
CMD ["node", "server.js"]Code breakdown
- Install once, cache often
COPY package.json pnpm-lock.yaml ./Only the manifest and lockfile are copied before the source. As long as these two files do not change, Docker reuses the cached install layer. --frozen-lockfile fails on any mismatch, so every build gets the same versions.
- Build-time public values
ARG NEXT_PUBLIC_SITE_URLNEXT_PUBLIC_ values are written into the JavaScript during pnpm build, so they are passed to the builder stage with --build-arg. Passing them with docker run -e cannot change browser code. Never pass secrets as ARG, because they can remain in the image history.
- A user without privileges
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjsA system user is created and USER nextjs switches to it, so the server does not run as root. --chown makes the standalone files belong to that user.
- The three things to copy
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/staticThree things are copied: the standalone output, .next/static and public. Forget .next/static and pages render, but CSS and client JavaScript return 404 and buttons stop working.
- Listen on every interface
ENV PORT=3000 HOSTNAME=0.0.0.0server.js reads the PORT and HOSTNAME env vars to decide where to listen. Docker sets HOSTNAME to the container ID by default, so it is overridden with 0.0.0.0 to accept connections from outside the container.
docker build --build-arg NEXT_PUBLIC_SITE_URL=https://notes.example.com -t myanmar-notes . finishes with a tagged image. docker run -p 3000:3000 --env-file .env.production myanmar-notes starts server.js as the nextjs user, and the app answers at http://localhost:3000 (the exact log lines vary between versions).Env: bake it in, or pass it at run time?
| Value | Where to supply it | Why |
|---|---|---|
| NEXT_PUBLIC_SITE_URL | docker build --build-arg | Inlined into browser JS at build time |
| DATABASE_URL, AUTH_SECRET | docker run --env-file or the orchestrator's secrets | Kept out of the image and varies per environment |
| APP_VERSION | Build arg or run-time env | Shows the release in logs and health checks |
docker build --build-arg NEXT_PUBLIC_SITE_URL=https://notes.example.com \
-t myanmar-notes:1.4.0 .
docker run -d --name notes -p 127.0.0.1:3000:3000 \
--env-file .env.production -e APP_VERSION=1.4.0 myanmar-notes:1.4.0Publishing the port as 127.0.0.1:3000 means only the reverse proxy on the same server can reach it, never the internet directly. If some static pages need the database at build time, plan how the builder stage connects, or make those pages dynamic.
Health checks and running many instances
Docker, Kubernetes and load balancers regularly ask a container whether it is alive, and restart it or stop sending traffic when it does not answer. The Alpine image has no curl but includes BusyBox wget, which a HEALTHCHECK can use.
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
CMD wget -q -O /dev/null http://127.0.0.1:3000/api/health || exit 1When there is more than one container
With many instances, each container's in-memory and on-disk cache is invisible to the others. Invalidation such as revalidatePath may only reach one instance, so consider a shared cache handler. Some settings, such as the Server Actions encryption key, must also match across all instances. Check the Next.js self-hosting guide for your version's details.
In real projects
In real projects
Companies build the container image once in CI, tag it with the commit SHA or a version, and push it to a registry. Staging and production pull the very same image and only swap secrets per environment, so every bit tested in staging runs unchanged in production.
Uploaded files go to object storage such as S3, and sessions and rate-limit counters go to a database or Redis. That way any container can be replaced at any moment, and the number of instances can grow or shrink with traffic. Teams also rebuild regularly to pick up security patches in the base image (node:22-alpine) and run an image scanner over the result.
Common mistakes
Common mistakes
- Storing uploads, sessions or a SQLite database on the container's filesystem. They vanish on every redeploy, and with two instances users see different data on different requests.
- Exposing the Next.js server's port 3000 directly to the internet without a reverse proxy. There is no HTTPS, no compression and no rate limiting, and slow clients can hold connections open for a long time.
- Copying only the standalone folder and forgetting .next/static and public. You get pages whose HTML renders but have no styles and dead buttons.
- Running COPY . . without a .dockerignore, or putting secrets in the Dockerfile with ENV. Anyone who obtains the image can read those secrets, even after you delete them in a later layer.
Mini challenge
Try it yourself: a liveness and readiness health route
Write app/api/health/route.ts for the container's HEALTHCHECK and the load balancer. /api/health answers only whether the process is alive (liveness), while /api/health?ready=1 also checks that the database is reachable (readiness). If the database does not answer, do not wait forever: time out and return 503.
- Liveness returns 200 { status: "ok", version } without touching the database
- Readiness pings the database with a 500 ms timeout: 200 "ready" on success, 503 "not-ready" otherwise
- Take version from the run-time env var APP_VERSION
- When readiness fails, write one JSON log line without secrets
type Ping = () => Promise<void>;
// In the app this would run `SELECT 1` through your db module.
let pingDatabase: Ping = async () => {};
function withTimeout(task: Promise<void>, ms: number): Promise<void> {
// TODO: reject with Error("timeout") if task takes longer than ms
return task;
}
export async function GET(request: Request): Promise<Response> {
// TODO: read APP_VERSION and the ?ready=1 query parameter
// TODO: liveness: 200 { status: "ok", version }
// TODO: readiness: ping with a timeout, 200 "ready" or 503 "not-ready" + a log line
return Response.json({});
}
// TODO: probe(path) calls GET with new Request(...) and prints status + body
// TODO: probe both paths, then swap in a database that never answers and repeatExpected: The first two probes show 200 "ok" and 200 "ready". After swapping in a database that never answers, liveness still returns 200 "ok" while readiness logs readiness-failed and returns 503 "not-ready". The version is 1.4.0 throughout.
Show hint
Promise.race([task, timeoutPromise]) settles with whichever finishes first. Read the query with new URL(request.url).searchParams.get("ready"). A database that never answers can be faked with () => new Promise(() => {}).
Show solution
// Liveness (/api/health) answers "is the process up?".
// Readiness (/api/health?ready=1) also asks "can it reach the database?".
type Ping = () => Promise<void>;
// In the app this would run `SELECT 1` through your db module.
let pingDatabase: Ping = async () => {};
function withTimeout(task: Promise<void>, ms: number): Promise<void> {
const timeout = new Promise<void>((_, reject) => {
setTimeout(() => reject(new Error("timeout")), ms);
});
return Promise.race([task, timeout]);
}
export async function GET(request: Request): Promise<Response> {
const version = process.env.APP_VERSION ?? "unknown";
const wantsReady = new URL(request.url).searchParams.get("ready") === "1";
if (!wantsReady) return Response.json({ status: "ok", version });
try {
await withTimeout(pingDatabase(), 500);
return Response.json({ status: "ready", version });
} catch (err) {
const reason = (err as Error).message;
console.error(JSON.stringify({ event: "readiness-failed", reason }));
return Response.json({ status: "not-ready", version }, { status: 503 });
}
}
// Demo: call the handler the way a HEALTHCHECK or load balancer would.
async function probe(path: string) {
const res = await GET(new Request(`http://localhost:3000${path}`));
console.log(`${path} -> ${res.status} ${JSON.stringify(await res.json())}`);
}
async function demo() {
process.env.APP_VERSION = "1.4.0";
await probe("/api/health");
await probe("/api/health?ready=1");
pingDatabase = () => new Promise(() => {}); // a database that never answers
await probe("/api/health");
await probe("/api/health?ready=1");
}
demo();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- output: "standalone" emits server.js and only the needed node_modules; copy public and .next/static yourself
- A multi-stage build separates install, build and run, keeping the final image small
- Pass NEXT_PUBLIC_ values as build args and secrets at run time, never inside the image
- Use a non-root user, a health check and a reverse proxy, and keep data outside the container
Next.js — Self-Hosting — Next.js
Next.js — Self-Hosting — Next.js