How to Containerize a Node.js App with Docker for Production
๐ Want the best deal? Check current prices and availability.
Compare Prices โWhen you buy through links on our site, we may earn a commission.
How to Containerize a Node.js App with Docker for Production
Most Docker tutorials for Node.js stop at FROM node:latest and CMD ["npm", "start"]. That gets you a container. It doesn't get you a container you'd want running at 3 a.m. when your payment webhook handler is the only thing between you and an angry customer.
This guide walks through the version I actually ship: a multi-stage build, a non-root user, proper signal handling, a health check that means something, and a deployment path that doesn't cost more than your database. By the end you'll have a Dockerfile you can copy into any Node project and a clear picture of where to run it.
Let me be upfront about the tradeoffs too. Docker adds real overhead for a solo developer โ build times, image registry costs, a whole extra layer of debugging. We'll get to when it's worth it and when it isn't.
Why bother containerizing a Node app at all?
You can deploy Node without Docker. git push to a platform that runs npm start and you're done. So what does the container buy you?
Three things, mostly. First, environment parity โ the Node version, the OS libs, the sharp binary compiled against glibc instead of musl. If it works on your laptop's container, it works in production because it's the same filesystem. Second, immutable artifacts โ the image you tested in staging is byte-for-byte the image running in prod. No "well, the server had a different Node patch version." Third, portability โ the same image runs on Railway, Fly.io, ECS, or a $6 VPS. You're not locked into a buildpack.
The cost is real: an extra build step in CI, a registry to manage, and a debugging experience that's slightly worse than SSHing into a box and reading logs. For a small API, that's usually still a good trade. For a static site, it's overkill.
The base image decision (and why it matters more than you think)
Before the Dockerfile, pick your base. This single line drives your image size, your attack surface, and whether native modules compile.
| Base image | Approx. compressed size | Native modules | Notes |
|---|---|---|---|
node:22 | ~350 MB | Works | Full Debian. Almost never what you want. |
node:22-bookworm-slim | ~80 MB | Works | The safe default. glibc, small enough. |
node:22-alpine | ~50 MB | Needs python3 Make g++ | musl libc. Breaks prebuilt binaries like some sharp/bcrypt builds. |
node:22-distroless | ~70 MB | Works | No shell. Great for security, painful for debugging. |
My default is bookworm-slim. Alpine's size advantage evaporates the moment you install build tools to compile a native module, and then you're shipping a 200 MB image with a compiler in it. The glibc compatibility is worth the extra 30 MB.
If you're on a security-sensitive project, distroless is genuinely better โ no shell means no curl | bash post-exploitation. Just know you can't docker exec in to poke around.
Step 1: The .dockerignore file
Write this before the Dockerfile. A missing .dockerignore means your COPY . . drags node_modules, .git, and your .env file into the build context โ slow builds and, in the .env case, a leaked secret baked into a layer.
node_modules
npm-debug.log
.git
.gitignore
.env
.env.*
!.env.example
dist
coverage
.vscode
.idea
Dockerfile
docker-compose*.yml
README.md
The .env exclusion matters. Layers are forever โ deleting a file in a later layer doesn't remove it from the image. Anyone who pulls the image can recover it.
Step 2: A production Dockerfile
Here's the full thing. I'll explain each piece below.
# ---------- build stage ----------
FROM node:22-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
---------- runtime stage ----------
FROM node:22-bookworm-slim AS runtime
ENV NODE_ENV=production
ENV NODE_OPTIONS=--max-old-space-size=384
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends dumb-init \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --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))"
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "dist/server.js"]
Why two stages
The build stage has devDependencies, TypeScript, your bundler, and whatever else. The runtime stage has none of it. On a typical Express + TypeScript API this takes the image from ~450 MB down to ~180 MB. Smaller images pull faster, which matters when your platform is spinning up a new instance during a traffic spike.
Why npm ci and not npm install
npm ci reads package-lock.json and fails if it doesn't match package.json. That's what you want in a build โ a deterministic install. npm install will happily resolve a newer minor version and give you a build that differs from your laptop's.
Why copy package.json first
Docker caches layers. Copying only the manifest before npm ci means the dependency layer is reused on every build where your dependencies haven't changed. Edit a source file and the rebuild takes seconds instead of two minutes. This one trick is the difference between a tolerable and an intolerable CI pipeline.
Why dumb-init
Node doesn't handle PID 1 duties well. When your orchestrator sends SIGTERM to stop a container, Node as PID 1 won't forward the signal to child processes and won't reap zombies. dumb-init sits in front and does both. Without it, your graceful shutdown handler never fires and in-flight requests get killed.
If you'd rather not install a package, docker run --init does the same thing โ but you can't always control the run flags on managed platforms, so baking it in is safer.
Why the non-root user
The node image ships with a node user at UID 1000. USER node means a container escape lands you as an unprivileged user instead of root. This is table stakes for anything handling real data, and several compliance frameworks won't let you ship without it.
Note the --chown=node:node on the COPY lines. Without it, files are owned by root and your app can't read them after switching users.
Why the health check
HEALTHCHECK lets the platform distinguish "container is running" from "app is actually serving." The check hits a /healthz endpoint that should verify your database connection and return 200. Keep it cheap โ it runs every 30 seconds. Don't run a full integration test in there.
The --start-period=15s gives your app time to boot before failures count. Without it, slow-starting apps get killed in a restart loop.
Step 3: Handle shutdown properly
Your app needs to close the HTTP server and drain the database pool on SIGTERM. With dumb-init in place, this works:
const server = app.listen(3000);
process.on('SIGTERM', () => {
server.close(async () => {
await db.end();
process.exit(0);
});
setTimeout(() => process.exit(1), 10000).unref();
});
The timeout is the important part. If a request hangs, you still exit before the platform's grace period (usually 30s) expires and it sends SIGKILL. Exiting on your own terms is cleaner than getting killed.
Step 4: Local development with Compose
Don't run the production image locally for development โ you lose hot reload and you rebuild on every change. Use a separate dev setup.
services:
api:
build:
context: .
target: build
command: npm run dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
DATABASE_URL: postgres://dev:dev@db:5432/app
depends_on:
db:
condition: service_healthy
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: dev
POSTGRES_PASSWORD: dev
POSTGRES_DB: app
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U dev"]
interval: 5s
retries: 5
volumes:
pgdata:
The anonymous volume on /app/node_modules is the trick that keeps your host's node_modules from overwriting the container's. It's the single most common source of "works on my machine" confusion in Node + Docker setups.
Step 5: Build for the right architecture
If you're on an M-series Mac and deploying to x86 servers, a plain docker build produces an arm64 image that will fail to start. Build multi-arch:
docker buildx build --platform linux/amd64,linux/arm64 \
-t registry.example.com/my-api:$(git rev-parse --short HEAD) --push .
Tag with the git SHA
๐ Want the best deal? Check current prices and availability.
Compare Prices โ