Skip to content

A smaller Docker image for Next.js: multi-stage builds and standalone output

From the work/ 11 min read

Shrink a Next.js Docker image with a multi-stage build, output: 'standalone', a slim base and a .dockerignore. The full Dockerfile, explained line by line.

  • Next.js
  • Node.js
  • Performance
In this article (9)
  1. Why your Docker image is so big
  2. Multi-stage builds: build in one stage, run in another
  3. Next.js output: 'standalone': what it copies and what it doesn't
  4. Base image: slim or alpine
  5. .dockerignore: what should never reach the build context
  6. Measure before and after
  7. Common mistakes
  8. Frequently asked questions
  9. Checklist

To make a Next.js Docker image smaller, combine four things: a multi-stage build that installs and compiles in stages you never ship, output: 'standalone' so you copy only the server and the dependencies it uses, a -slim base image, and a .dockerignore that keeps everything else out.

Below is the full Dockerfile explained line by line, what the standalone folder includes and what it leaves out, when to pick slim or alpine, and how to measure before and after. We tested the standalone output with Next.js 16.4.6; the Dockerfile itself was not built on this machine, and we say so where it matters.

Why your Docker image is so big

Most heavy images come from a single-stage Dockerfile like this one:

FROM node:24.22.3-bookworm
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
  1. FROM node:24.22.3-bookworm uses the full variant. According to the official Node image docs, it is built on buildpack-deps and ships a large number of common Debian packages. Useful for compiling, unused by your server.
  2. COPY . . with no .dockerignore pulls in everything in the folder: .git, your local node_modules, a stale .next and, if it exists, your .env.
  3. npm install also installs devDependencies: TypeScript, ESLint, test tooling. You need them to build, not to run.
  4. npm run build leaves the build output and its cache in .next, and all of it stays in the image.
  5. npm start runs next start, which needs the whole node_modules.

Every instruction adds a layer. Deleting files in a later instruction does not remove them from the layer that wrote them: they are still in the image, just hidden. So the fix is not cleaning up at the end, it is never putting those files in the final image.

the same app, two Docker imagesbefore · one stageafter · three stagesnode:24-bookworm (full)COPY . . (source, .git, .env)npm install (all deps)npm run build (.next, cache)node:24-bookworm-slimstandalone: server.js + deps.next/staticpublicleft behind in the build stage:devDependencies, source, cacheheights are illustrative: they show which layers exist, not their sizethe final image carries only what runsDocker multi-stage + Next.js output: 'standalone'

Scroll the figure sideways to see all of it

Multi-stage builds: build in one stage, run in another

A multi-stage build uses several FROM lines in one Dockerfile. Each starts a fresh stage. The Docker docs put it this way: you can selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image. You name stages with AS and copy between them with COPY --from. Here is the full Dockerfile for a Next.js app, with the same shape as the Next.js with-docker example:

# syntax=docker/dockerfile:1
ARG NODE_VERSION=24.22.3-bookworm-slim

# 1) deps: install every dependency (dev included) from the lockfile
FROM node:${NODE_VERSION} AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund

# 2) build: compile the app with output: "standalone"
FROM node:${NODE_VERSION} AS build
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# 3) runner: only the standalone server, static files and public
FROM node:${NODE_VERSION} AS runner
WORKDIR /app
ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3000 \
    HOSTNAME=0.0.0.0
COPY --from=build --chown=node:node /app/.next/standalone ./
COPY --from=build --chown=node:node /app/.next/static ./.next/static
COPY --from=build --chown=node:node /app/public ./public
USER node
EXPOSE 3000
CMD ["node", "server.js"]
  1. ARG NODE_VERSION before the first FROM sets the base image in one place for all three stages. We use the exact version: on November 19, 2026 the newest on the 24 line is 24.22.3, a security release from November 10.
  2. The deps stage copies only package.json and the lockfile and runs npm ci. Since this layer depends on those two files alone, Docker reuses it from cache until your dependencies change, even when your code does.
  3. The build stage brings in node_modules from deps, copies the source and compiles. This is where devDependencies are needed.
  4. COPY . . relies on the .dockerignore below: without it, your local node_modules would overwrite the Linux one.
  5. The runner stage starts again from the clean base image. NODE_ENV=production, the port and HOSTNAME=0.0.0.0 are set as environment variables.
  6. The three COPY --from=build lines bring over only the standalone folder, the static files and public. --chown=node:node gives the files to the node user, which already exists in the official image, so the server can write its cache under .next.
  7. USER node runs the process without root, and CMD ["node", "server.js"] starts the minimal server instead of next start.

