How to Write a Production Dockerfile for Node.js
Build a production Dockerfile for Node.js: multi-stage builds, npm ci, a non-root user, a health check, signal handling and a .dockerignore.

A Dockerfile that works on your laptop is not yet one you should deploy. The quick version copies everything, installs development dependencies, runs as root and starts the app through a layer of wrappers that swallow stop signals. Each of those is a small problem that turns into a large one in production: slow builds, big images, a wider attack surface and containers that take ten seconds to stop. This post turns the minimal Dockerfile from How to Run Node.js in Docker into one you can ship. Each line has a reason, and the post explains it. The samples use Node.js 26 and the official node image, and the application is a small HTTP service with a build step that compiles source into a dist directory, so the multi-stage pattern has something to do.
What production needs that development does not
Reproducible installs. The same lockfile must give the same dependency tree on every build.
Small images. Fewer files mean faster pulls, quicker deploys and less to patch.
No build tools at run time. Compilers and development dependencies do not belong in the image that serves traffic.
A non-root user. If the app is compromised, the attacker should not be root inside the container.
Correct signals. The container must stop quickly and cleanly on
SIGTERM.A health signal. The platform should be able to tell a running but broken container from a healthy one.
A cache-friendly layer order. Rebuilds after a code change should take seconds.
The finished Dockerfile
Here is the whole file first, then each part explained.
FROM node:26-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:26-slim AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build && npm prune --omit=dev
FROM node:26-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --from=build --chown=node:node /app/package.json ./
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
CMD ["node", "dist/server.js"]The docker build command reads the whole file top to bottom and builds the stages in order.
Multi-stage builds
A multi-stage build has several FROM lines. Each starts a new, separate image stage, and a later stage can copy files from an earlier one with COPY --from=. Only the last stage becomes the final image, and everything else is thrown away. That is how a build that needs a compiler and development dependencies produces a run-time image with neither.
The three stages here have distinct jobs.
**
deps** installs every dependency, development ones included, using only the two manifest files. Because it copies justpackage.jsonandpackage-lock.json, Docker reuses its cached result until one of those files changes. Editing your source does not touch this stage, so a typical rebuild skips the slowest step.**
build** brings in the installed modules and your source, runs the build script and then runsnpm prune --omit=devto remove the development dependencies fromnode_modules. What remains is exactly the packages the app needs at run time.**
runtime** starts from a clean base image and copies in only the prunednode_modules, the compileddistdirectory andpackage.json. No source files, no TypeScript compiler, no test tools.
The stage names after AS are labels that COPY --from= refers to. You can also build a single stage with docker build --target build ., which is handy for running tests in CI against the build stage.
Use npm ci, not npm install
RUN npm cinpm ci installs exactly what package-lock.json records. It fails if the lockfile and package.json disagree, and it never rewrites the lockfile. npm install may resolve newer versions and change the file. For a build that must be repeatable, npm ci is the right command, as the npm documentation describes. It also deletes any existing node_modules first, so the result is clean. Commit your lockfile, because the build cannot work without it.
For a service with no build step, you can skip the middle stage and install production dependencies directly in the runtime stage with RUN npm ci --omit=dev.
The final base image
The runtime stage uses node:26-slim again. Using the same major version in every stage keeps native modules compiled in the build stage compatible with the runtime stage, because they come from the same operating system and libc. Mixing, for example, a glibc build stage with an Alpine runtime stage would break any package with a compiled addon.
You can go further for the runtime image. A distroless Node.js image, which contains the runtime and not a shell or package manager, shrinks the attack surface more, at the cost of being harder to debug because you cannot open a shell in it. Whichever base you choose, pin the major version, and for strict reproducibility pin by digest, which is the @sha256: form, updated deliberately by a dependency bot.
Run as a non-root user
By default processes in a container run as root. The official node images already create an unprivileged user named node, so switching to it takes one line.
USER nodeFiles copied into the image are owned by root unless you say otherwise, so the COPY lines use --chown=node:node. That matters when the app needs to write into its own directory. If your app only reads its files, you can leave ownership alone, and the unprivileged user can still read them. Anything the app must write, such as uploads or a cache, belongs on a mounted volume or /tmp, not in the image.
A non-root user also cannot bind ports below 1024. That is why the example listens on 3000. If you need port 80, map it at publish time with -p 80:3000 and keep the process on a high port.
Set NODE_ENV=production
ENV NODE_ENV=productionMany libraries change behaviour when NODE_ENV is production: Express caches view templates and produces shorter error output, and several packages disable debug features. Set it in the runtime stage. Do not set it before npm ci in a build stage that needs development dependencies, because npm ci skips them when it is production. That ordering is why the variable appears only in the last stage.
Start Node.js directly
CMD ["node", "dist/server.js"]Use the exec form and call node itself. Starting the app with npm start puts npm between Docker and your process, and npm does not forward SIGTERM to its child. docker stop sends SIGTERM, waits ten seconds by default and then kills the container with SIGKILL, so a wrapped process is killed abruptly after a long delay and never runs its shutdown code. With node as the main process, your signal handlers run. A server that handles shutdown gracefully stops accepting connections, finishes in-flight requests and exits, as shown in How to Handle Graceful Shutdown in Node.js.
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/healthz") {
res.end("ok");
return;
}
res.end("hello\n");
});
server.listen(3000, "0.0.0.0");
process.on("SIGTERM", () => {
console.log("SIGTERM received, closing");
server.close(() => process.exit(0));
});When you stop the container, the log shows:
SIGTERM received, closingThere is one more subtlety. In a container, your process is PID 1, and Linux treats PID 1 specially: it does not get default signal handling, and it must reap zombie child processes. Node.js with an explicit SIGTERM handler, as above, is fine for signals. If your app spawns many child processes, add a tiny init process by running the container with docker run --init, or set init: true in Compose, so zombies are reaped.
Add a health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"A HEALTHCHECK runs a command inside the container on a schedule, and Docker marks the container healthy or unhealthy from its exit code. The command here uses the global fetch in Node.js 26, so it needs no curl, which is not present in slim images. The --start-period gives the app time to boot before failures count, and --retries=3 means three failures in a row make it unhealthy. Your /healthz route should check that the app can do its job, but keep it cheap: a check that queries a database every 30 seconds from every replica can itself cause load. Orchestrators such as Kubernetes ignore the Dockerfile HEALTHCHECK and use their own probes, so treat it as a default for plain Docker and Compose.
The .dockerignore file
The build context is everything Docker sends to the builder. Keep it small and free of secrets.
node_modules
dist
.git
.env
.env.*
*.log
coverage
Dockerfile
.dockerignore
README.mdExcluding dist and node_modules stops stale local build output overwriting what the image builds itself. Excluding .env and .env.* keeps secrets out of every layer. A layer that once contained a secret keeps it, even if a later step deletes the file, because the layers are cumulative and can be inspected.
Build and verify
docker build -t myapp:1.0.0 .
docker run --rm -p 8080:3000 --init myapp:1.0.0Check what the image runs as and how big it is:
docker run --rm myapp:1.0.0 id
docker images myappuid=1000(node) gid=1000(node) groups=1000(node)
REPOSITORY TAG IMAGE ID CREATED SIZE
myapp 1.0.0 3f2a9c81d4be 10 seconds ago 224MBThe id command confirms the process is not root. The image id, age and size above are placeholders, and your numbers depend on the base image and your dependencies. Compare the size of a single-stage build to the multi-stage one on your own project to see what the runtime stage saves, and do not trust a figure from someone else's app.
Secrets and configuration
Do not put secrets in the Dockerfile or ENV. Anything in an image layer can be read by whoever can pull the image. Pass configuration when the container starts, with docker run -e, --env-file, or the secrets mechanism of your platform. If a build step needs a secret, such as a private registry token, use a BuildKit secret mount, which exposes the secret to one RUN command without saving it in a layer.
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ciBuild with docker build --secret id=npmrc,src=$HOME/.npmrc .. The token is available to that one command and is not written into the image.
A checklist before you ship
The lockfile is committed and the build uses
npm ci.Stages separate dependencies, build and runtime, and the runtime stage has no dev dependencies.
The base image tag pins a major version, ideally a digest.
USER nodeis set, and the app does not need root or a port below 1024.CMDuses the exec form withnode, notnpm start..dockerignoreexcludes.env,.git,node_modulesand build output.A
HEALTHCHECKor an orchestrator probe exists, anddocker stopfinishes quickly.


