Skip to main content

Chapter 36 — Containers & the 12-Factor App

Part VII · Delivery | Prerequisites: Ch 3, Ch 8 | Builds: Pulsely containerized with a production multi-stage Dockerfile + Compose

Earlier you saw what a process actually is — a thread of execution the kernel schedules, given its own virtual address space, its own file descriptors, and a fence around what it can touch. You met the kernel mechanisms (namespaces, cgroups) almost in passing, as facts about how the OS keeps tenants apart. This chapter is where that knowledge pays off. A container is not a new kind of thing you have to learn from scratch; it is a process you already understand, wearing a costume the kernel sews for it. Once you see that, the whole edifice — images, layers, registries, Compose, even Kubernetes — stops being magic and becomes mechanics.

But packaging a process is only half the job. A box that boots reliably is worthless if the application inside it can't survive being run five times at once, killed without warning, and moved between machines. So this chapter has two halves that lock together: containers (the packaging) and the twelve-factor discipline (the application constraints that make the package replicable). One without the other is a trap. We'll derive both from problems, then containerize Pulsely for real.


1. The problem: "works on my machine," and three deploys that hurt​

Here is a scene every backend engineer eventually lives through. Pulsely renders patient-facing report PDFs and DICOM thumbnails, and that path uses sharp, a native module that compiles against system libraries. On the author's laptop it works perfectly — Node 20, sharp globally cached, a .env file nobody committed (holding the database URL and a live PHI-store credential) sitting helpfully in the project root. CI is green-ish until the image step, where it dies: the runner has a different glibc, sharp's prebuilt binary doesn't match, and npm ci recompiles against headers that aren't there. Staging dies differently — same code, different distro, a missing environment variable that lived only in the author's shell. Debugging becomes archaeology across three environments, none of which is the same as the other two. The bug isn't in the code. The bug is that the code was never the unit being shipped — the whole environment was, implicitly, and nobody controlled it.

Now widen the lens to deployment. The classic small-team deploy is: SSH to the box, git pull, npm ci, pm2 restart. It works on day one. By day ninety, that box is a snowflake — a one-off no other machine matches. Someone hotfixed a config by hand at 2 a.m. and never wrote it down. A migration ran half-way and stopped. node_modules has a leftover from a dependency you removed three sprints ago. No two servers are byte-identical, so a bug that reproduces on server #2 and not #4 has no explanation you can find. And "rollback" means git checkout the previous SHA and rebuild on the box — hoping it still builds, during an outage, while clinicians stare at 500s mid-visit.

And scale. To run five copies of the API, the snowflake model says: provision five VMs. Each is a two-minute boot plus a config-management run, each carries a full guest OS to run your 200 MB process, and you're bin-packing 200 MB of work into 4 GB of metal. Wasteful in money, slow in time, fragile in operation.

The promise this chapter cashes: ship the exact filesystem and process the developer tested, as one immutable artifact, that boots in roughly a tenth of a second and packs many-to-a-host. No "works on my machine," because your machine — the relevant parts of it — is what ships. But that promise has a condition attached, and the condition is the second half of the chapter: the artifact is only safe to replicate if the app inside obeys rules that make "just run another copy" actually correct. Containers buy you the package; twelve-factor buys you the right to run it many times.


2. The mental model: a process the kernel lied to, frozen into a tarball​

Hold four pictures.

A container is a process, not a machine. This is the single most important sentence in the chapter. When you "run a container," the kernel starts an ordinary Linux process and then lies to it: it tells the process that it has its own root filesystem (a private /), that it is PID 1, that it has its own network interface, and that the machine has only the CPU and RAM you allotted. There is no guest operating system, no hypervisor, no second kernel. The container shares the host's kernel and is scheduled by it exactly like any other process. Strip the lies away and a container is node dist/server.js — just one that can't see your files, can't see your other processes, and can't use more than its slice.