With BuildKit, Docker only builds the stages the target stage depends on, and --target stops at an intermediate one: docker build --target build . lets you inspect what the build produced.

three stages in one Dockerfile, one final image1 · depspackage.jsonpackage-lock.jsonnpm cinode_modules (all)2 · buildCOPY --from=depsCOPY . .npm run build.next/standalone3 · runnerstandalone → ./.next/staticpublicnode server.jseach stage starts clean: only what you COPY --from crosses overthe image you push is the runner stage; deps and build stay behindbuild in one stage, run in anotherDocker Docs: multi-stage builds; Next.js with-docker example

Scroll the figure sideways to see all of it

Next.js output: 'standalone': what it copies and what it doesn't

Multi-stage alone is not enough: if the final stage copies the whole node_modules to run next start, you still carry every dependency. The Next.js piece is output: 'standalone':

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

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

export default nextConfig;

According to the output docs, during next build Next.js traces the import, require and file reads of every page, and with this option it writes .next/standalone: a minimal server.js plus only the node_modules files the server uses. That folder deploys without installing dependencies. It does not copy public or .next/static, because those are meant for a CDN; copy them in by hand and server.js serves them.

Folder or fileIn .next/standalone?Where it goes in the image
server.jsYes/app/server.js
Traced node_modulesYes, only what is used/app/node_modules
.next/staticNo/app/.next/static
publicNo/app/public
.env, .env.productionYes, if next build loaded themBetter kept out: pass secrets at runtime

We tested it with a minimal Next.js 16.4.6 app. Before copying anything, server.js returned 200 for the page and an API route, but 404 for the JavaScript under /_next/static and for an image in public: the page loads with no styles and no interactivity. After the documented cp, everything returned 200, /_next/image included, because sharp is traced into standalone. As an illustrative reference, in that Windows test the project's node_modules took 379 MB and the standalone folder 33 MB; your ratio will differ.

Two variables control where it listens: PORT (default 3000) and HOSTNAME (default 0.0.0.0). In Docker this matters: Docker sets HOSTNAME in every Linux container to the container's hostname, per the container run reference, and server.js would then listen only on that address. We tried it with the machine's name: the app answered on that name and not on 127.0.0.1. That is why the Dockerfile sets HOSTNAME=0.0.0.0, like the official example.

If your app reads files through paths built at runtime, tracing may miss them: add them with outputFileTracingIncludes. In a monorepo, outputFileTracingRoot tells it where to trace from.

Base image: slim or alpine

The official Node image comes in three families: the full one; -slim, with only what node needs to run; and -alpine, based on Alpine Linux, much smaller but built on musl instead of glibc, which can cause trouble depending on what your dependencies assume about libc. bookworm and trixie are Debian releases. We read the Docker Hub registry manifests on November 19, 2026 (compressed layer size, linux/amd64):

  • node:24.22.3-bookworm: 410 MB.
  • node:24.22.3-bookworm-slim: 81 MB.
  • node:24.22.3-trixie-slim: 83 MB.
  • node:24.22.3-alpine: 63 MB.

On disk they take more, because layers are unpacked after the pull. Docker's build best practices recommend Alpine for its size; the Next.js example uses slim for compatibility with native packages. Both positions make sense: start with slim, and try alpine if size is critical and your native dependencies (sharp, database drivers, bcrypt) ship musl builds. If you switch base, run the app and its tests, not just the build.

Two more notes. Pinning the exact version makes it obvious which Node runs; when a patch ships, you change one line and rebuild, as covered in updating Node in Docker. And if you use the Next.js image optimizer on a glibc base, the self-hosting guide warns it may need extra configuration to avoid excessive memory use; we ran into that in reducing Next.js memory usage.

Node base images for the runner stagetaglibcpullwhat it hasnode:24.22.3-bookwormglibc410 MBfull: many common Debian packagesnode:24.22.3-bookworm-slimglibc81 MBjust what node needs to runnode:24.22.3-trixie-slimglibc83 MBslim on Debian 13 (trixie)node:24.22.3-alpinemusl63 MBsmallest; test your native depscompressed layer size, linux/amd64, Node 24.22.3on disk they take more: layers are unpacked after the pullslim by default; alpine if your deps cope with muslDocker Hub registry manifests, read on 19 Nov 2026

Scroll the figure sideways to see all of it

.dockerignore: what should never reach the build context

