Getting a Node.js server running inside a container takes five lines of Dockerfile. Getting that same container to deploy without dropping active user requests, pass a security audit, and stay under 250 MB requires fixing half a dozen subtle defaults that tutorials routinely skip.
When a container receives a stop signal during a rolling deployment, an improperly configured Node.js image hangs for 10 or 30 seconds until Docker sends SIGKILL—severing open database transactions and throwing HTTP 502 errors to users. Here is how to package and deploy Node.js applications with Docker the way production systems actually require.

Choosing the Right Base Image
Start by ditching the default node:22 image. It bundles build toolchains, compilers, and packages you never need at runtime, ballooning image size beyond 1 GB and widening your CVE surface area.
| Base Image | Approximate Compressed Pull Size | C Library | Best Production Use Case |
|---|---|---|---|
node:22 |
~400 MB+ (1 GB+ uncompressed) | glibc |
Build stage only when compiling native addons |
node:22-slim |
~75 MB | glibc |
Default production choice (Prisma, sharp, native bindings) |
node:22-alpine |
~50 MB | musl |
Pure-JS services optimizing for smallest image footprint |
Unless you strictly audit every native dependency against musl, node:22-slim is usually the safest production trade-off: small enough for fast autoscaling pulls, yet fully compatible with standard Linux binaries.
The .dockerignore File You Must Create First
Before Docker sends your project directory to the build daemon, it reads .dockerignore. Without it, COPY . . ships your local node_modules, .env secrets, .git history, and test fixtures into the build context:
.git
.gitignore
node_modules
dist
coverage
.env
.env.*
*.log
Dockerfile
compose.yaml
Keeping .env out of the Docker build context is non-negotiable—never bake environment secrets into image layers where anyone with registry pull access can inspect them via docker history.
Production Multi-Stage Dockerfile (TypeScript + Node.js)
A multi-stage build compiles TypeScript and installs devDependencies in a throwaway builder stage, then copies only production dependencies and compiled JavaScript into a hardened runtime image:
# syntax=docker/dockerfile:1.7
FROM node:22-slim AS builder
WORKDIR /app
# Install dependencies first for layer caching
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
# Strip devDependencies cleanly
RUN npm prune --omit=dev
FROM node:22-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
# Install dumb-init for proper PID 1 signal forwarding and zombie reaping
RUN apt-get update \
&& apt-get install -y --no-install-recommends dumb-init curl \
&& rm -rf /var/lib/apt/lists/*
# Use the built-in non-root 'node' user
COPY --from=builder --chown=node:node /app/package.json ./
COPY --from=builder --chown=node:node /app/node_modules ./node_modules
COPY --from=builder --chown=node:node /app/dist ./dist
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD curl -f http://localhost:3000/healthz || exit 1
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "dist/server.js"]
Why Three Details Here Matter
ENTRYPOINT ["dumb-init", "--"]: Inside Linux containers, PID 1 ignores default termination signals unless a process explicitly registers handlers.dumb-initforwardsSIGTERMcleanly to Node.js and reaps orphaned child processes.USER node: Running as root inside a container turns any application RCE vulnerability into root execution on the container filesystem. The official Node image includes anodeuser (uid 1000) ready to use.- Immutable
CMD ["node", "dist/server.js"]: Skippingnpm startcuts startup memory overhead and removes an unnecessary parent shell process.
Implementing Graceful SIGTERM Shutdown in Node.js
Docker sending SIGTERM accomplishes nothing if your Node.js HTTP server immediately exits—or ignores the signal completely. Wire up graceful draining so in-flight requests finish and database pools close cleanly:
import http from "node:http";
import express from "express";
import { pool } from "./db.js";
const app = express();
let isShuttingDown = false;
app.get("/healthz", async (_req, res) => {
if (isShuttingDown) {
return res.status(503).json({ status: "draining" });
}
try {
await pool.query("SELECT 1");
return res.status(200).json({ status: "ok" });
} catch {
return res.status(503).json({ status: "db_unavailable" });
}
});
const server = http.createServer(app);
const port = Number(process.env.PORT ?? 3000);
server.listen(port, "0.0.0.0", () => {
console.log(JSON.stringify({ level: "info", msg: "server_started", port }));
});
async function shutdown(signal: string): Promise<void> {
if (isShuttingDown) return;
isShuttingDown = true;
console.log(JSON.stringify({ level: "info", msg: "shutdown_started", signal }));
// Force exit if connections hang past orchestrator grace period
const forceTimer = setTimeout(() => {
console.error(JSON.stringify({ level: "error", msg: "forced_exit_timeout" }));
process.exit(1);
}, 15_000);
forceTimer.unref();
server.close(async () => {
await pool.end();
console.log(JSON.stringify({ level: "info", msg: "shutdown_complete" }));
process.exit(0);
});
}
process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
Returning 503 on /healthz as soon as isShuttingDown flips tells your load balancer or reverse proxy to stop routing new requests immediately while existing connections finish draining.
Deploying to a Single Server or Managed Cloud
Whether you deploy this image to AWS ECS, Google Cloud Run, or a Linux VM with Docker Compose, keep the runtime topology disciplined:
- Reverse Proxy & TLS: On a VM, place Caddy or Nginx on the host listening on ports 80/443 and reverse-proxy to
127.0.0.1:3000so Docker never exposes your Node port directly to the public internet. - Heap Memory Alignment: Node.js inside containers does not always respect container cgroup limits automatically for V8 garbage collection on older configurations. Match
--max-old-space-sizeroughly to 75% of your container memory limit (for a 1024 MB container, setNODE_OPTIONS=--max-old-space-size=768) so Node triggers GC before the Linux OOM killer terminates the process. - Separate Background Workers: If your Node.js stack processes webhooks, emails, or heavy exports via BullMQ, run a separate worker container from the same image rather than saturating the API event loop. For deeper queue reliability patterns, see scaling background jobs and queues with Laravel and Redis (the retry, dead-letter, and memory isolation rules apply equally to Node.js workers).
- Cloud Reference Patterns: When moving from a single host to managed multi-AZ deployments, align your load balancer health check intervals with the AWS Architecture Center container best practices and automate image pushes via OIDC as highlighted on the GitHub Engineering Blog.
Ship Containerized Node.js Systems With SmitDev
Containerizing a legacy Node.js API—or hardening multi-stage Docker builds for a scaling SaaS product—eliminates "works on my laptop" surprises and cuts rollback time to seconds. Across years of shipping production web platforms and overseeing large multi-site Linux infrastructure in Europe, I prioritize predictable health checks, non-root runtime containers, and repeatable CI pipelines.
Whether you need to migrate a brittle VM setup through a legacy software upgrade or add senior DevOps capacity via remote software engineering or an hourly developer ($55/day for an 8–9 hour workday or $1,999/month retainer), reach out via our contact page to tighten your container workflow.