🧭 Mental model. A VM virtualizes hardware and runs a whole guest OS on top; a container virtualizes the view a process has of the OS and runs no guest at all. "VM = a fake computer; container = a process wearing blinders." This is why containers boot in milliseconds (it's just fork/exec with extra setup) and VMs boot in tens of seconds (a kernel has to come up). It is also why the isolation is weaker — a topic for §8.

An image is a tarball, not a running thing. An image is a frozen filesystem plus a little metadata (what command to run, what ports it declares, what env it defaults). It is the class; a container is the instance. "Run image → container" is "construct an object from a class." You can have one image and a hundred running containers off it, the way one class spawns a hundred objects. Nothing in an image is executing; it's inert bytes until something instantiates it.

Build time and run time are different worlds, and the line between them is sacred. The image is frozen at build. Everything that varies between environments — the database URL, the Redis host, the secret keys, which region you're in — arrives at run time, injected from outside. This single boundary is the spine of the whole chapter. Most of twelve-factor is, at heart, rules enforcing exactly this separation: bake the code, inject the config.

A twelve-factor process is a near-pure function of (request, env, backing services). Give it the same request, the same environment variables, and the same database, and any copy produces the same answer. It holds nothing important in its own memory between requests. That property — and only that property — is what makes "kill one, start another, run five" safe. The container is the packaging; this statelessness is what makes the packaging worth having. And it sets up the final picture: an orchestrator is a control loop to which you declare "I want N healthy copies of image X reachable at one address," and which continuously reconciles reality toward that wish. Hold that; we open it in §4.


3. Theory & invariants​

A mental model tells you how to picture containers. Invariants tell you what stays true no matter which tool builds them.

🔑 The isolation invariant: same kernel, two knobs. A container is a process placed in fresh namespaces (what it can see) with cgroup limits (what it can use), running on a private root filesystem. Namespaces are the costume — the three you can actually feel are PID (its own process tree, so it thinks it's the only process, PID 1), mount (its own filesystem view), and network (its own interfaces and ports). A few more round it out — its own hostname (UTS), its own shared-memory channels between processes (IPC), and its own user-ID mapping — same idea, different resource. Cgroups are the leash — CPU shares, a hard memory cap, a pids limit, I/O throttling. Isolation is namespaces; resource control is cgroups. That's the entire trick. Everything Docker does is orchestration around these two kernel features you've already met.

A corollary you must internalize: the kernel is shared, always. A container cannot run a different kernel than its host. This is why "Linux containers on a Mac or Windows" silently spins up a hidden Linux VM — the Linux container needs a Linux kernel, and your laptop doesn't have one to share. It also bounds the security guarantee: container isolation is process-level, enforced by the host kernel, not VM-level enforced by a hypervisor. We pay for that in §8.

🔑 The image invariant: content-addressed, layered, immutable. An image is an ordered stack of layers, each an immutable filesystem diff identified by a cryptographic digest of its contents, plus a manifest tying them together. Because layers are content-addressed, two images that share a base layer share the bytes — the layer is stored and pulled once, deduplicated across every image that references it. Identical inputs produce an identical digest, which is the foundation of both caching and reproducibility.

🔑 The disposability invariant: the filesystem is ephemeral. At run time the kernel stacks the image's read-only layers under one thin writable layer (copy-on-write via an overlay filesystem). The container reads through the stack; the moment it writes, the file is copied up into that top layer. When the container is removed, the writable layer is deleted with it. Anything a container writes to its own filesystem is gone on restart. This is not a limitation to fight; it is the property that makes containers safe to throw away and recreate at will. Durable state goes elsewhere — a volume, a database, object storage — never the container's own disk. (In a clinical system this rule is non-negotiable: a chart note or a scanned document written to a container's local disk is a record you will lose.)

Now the application half. The twelve factors are not a checklist to tick; they are constraints that, taken together, make a process safely replicable. Learn them as principles:

  1. Codebase — one repo tracked in version control, many deploys from it.
  2. Dependencies — declared and isolated (package.json + lockfile); never assume anything is installed on the host.
  3. Config in the environment — the load-bearing one. Anything that varies between deploys lives in env vars, not in code.
  4. Backing services as attached resources — the DB, Redis, the queue, the immutable audit log are just URLs; swapping one for another is a config change, not a code change.
  5. Strict build / release / run separation — build makes the image, release combines it with config, run executes; you never edit code at run time.
  6. Stateless processes — no sticky session or cache state in process memory.
  7. Port binding — the app is self-contained and exports HTTP by binding a port itself; no webserver is injected around it.
  8. Concurrency via the process model — scale by running more processes (out), not a bigger one (up).
  9. Disposability — fast startup, graceful shutdown on SIGTERM.
  10. Dev/prod parity — keep environments as similar as possible (same Postgres major version locally as in prod).
  11. Logs as event streams — write to stdout; let the platform capture and route.
  12. Admin processes — run one-off tasks (migrations, scripts) as separate processes from the same image.

🔑 The invariant that fuses both halves. Only a process that is stateless (VI), reads its config from the environment (III), and is disposable (IX) can be safely replicated by an orchestrator. The Dockerfile gives you the package; factors III, VI, and IX are what make the package replicable. Every other factor is in service of these three. If you remember nothing else, remember which three are load-bearing — the rest fall out of them.

📎 Borrowed on credit: the orchestrator's reconciliation loop. We keep saying "an orchestrator runs N copies." The full machinery — schedulers, control planes, how Kubernetes reconciles desired against actual — is more than this chapter needs. We open it at intro depth in §4 so the words (Pod, Deployment, Service, probe) mean something, and we deliberately stop there.


4. Under the hood: images, the build cache, multi-stage, and a peek at orchestration​

Let's kill the magic by building things.

How a Dockerfile becomes layers​

Each instruction in a Dockerfile produces (mostly) one layer. FROM, COPY, ADD, and RUN create filesystem layers — they change what's on disk. ENV, EXPOSE, CMD, ENTRYPOINT, WORKDIR, and USER are metadata only: they change the image's configuration, not its filesystem, and add no new layer. You can see the whole stack with docker history <image> and the config with docker image inspect. Layers are just gzipped tarballs in the image store, named by digest.

Registries — where images live between build and run​

An image you build locally is useless to a server that can't see your laptop. A registry is the shared store images are pushed to and pulled from — Docker Hub, GitHub's GHCR, AWS ECR — addressed as registry/namespace/name:tag. Push and pull move only the layers the other side doesn't already have, because layers are content-addressed by digest (the §3 image invariant doing real work): a base layer shared by a hundred images transfers once. A registry is the handoff point between this chapter and the next two — CI pushes the SHA-tagged image here, and the cloud runtime pulls it from here. Treat it as part of your trust boundary: anyone who can pull reads every layer (including any secret you leaked into one), so registries need authn/authz and, for tamper-resistance, image signing.

The build cache — the thing that decides if your builds are fast or agonizing​

The builder hashes each instruction together with its inputs. On a rebuild, if the hash matches a previous build, it reuses that layer and every layer before it for free. The first instruction whose hash changes is a cache miss, and a miss invalidates that layer and everything after it. This one rule dictates Dockerfile order:

copy package.json + lockfile ──▶ install deps ──▶ copy source ──▶ build
(changes rarely) (changes constantly)

If you COPY . . before npm ci, then editing a single line of source changes the copied layer, busts the cache, and re-runs the entire install — minutes, every build. Copy the manifest and lockfile first, install, then copy source. Now a source edit only invalidates the cheap tail. BuildKit (Docker's modern builder) adds parallelism, --mount=type=cache to persist the npm/.cache directory across builds, and --mount=type=secret so a build-time token is available to a RUN step without ever landing in a layer.

CMD vs ENTRYPOINT, and the signal trap that drops requests​

How you write the start command decides whether your app can shut down gracefully. Shell form (CMD node dist/server.js) runs your command under /bin/sh -c, so the shell is PID 1 and your Node process is its child. When the container is stopped, SIGTERM goes to PID 1 — the shell — and is not forwarded to Node. Your graceful-shutdown handler never fires. Exec form (CMD ["node", "dist/server.js"]) makes Node itself PID 1, so it receives SIGTERM directly. Always use exec form for the start command.

There's a PID-1 caveat. When a child process exits, the OS keeps a tiny record of it until its parent formally acknowledges the death — an unacknowledged record is a zombie. PID 1 is expected to do that acknowledging for any orphaned process; a bare Node process doesn't, so zombies pile up (and it can mishandle some signal defaults too). tini (or Docker's --init) is a one-file program that sits at PID 1 and does exactly this bookkeeping — reaping zombies and forwarding SIGTERM down to Node. Add it if your app forks child processes. This is the operational payoff of the graceful-shutdown work you did earlier — the handler you wrote only runs if the signal actually reaches your process, and that depends entirely on getting PID 1 right.

ENTRYPOINT versus CMD is a related distinction worth one sentence: ENTRYPOINT sets the fixed executable and CMD sets default arguments a caller can override, so ENTRYPOINT ["node"] + CMD ["dist/server.js"] lets docker run img dist/worker.js reuse the same image for a worker. Use that split when one image runs multiple roles; otherwise a single exec-form CMD is plenty.

The multi-stage build — the core Node/TS technique​

A naïve Dockerfile uses one stage: it installs every dependency including the TypeScript compiler, compiles, and ships the result — toolchain, dev deps, source, and all. That's a 1+ GB image carrying a compiler into production. The fix is multi-stage: a builder stage with the full toolchain produces dist/, and a lean runner stage copies only the built artifact and production dependencies from it. Here is Pulsely's production Dockerfile:

# syntax=docker/dockerfile:1

# ---- Stage 1: builder — full toolchain, compiles TS to dist/ ----
FROM node:20.14-slim AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci # all deps, incl. devDependencies (tsc)
COPY tsconfig.json ./
COPY src ./src
RUN npm run build # tsc → dist/

# Production-only deps, computed in isolation so dev deps can't leak forward
RUN npm ci --omit=dev

# ---- Stage 2: runner — slim, non-root, artifact only ----
FROM node:20.14-slim AS runner
ENV NODE_ENV=production
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules # prod deps only
COPY --from=builder /app/dist ./dist # compiled JS only
USER node # non-root, fixed uid
EXPOSE 3000
CMD ["node", "dist/server.js"] # exec form → Node is PID 1

The runner has no compiler, no tsconfig, no TypeScript source, no dev dependencies, and runs as the unprivileged node user. The unit you carry forward across stages is the built artifact, not the build tools.

A Node-specific landmine lives in the base image. Some npm packages aren't pure JavaScript — packages like sharp (the report/thumbnail renderer from §1), bcrypt, and pg-native ship native C/C++ code that gets compiled against whatever standard C library the OS provides. Debian-based images (slim) ship one implementation, glibc; Alpine ships a different, smaller one, musl. A binary compiled against glibc goes looking for glibc at runtime; drop it into an Alpine image and it can't find the functions it expects and crashes (a segfault). This is the single most common "works in slim, crashes in alpine" bug. So compile native modules inside the same base image you'll run them in, and prefer -slim (glibc) over Alpine when you depend on them. Always use npm ci (installs exactly the lockfile, fails on drift) rather than npm install (may resolve newer versions) — reproducibility depends on it.

🏭 The JVM teaches the same lesson with a different boundary. A Spring Boot fat-jar is already a self-contained artifact, so its build stage is mvn package and its runtime stage is just a JRE plus the jar — multi-stage in the same shape, but the unit copied forward is one jar instead of dist/ + node_modules. The principle transfers exactly: carry the artifact, drop the toolchain. (Modern JDKs even read cgroup memory limits to size the heap — the JVM analog of Node's --max-old-space-size, which §8 returns to.)

Logs as streams​

Factor XI in mechanics: write to stdout and stderr, and let the runtime capture them. Do not open and rotate log files inside the container — the writable layer is ephemeral, and the platform (Docker's json-file driver, or an orchestrator's log pipeline) already collects stdout. The structured JSON logger you built earlier composes perfectly: emit one JSON object per line to stdout and the platform ships it where it needs to go. (One clinical caveat: application logs are not the HIPAA audit trail — never let PHI leak into stdout logs; the immutable "who viewed which chart" audit log is a separate, first-class backing service.)

Compose under the hood​

docker-compose.yml declares a set of services on a shared user-defined bridge network. On that network, service names are DNS names — the API reaches Postgres at host db, not localhost. This trips up everyone once: inside a container, localhost is that container, so localhost:5432 finds nothing. depends_on controls start order but does not wait for a service to be ready — Postgres accepting connections lags its container starting — so you need a healthcheck with condition: service_healthy. Named volumes persist data across down/up; without one, your Postgres data lives on the ephemeral writable layer and vanishes.

Orchestration at intro depth — what Kubernetes actually solves​

Compose runs containers on one host. The moment you need many hosts, self-healing, and zero-downtime rollouts, you reach for an orchestrator, and Kubernetes is the lingua franca. Four nouns carry the intro:

Deployment (desired state: "keep N replicas of this Pod template")
│ reconciles ──▶ creates / replaces
▼
┌──── Pod ────┐ ┌──── Pod ────┐ ┌──── Pod ────┐ Pods are mortal,
│ pulsely-api │ │ pulsely-api │ │ pulsely-api │ re-created and re-IP'd
└─────────────┘ └─────────────┘ └─────────────┘
▲ ▲ ▲
└──────── Service (stable virtual IP + DNS) ───────┘
load-balances over the *healthy* Pods
  • Pod — one or more co-located containers sharing a network namespace; the smallest schedulable unit. Usually that's your one container, occasionally plus a sidecar.
  • Deployment — a controller holding the desired state: "keep N replicas of this Pod template alive, roll updates gradually, let me roll back." The reconciliation loop from §2, made concrete.
  • Service — a stable virtual IP and DNS name that load-balances across the currently healthy Pods. Pods die and get new IPs; the Service does not move. This is how callers find a moving target.
  • Probes — the orchestrator continuously asks each Pod how it's doing. Liveness: "are you hung? if so I restart you." Readiness: "are you ready for traffic? if not I remove you from the Service's load-balancer." Startup: "are you a slow booter? don't kill you prematurely."

These map straight back to disposability (factor IX): readiness flipping to not-ready during shutdown is what drains traffic off a Pod before it dies, and a graceful SIGTERM handler is what lets it finish in-flight work. A rolling update is this loop in motion — the Deployment brings up a new-image Pod, waits for its readiness probe to pass, drains and removes an old one, and repeats, so capacity never dips and no request lands on a Pod that isn't ready. The orchestrator is just the §2 reconciliation loop with a vocabulary; everything else it does is variations on "keep desired and actual in sync."

📎 Borrowed on credit: running containers in the cloud. Where these containers actually run on managed infrastructure — ECS, Fargate, the AWS networking around them, and the HIPAA-eligible services under a BAA that a PHI workload demands — is Chapter 37. How CI builds and pushes the image and rolls it out (build pipelines, blue-green, canary) is Chapter 38. Here we build the artifact and run it locally; the next two chapters take it to production.

🛑 What we deliberately did not explain. We took Kubernetes only as far as its vocabulary — Pods, Services, Deployments, probes, the reconciliation loop — because that's the layer you reason about when you deploy. We did not open the scheduler internals, the networking model (CNI plugins, Ingress controllers), StatefulSets, operators, or service meshes. For most backend engineers a managed runtime (Chapter 37) hides nearly all of it; reach for deep Kubernetes only when you operate the platform itself rather than ship onto it.


5. In production: the Dockerfile checklist tutorials skip, and graceful shutdown for real​

The Dockerfile in §4 is production-shaped, but production demands a few more disciplines.

The .dockerignore is not optional. The build context — everything sent to the builder — must exclude node_modules (wrong arch, huge), .git (history bloat), .env (you will bake secrets in if you don't — and in a HIPAA system those secrets guard PHI), tests, and any local dist. Without it your context balloons, builds slow, and secrets leak into layers:

node_modules
.git
.env
.env.*
dist
**/*.test.ts
coverage

Pin the base image. Use node:20.14-slim, never node:latest — latest is a moving pointer, so "the same Dockerfile built twice" yields different images and "reproducible build" becomes a lie. For maximum rigor, pin by digest. Commit the lockfile. Pin any apt-geted package version that matters.

Tag images with the git SHA. The SHA tag is immutable and ties a running image back to the exact commit CI tested; latest and per-environment tags are moving pointers to SHA tags. Never re-push different bytes to an existing SHA tag — a deploy must be byte-identical to what was tested.

Run as non-root, harden the rest. USER node (a fixed uid), chown only what the process must write, drop Linux capabilities, and run a read-only root filesystem where you can. Set ENV NODE_ENV=production explicitly. EXPOSE documents the port (it doesn't publish it).

Graceful shutdown — factor IX made real. This is where the chapter touches patients directly. When an orchestrator stops a container (a deploy, a scale-down), it sends SIGTERM, waits a grace period, then SIGKILLs whatever's left. Your job in that window: stop accepting new connections, flip readiness to not-ready so the load balancer drains you, finish in-flight requests, close the DB and Redis pools, and exit — all before the grace period expires.

// server.ts — graceful shutdown wired to the container lifecycle.
let ready = true;
app.get('/healthz', (_req, res) => res.sendStatus(200)); // liveness: process up
app.get('/readyz', (_req, res) => // readiness: deps + draining
ready && db.isConnected() ? res.sendStatus(200) : res.sendStatus(503),
);

const server = app.listen(Number(config.PORT));

async function shutdown(signal: string) {
logger.info({ signal }, 'shutting down');
ready = false; // 1. fail readiness → orchestrator drains traffic
server.close(async () => { // 2. stop accepting, let in-flight finish
await Promise.allSettled([pgPool.end(), redis.quit()]); // 3. close pools
process.exit(0);
});
setTimeout(() => process.exit(1), 8_000).unref(); // 4. deadline < orchestrator grace period
}
process.on('SIGTERM', () => shutdown('SIGTERM')); // works only because CMD is exec-form

Without this, every deploy of Pulsely drops live requests — an encounter note lost mid-save, or a claim submission cut off mid-flight. In a clinical system a dropped write isn't a nuisance: it can be a lost chart entry or a claim that silently never reached the clearinghouse. The shutdown deadline (8 s) must be shorter than the orchestrator's grace period (often 30 s) so you exit cleanly on your own terms rather than being killed.

Health endpoints, two of them. /healthz answers "is the process alive?" (liveness — restart if not). /readyz answers "can I serve traffic right now?" — it checks the DB and Redis are reachable, and it flips to not-ready during shutdown so traffic drains. Wire both into Compose and document the K8s probe mapping; conflating the two is a classic cause of restart loops (a readiness blip triggering a liveness restart).

Local dev with Compose. One docker compose up should bring the whole stack to life. Here's Pulsely's:

services:
api:
build: { context: ., target: runner }
environment:
DATABASE_URL: postgres://pulsely:pulsely@db:5432/pulsely # service name 'db', not localhost
REDIS_URL: redis://cache:6379
PORT: "3000"
ports: ["3000:3000"]
depends_on:
db: { condition: service_healthy } # wait for readiness, not just start
cache: { condition: service_healthy }
db:
image: postgres:16 # same MAJOR as prod (factor X parity)
environment: { POSTGRES_USER: pulsely, POSTGRES_PASSWORD: pulsely, POSTGRES_DB: pulsely }
volumes: ["pgdata:/var/lib/postgresql/data"] # named volume → data survives down/up
healthcheck:
test: ["CMD-SHELL", "pg_isready -U pulsely"]
interval: 5s
timeout: 3s
retries: 5
cache:
image: redis:7
healthcheck: { test: ["CMD", "redis-cli", "ping"], interval: 5s, timeout: 3s, retries: 5 }
volumes:
pgdata:

This is the Appendix-A lab, finally explained: the API binds a port (factor VII), reaches Postgres and Redis as attached resources by service-name DNS (factor IV), and config arrives entirely through env (factor III). The same shape holds for the services this stack will grow — the immutable HIPAA audit log, the object store for scanned documents, the eligibility and clearinghouse partners — each an attached resource reached by URL, swappable by config. For hot reload in dev, a docker-compose.override.yml (Compose merges it automatically) adds a bind-mount of ./src and runs tsx watch instead of the built image — keeping dev-only mounts out of the production image build so the thing you run in dev and the thing you ship stay structurally the same. Dev/prod parity (factor X) means running the same Postgres major version locally that prod runs; a minor-version or, worse, a "SQLite in dev, Postgres in prod" gap is exactly where the bugs no test caught come from.

Migrations are factor XII — admin processes — in practice: run them as a one-off process from the same image (docker compose run --rm api npm run migrate), not as a step baked into the API's startup. Coupling migrations to app boot means N replicas race to migrate, and a bad migration takes the whole service down with it — on a live chart table that means clinicians locked out of records mid-visit. A separate one-off process keeps schema change decoupled from serving traffic. (The full deploy-time choreography — expand/contract, migrating a live PHI/chart table with zero downtime — is Chapter 38.)

Image-size discipline. Measure with docker images and audit layers with dive. The wins compound: multi-stage, a slim base, npm ci --omit=dev, no build caches in the final layer, chained RUNs that clean their own apt lists in the same layer (a separate cleanup RUN can't shrink a prior layer — layers are immutable diffs).


6. Common pitfalls​

Bloated image. Signature: a 1.2 GB image — full node:20 base, dev deps, TS toolchain, and source all baked in. Fix: multi-stage build, slim or distroless runtime, npm ci --omit=dev; carry only dist/ forward.

Cache never hits. Signature: every build re-runs npm ci, even for a one-line source edit. Fix: COPY the manifest and lockfile and install before copying source; the dependency layer then stays cached until dependencies actually change.

node_modules copied from host. Signature: native deps segfault or report the wrong architecture. Fix: .dockerignore node_modules and always install inside the image for the target platform.

SIGTERM ignored; deploys drop requests. Signature: every deploy 500s some requests, or containers take the full grace period to die. Fix: exec-form CMD so your process is PID 1, a SIGTERM handler that drains, and --init/tini if you fork children. (This is §5's handler being defeated by §4's shell-form trap.)

Secret leaked into the image. Signature: a token shows up in docker history — baked via ENV SECRET= or --build-arg, or a .env copied in. Build-args and env persist in image history, readable by anyone who can pull. Fix: BuildKit --mount=type=secret for build-time tokens, runtime injection for everything else, and .dockerignore the env file.

Container can't reach the database. Signature: connection refused on localhost:5432. Fix: connect to the service name (db:5432); inside a container localhost is the container itself.

App writes to local disk and loses it on restart. Signature: uploaded scanned documents or cache land on the writable layer and vanish. Fix: the filesystem is ephemeral (§3) — externalize state to a volume, object storage, or Redis (factor VI).

depends_on doesn't wait. Signature: the API crash-loops on boot, racing a Postgres that isn't accepting connections yet. Fix: condition: service_healthy plus a real healthcheck, and retry-on-connect in the app — readiness ordering is best-effort, not a guarantee.

Runs as root. Signature: no USER line; a container escape lands the attacker near host root — and on a host handling PHI, near the records. Fix: non-root USER, dropped capabilities, read-only rootfs.

In-process session or cache state. Signature: a clinician's login works about half the time behind a load balancer — whichever replica holds their session answers, the others don't. Fix: move sessions to Redis or a JWT; make the process stateless (factor VI). This is the pitfall that proves the whole point: the container was fine; the app wasn't replicable.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying where you stand.

Containers vs VMs. Containers give density, fast boot, and a shared kernel; VMs give stronger isolation — their own kernel — at the cost of weight. You stay on containers for your own trusted services. You reverse toward VMs or microVMs (Firecracker, gVisor) when you run untrusted code (a multi-tenant platform executing customers' code) or face hard compliance boundaries, because then the weaker, shared-kernel isolation is a real risk.

Base image: distroless vs alpine vs slim. Distroless is smallest and has the least attack surface, but ships no shell and no package manager — debugging is harder. Alpine is tiny but uses musl libc, which bites native modules. Slim (Debian) is larger but brings glibc and apt and the fewest surprises. Default for a Node service with native deps: -slim, graduating to distroless once the image is stable and you've solved debugging. You'd reverse toward distroless the moment attack surface matters more than shell access — which, for a PHI workload, comes sooner than for a hobby app.

Config: env vars vs mounted files vs secrets manager. Env vars are the simplest and the twelve-factor canon, but they're flat strings, visible in /proc, and awkward for large or structured config. Mounted files suit structured or rotated config. A secrets manager is best for rotation and audit but adds infrastructure. The ADR below picks env as the default and names the exceptions.

Build-time vs run-time config. Baking config into the image means fewer moving parts but one image per environment — which breaks build/release/run separation (factor V) and dev/prod parity (factor X). Run-time config means one image everywhere, which is the whole point. You bake only truly build-invariant facts (the Node version, the app's own code). Everything environmental is injected.

Compose vs Kubernetes. Compose is ideal for local dev and single-host setups; it is not a production HA scheduler — it has no notion of multi-host scheduling, self-healing, or rolling deploys. Don't reach for Kubernetes until you genuinely need those; its operational cost is real and frequently underestimated. The decision tree: single host and a human watching → Compose; many hosts that must self-heal → an orchestrator.

One process per container vs sidecars. Single-responsibility containers compose and scale more cleanly; the exception is a sidecar (a log shipper, a proxy) co-located in the same Pod for a tightly-coupled concern. Introduce sidecars sparingly and only when the coupling is genuine.

🚫 A framing this book rejects. "A container is a lightweight VM." It's a tempting one-liner and it's wrong in the way that matters: it hides the shared kernel, which is the entire source of both the speed (no guest OS to boot) and the weaker isolation (an escape is a kernel exploit, not a hypervisor one). Engineers who carry the "tiny VM" model are blindsided when they try to run a different kernel, when a root container turns out to be near-root on the host, or when a cgroup OOM-kills a process they thought had its "own" RAM. Picture a process the kernel lied to, and all three surprise you exactly never.


8. Security & scale notes​

Root in a container is close to root on the host. Because the kernel is shared, a container escape is a kernel vulnerability, not a hypervisor one — so the host kernel is part of your attack surface, and patching it is security work. On a host running PHI workloads, that host kernel is part of the boundary protecting protected health information, so patching it is compliance work, not just hygiene. Shrink the blast radius the same way every time: non-root USER, dropped capabilities, read-only root filesystem, no-new-privileges. These are cheap and they compound.

Your image is a supply chain. Every base image and every transitive npm dependency is attack surface baked into your artifact. Scan images and lockfiles in CI (Trivy, Grype), pin and digest-lock bases, prefer minimal images (fewer packages, fewer CVEs to triage), and generate an SBOM so you can answer "are we affected by this CVE?" in minutes. This is the direct, physical form of the supply-chain concerns you've already met: the container is where those dependencies ship — and in a clinical system, a CVE in a base image is baked into the artifact that touches every chart, so "are we affected?" is a question you must answer in minutes, not days.

Secrets never live in the image. Image layers, image history, and the registry are readable by anyone who can pull. So a secret in ENV, in a --build-arg, or in a copied .env is a published secret. In a HIPAA system those secrets guard PHI — the database password, the clearinghouse API key, the PHI-store credential — so a leaked layer is a direct path to protected records, exactly the kind of exposure that becomes a reportable breach. Inject at run time via orchestrator secrets or mounted files; use BuildKit secret mounts for build-time tokens. On AWS that run-time injection lands only on HIPAA-eligible services under a signed BAA (Business Associate Agreement) — secrets in Secrets Manager, PHI in S3 with server-side encryption, the whole workload in private subnets so no chart data ever sits on a publicly routable network. Lock down the registry with authn/authz, and sign images (cosign) so a tampered image can't be silently substituted. This is the ADR's hard line.

Statelessness is the scale lever. A Service can fan traffic across N Pods only because any Pod can answer any request (factor VI). The instant you keep per-user state — a clinician's session, a cached chart — in process memory, you're capped at one replica, and you'll discover it as the intermittent-login bug from §6, under load, in production. Statelessness isn't tidiness; it's the precondition for horizontal scale.

cgroup limits bite at run time, and they bite differently. A memory limit is hard: exceed the cgroup cap and the kernel OOM-kills your container — you'll see exit code 137 and a container that "just restarts" mysteriously. The fix takes one insight: Node's JS heap is only part of what the process uses. Buffers, native modules like sharp, and the runtime itself all allocate memory outside that heap. So if you let V8 grow its heap right up to the container's memory cap, the extra non-heap memory pushes you over the edge and the kernel kills the container. Set --max-old-space-size a few hundred MB below the cap, so V8 garbage-collects and frees memory before the kernel steps in. (The frontend analogy: like a browser tab that gets killed for exceeding a memory budget that included far more than just your objects.) A CPU limit throttles rather than kills: under CPU pressure the event loop gets less time, so event-loop latency rises and tail latency degrades — the performance failure mode you've seen before, now triggered by a cgroup rather than a busy handler.

Disposability decides whether scaling is graceful. Fast boot plus graceful drain make autoscaling and rolling deploys invisible to users. Slow boot or ignored SIGTERM turns every scale event into dropped requests. Readiness probes are the backpressure that keeps traffic off a not-yet-warm replica until it's ready — the same shape as the saturation reasoning you've already seen, now operationalized by the orchestrator.

Density trades utilization against blast radius. Packing many containers per host raises utilization, but a noisy or compromised neighbor shares your kernel. Resource limits (so one container can't starve the rest) plus isolation hardening (so a compromise is contained) bound the damage. There is no free lunch — only a knob between cost and isolation, which §7 already named as containers-vs-VMs at the extreme.


9. Interview lens & exercises​

Interview questions​

"How is a container different from a VM?" Junior answer: "It's lightweight." Correct and empty. Senior answer: "Namespaces decide what it sees, cgroups decide what it uses, and it shares the host kernel — so it's process-level isolation, not a guest OS. That's why it boots in milliseconds and packs densely, and also why the isolation is weaker: an escape is a kernel exploit. For untrusted multi-tenant code I'd reach for a microVM instead, trading density for a real isolation boundary."

"Walk me through a production Node Dockerfile and why each line is ordered that way." Junior: lists FROM/COPY/RUN top to bottom. Senior: narrates the reasons — manifest and lockfile copied before source so a code edit doesn't bust the install cache; multi-stage to leave the compiler and dev deps behind; npm ci --omit=dev for a reproducible prod-only install; non-root USER; exec-form CMD so Node is PID 1 and receives SIGTERM; .dockerignore to keep the context lean and secrets out; -slim over Alpine because of musl-vs-glibc on native deps.

"What does 'config in the environment' buy you, and where does it break down?" Junior: "Use env vars." Senior: "One image promoted unchanged across every environment, which is build/release/run separation in practice. It breaks down for large or structured config and for secret rotation — there I move to mounted files or a secrets manager — and env is visible in /proc and in image history if you bake it, so secrets never go in via ENV or build-args."

"What does Kubernetes actually solve that Compose doesn't — in three nouns?" Junior: "It orchestrates things." Senior: "Deployment: declarative desired-replica reconciliation with rolling updates and rollback. Service: a stable address load-balancing over mortal, re-IP'd Pods. Probes: self-healing and traffic draining. The throughline is multi-host scheduling and self-healing, which Compose has no concept of."

"Your service drops requests on every deploy. Diagnose." Junior: "Add retries." Senior: "It's the disposability path. Either SIGTERM isn't reaching the process — shell-form CMD so the shell is PID 1 — or there's no graceful-shutdown handler, or readiness doesn't flip to not-ready during shutdown so the load balancer keeps sending traffic into a dying Pod, or the shutdown deadline is longer than the orchestrator's grace period so it gets SIGKILLed mid-request. Each maps to factor IX and a probe."

Exercises & the Pulsely increment​

  1. Build the Pulsely container, for real. Write the production multi-stage Dockerfile (builder + slim non-root runner, npm ci --omit=dev, exec-form CMD), the .dockerignore, and the docker-compose.yml wiring API → Postgres → Redis with healthchecks and seeded dev data. docker compose up must boot the whole stack from cold.

  2. Cache & size audit. Measure the image size and rebuild time, then reorder layers and add multi-stage to cut both. Record before/after with docker history and dive, and prove that a source-only edit no longer re-runs npm ci.

  3. Graceful shutdown + probes. Add a SIGTERM handler that drains in-flight requests and flips /readyz to not-ready, wire the Compose healthchecks, and demonstrate a rolling restart that drops zero requests under a small load generator (imagine each request is an encounter note being saved). Then break it on purpose — switch CMD to shell form — and watch the requests drop, so you feel why exec form matters.

  4. Config/secret refactor + the ADR. Move all Pulsely config to env vars validated against a schema at boot (fail fast on a missing DATABASE_URL — the startup-validation pattern you built earlier). Inject a fake PHI-store secret via a runtime mount and prove it is absent from docker history. Then write the Container/runtime config-strategy ADR.

ADR-036 — Container & runtime config strategy. Context: Pulsely must run as one immutable image across dev, staging, and prod under HIPAA; config and secrets vary per environment and must not leak, because a leaked credential here is a path to PHI. Decision: (1) One image per commit, tagged by git SHA; environment tags are moving pointers. (2) All config via env vars (factor III), validated against a schema at boot. (3) Secrets are never in the image — injected at run time via orchestrator secrets or mounted files; build-time tokens use BuildKit --mount=type=secret; ENV and --build-arg for secrets are banned because they persist in image history. (4) Base image node:20.14-slim, pinned (digest in prod), chosen over Alpine for glibc/native-dep compatibility and over distroless for debuggability until the image stabilizes. (5) Exception: large or structured config and rotated secrets move to mounted files / a secrets manager. Consequences: one tested artifact promoted unchanged; reproducible builds; secrets auditable and rotatable independently of deploys. Cost: env is flat and visible in /proc, so structured config needs the file/secrets-manager path. Reverse when: untrusted-tenant isolation is required (→ microVM base) or config grows beyond what flat env can express (→ secrets manager as default).


Key takeaways​

  • A container is a process the kernel lied to — namespaces decide what it sees, cgroups decide what it uses, and it shares the host kernel. Not a VM. This is the payoff of the process model you already understand.
  • An image is an immutable, content-addressed, layered tarball (the class); a container is a running instance (the object) with one ephemeral writable layer on top — so the container's own filesystem is disposable.
  • The build cache rule — a miss invalidates everything after it — dictates Dockerfile order: copy manifest + lockfile and install before copying source. Multi-stage carries the artifact forward and leaves the toolchain behind.
  • Exec-form CMD makes your process PID 1 so it receives SIGTERM — without it, the graceful-shutdown handler you wrote never runs and every deploy drops requests (a lost chart note, a dropped claim).
  • Twelve-factor makes a process replicable; the three load-bearing factors are config-in-env (III), stateless (VI), and disposable (IX). Only a process that is all three can be safely run in many copies by an orchestrator.
  • Compose is local-dev DNS-by-service-name with healthchecks; Kubernetes at intro depth is Deployment (desired replicas), Service (stable address over mortal Pods), and probes (self-healing + drain).
  • Secrets never live in image layers or history — in a HIPAA system they guard PHI; cgroup memory limits OOM-kill (size Node's heap under them), CPU limits throttle and raise tail latency.

← Previous: Ch 35 — Testing & Quality Strategy · Up: Part VII overview · Master TOC · Next: Ch 37 — Cloud & AWS for Backend Engineers →