When you run docker build ., that folder is the build context. Per the build context docs, the client looks for a .dockerignore at its root and does not send matching files to the builder. A starting point:

node_modules
.next
.git
.env*
!.env.example
npm-debug.log*
coverage
test-results
playwright-report
*.md
Dockerfile*
.dockerignore
  1. node_modules: yours holds binaries for your operating system. If it gets in, COPY . . overwrites the one npm ci installed on Linux, and the build fails or runs with the wrong binaries.
  2. .next: output of a local build. The container build makes its own.
  3. .git: the full repo history, which no stage uses.
  4. .env* with the !.env.example exception: secrets stay out. Next.js copies .env and .env.production into .next/standalone when next build loads them, so they would end up in the image. Pass them as environment variables when the container starts. NEXT_PUBLIC_ values are inlined at build time, so they go in as ARG in the build stage; check what is public in NEXT_PUBLIC variables and secrets.
  5. Logs, test reports and Markdown: none of it runs in production.
  6. Dockerfile* and .dockerignore: Docker still sends them because it needs them, but COPY cannot use them.

Patterns go one per line, like shell globs; ! adds an exception and the last matching line wins. If you keep non-secret build values in .env.production, let it through with !.env.production.

Measure before and after

Do not settle for a feeling that it got smaller: compare both images built from the same app. Save the single-stage Dockerfile as Dockerfile.naive and build both:

docker build -f Dockerfile.naive -t my-app:before .
docker build -t my-app:after .
docker image ls my-app
docker image history my-app:after
docker run --rm -p 3000:3000 my-app:after
  1. The first two lines build the single-stage version and the new one under different tags.
  2. docker image ls my-app shows the SIZE column, which the reference defines as the cumulative space of the image and its parent images, base included.
  3. docker image history lists every layer with the instruction that created it and its size: that tells you whether a big layer is the base, the dependencies or a file that should not be there.
  4. docker run starts it on port 3000. Open the page and check that a file under /_next/static, one from public and, if you use it, /_next/image return 200.

Write both numbers down with the date and the base version. We publish no image sizes because this guide was not built against a real project: the difference depends on your dependencies, your base and what sits in public. If the final image is still large, docker image history shows which layer carries the weight.

Common mistakes

  • Forgetting .next/static or public. The page returns 200 with no JavaScript, CSS or images. Standalone does not copy them.
  • Not setting HOSTNAME=0.0.0.0. Docker sets its own HOSTNAME and the server listens only on that address.
  • Copying your local node_modules. Without .dockerignore, your machine's binaries overwrite the Linux ones.
  • Running next start in the final image. It forces you to ship every dependency; with standalone it is node server.js.
  • Leaving .env in the context. Next.js copies it into standalone and it ships inside the image.
  • Switching to alpine without testing. A native package with no musl build can fail only at startup or on first use, not during the build.
  • A project with no public folder. COPY --from=build /app/public fails if it does not exist; create the folder or drop that line.

Frequently asked questions

Do I need standalone if I already use a multi-stage build?

If the final stage runs next start, it needs the whole production node_modules. Standalone cuts that down to the files the server actually uses. The two techniques stack.

Does standalone work with Next.js 15 and 16?

Yes. output: 'standalone' has been stable since Next.js 12.2, per its release post, and the configuration is the same. We tested it with 16.4.6, the latest version on npm on November 19, 2026.

Alpine or slim for Next.js?

Slim, unless size is critical. Alpine is smaller but uses musl; if a native dependency does not support it, you find out when the app runs, not when it builds. If you pick it, test the whole app in the image.

Where do environment variables and secrets go?

Secrets go in when the container starts, from your platform or your secret manager. NEXT_PUBLIC_ values go in as ARG in the build stage, because they are inlined into the JavaScript. None of them should live in a .env inside the build context.

Checklist

  • output: "standalone" in next.config.
  • Three stages, deps, build and runner, with the same base pinned in one ARG.
  • package.json and the lockfile are copied before the source.
  • The final stage copies .next/standalone, .next/static and public.
  • PORT and HOSTNAME=0.0.0.0 are set; it starts with node server.js.
  • It runs as USER node.
  • .dockerignore keeps out node_modules, .next, .git and .env.
  • Slim base; alpine only after testing the app.
  • You measured with docker image ls and docker image history, and static files return 200.

A smaller image pulls and starts faster, but it still runs whatever Node its base carries. When a patch ships, see how to update Node in Docker.

Saw this on Instagram? Comment DOCKER on the Reel and I'll send you the guide.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 19, 2026

← Blog