HomeBlogHow to Deploy Node.js Applications Using...

Engineering Guide · 8 min read · June 1, 2026

How to Deploy Node.js Applications Using Docker

A working local Dockerfile often turns into a 1.2 GB root-owned image in production that ignores SIGTERM during deployments and drops in-flight HTTP requests. This practical guide covers multi-stage TypeScript/Node.js builds, proper PID 1 signal forwarding, non-root security, graceful shutdown code, and reverse-proxy deployment.

Author
Smit Desai
Published
June 1, 2026
Read time
8 min read
Topic
Cloud & DevOps
Services
Custom Web · Mobile Apps · All Services

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.

Deploying Node.js Applications With Docker


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

  1. ENTRYPOINT ["dumb-init", "--"]: Inside Linux containers, PID 1 ignores default termination signals unless a process explicitly registers handlers. dumb-init forwards SIGTERM cleanly to Node.js and reaps orphaned child processes.
  2. 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 a node user (uid 1000) ready to use.
  3. Immutable CMD ["node", "dist/server.js"]: Skipping npm start cuts 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:3000 so 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-size roughly to 75% of your container memory limit (for a 1024 MB container, set NODE_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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

cloud & devops

Why shouldn't I use npm start in a production Node.js Dockerfile?

Running CMD ["npm", "start"] spawns npm as PID 1, which often fails to forward SIGTERM signals cleanly to the child node process. Using CMD ["node", "dist/server.js"] (paired with dumb-init or --init) ensures Node receives shutdown signals immediately.

Should I choose node:22-alpine or node:22-slim for production?

node:22-alpine produces slightly smaller images using musl libc, while node:22-slim uses standard Debian glibc. If your app depends on native C++ addons, Prisma binaries, or sharp/canvas, node:22-slim avoids subtle musl compatibility issues while remaining compact.

How do I stop Docker builds from taking several minutes every time I edit one source file?

Copy package.json and your lockfile first, run npm ci before copying your source directory, and include node_modules and .git inside .dockerignore so Docker reuses the cached dependency layer.

How do I run background jobs alongside a containerized Node.js API?

Build one shared image and run two separate containers from it: one executing the HTTP server and another executing your BullMQ or worker entrypoint, so CPU-heavy jobs never starve API response times.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.