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)
- Why your Docker image is so big
- Multi-stage builds: build in one stage, run in another
- Next.js output: 'standalone': what it copies and what it doesn't
- Base image: slim or alpine
- .dockerignore: what should never reach the build context
- Measure before and after
- Common mistakes
- Frequently asked questions
- 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"]
FROM node:24.22.3-bookwormuses the full variant. According to the official Node image docs, it is built onbuildpack-depsand ships a large number of common Debian packages. Useful for compiling, unused by your server.COPY . .with no.dockerignorepulls in everything in the folder:.git, your localnode_modules, a stale.nextand, if it exists, your.env.npm installalso installsdevDependencies: TypeScript, ESLint, test tooling. You need them to build, not to run.npm run buildleaves the build output and its cache in.next, and all of it stays in the image.npm startrunsnext start, which needs the wholenode_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.
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"]
ARG NODE_VERSIONbefore the firstFROMsets 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.- The
depsstage copies onlypackage.jsonand the lockfile and runsnpm ci. Since this layer depends on those two files alone, Docker reuses it from cache until your dependencies change, even when your code does. - The
buildstage brings innode_modulesfromdeps, copies the source and compiles. This is wheredevDependenciesare needed. COPY . .relies on the.dockerignorebelow: without it, your localnode_moduleswould overwrite the Linux one.- The
runnerstage starts again from the clean base image.NODE_ENV=production, the port andHOSTNAME=0.0.0.0are set as environment variables. - The three
COPY --from=buildlines bring over only the standalone folder, the static files andpublic.--chown=node:nodegives the files to thenodeuser, which already exists in the official image, so the server can write its cache under.next. USER noderuns the process without root, andCMD ["node", "server.js"]starts the minimal server instead ofnext 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.
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 file | In .next/standalone? | Where it goes in the image |
|---|---|---|
server.js | Yes | /app/server.js |
Traced node_modules | Yes, only what is used | /app/node_modules |
.next/static | No | /app/.next/static |
public | No | /app/public |
.env, .env.production | Yes, if next build loaded them | Better 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.
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
node_modules: yours holds binaries for your operating system. If it gets in,COPY . .overwrites the onenpm ciinstalled on Linux, and the build fails or runs with the wrong binaries..next: output of a local build. The container build makes its own..git: the full repo history, which no stage uses..env*with the!.env.exampleexception: secrets stay out. Next.js copies.envand.env.productioninto.next/standalonewhennext buildloads 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 asARGin thebuildstage; check what is public in NEXT_PUBLIC variables and secrets.- Logs, test reports and Markdown: none of it runs in production.
Dockerfile*and.dockerignore: Docker still sends them because it needs them, butCOPYcannot 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
- The first two lines build the single-stage version and the new one under different tags.
docker image ls my-appshows theSIZEcolumn, which the reference defines as the cumulative space of the image and its parent images, base included.docker image historylists 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.docker runstarts it on port 3000. Open the page and check that a file under/_next/static, one frompublicand, if you use it,/_next/imagereturn 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/staticorpublic. 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 ownHOSTNAMEand the server listens only on that address. - Copying your local
node_modules. Without.dockerignore, your machine's binaries overwrite the Linux ones. - Running
next startin the final image. It forces you to ship every dependency; with standalone it isnode server.js. - Leaving
.envin 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
publicfolder.COPY --from=build /app/publicfails 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"innext.config.- Three stages,
deps,buildandrunner, with the same base pinned in oneARG. package.jsonand the lockfile are copied before the source.- The final stage copies
.next/standalone,.next/staticandpublic. PORTandHOSTNAME=0.0.0.0are set; it starts withnode server.js.- It runs as
USER node. .dockerignorekeeps outnode_modules,.next,.gitand.env.- Slim base; alpine only after testing the app.
- You measured with
docker image lsanddocker 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

Published November 19, 2026