Polski

Tutorial · Docker · Node.js

Docker for developers – multi-stage Node/NestJS and React images, layer caching, docker compose and image scanning

From a Dockerfile that "works" to a production-ready image. We build a NestJS API image and a React frontend (nginx), organise layers and caching, run containers as an ordinary user with a healthcheck, set up a development environment with docker compose (PostgreSQL 18, Redis 8, hot reload) and scan images with Trivy in CI – with real image sizes and build times.

By · · 19 min read

The first Dockerfile in a project usually looks the same: FROM node, COPY . ., npm install, npm start. It works – and that is where its virtues end. The image weighs 1.7 GB, every one-line code change reinstalls all dependencies, the process runs as root, and docker stop waits 10 seconds before killing the container. In this tutorial you will rework such a Dockerfile step by step, build images for an API (NestJS) and a frontend (React + nginx), set up a local environment with a database and cache in docker compose, and add vulnerability scanning to CI. The image sizes and build times in this article were measured on real builds.

Prerequisites: Docker Desktop or Docker Engine with Compose v2, Node.js 24 LTS, NestJS and React basics. Node.js under the hood helps – it explains signals and process memory.

418 → 65 MB
API image (compressed) – naive vs multi-stage
1.7 GB → 268 MB
API image on disk – the same, unpacked
23 MB
frontend image – nginx + static files, no Node.js
1.4 s
rebuild without changes – BuildKit layer cache

Image, container, layers

Diagram: From a Dockerfile to a running container
  • An image is a stack of filesystem layers (each one a diff on top of the previous) plus metadata: which command to run, as which user, with which variables. Images are immutable and identified by a digest (sha256:…).
  • A container is an ordinary Linux process isolated by namespaces and limited by cgroups, with a thin writable layer on top of the image. When the container is removed, that layer is gone – data lives in volumes.
  • The layer cache: while building, Docker checks whether an instruction and its inputs (e.g. copied files) have changed. The first changed layer and everything after it is rebuilt. That is why instruction order determines build times.

Step 1. The application and the starting point

We containerize a small API: GET /api/live (is the process alive), GET /api/health (are the database and Redis working) and GET /api/menu (cache-aside: Redis first, PostgreSQL on a miss). Configuration comes only from environment variables, so the same image runs locally, in CI and in production.

API code

api/src/app.controller.ts
import { Controller, Get, Inject, ServiceUnavailableException } from "@nestjs/common";
import type { Redis } from "ioredis";
import type pg from "pg";
import { PG, REDIS } from "./infra.js";

type MenuItem = { id: string; name: string; price_cents: number };

@Controller()
export class AppController {
  constructor(
    @Inject(PG) private readonly db: pg.Pool,
    @Inject(REDIS) private readonly cache: Redis,
  ) {}

  // Liveness: "is the process alive?" – deliberately WITHOUT database checks,
  // otherwise a database outage would make Kubernetes restart every API pod.
  @Get("live")
  live() {
    return { status: "ok" };
  }

  // Readiness: "can I serve traffic?" – used by the Dockerfile HEALTHCHECK, compose and Kubernetes.
  @Get("health")
  async health() {
    const [db, cache] = await Promise.allSettled([this.db.query("SELECT 1"), this.cache.ping()]);
    const status = { db: db.status === "fulfilled" ? "up" : "down", cache: cache.status === "fulfilled" ? "up" : "down" };
    if (status.db === "down" || status.cache === "down") throw new ServiceUnavailableException(status);
    return { status: "ok", ...status, uptimeSec: Math.round(process.uptime()) };
  }

  // Cache-aside: Redis first, PostgreSQL on a miss, then store for 30 s.
  @Get("menu")
  async menu() {
    const cached = await this.cache.get("menu:v1");
    if (cached) return { source: "cache", items: JSON.parse(cached) as MenuItem[] };
    const { rows } = await this.db.query<MenuItem>("SELECT id, name, price_cents FROM menu ORDER BY name");
    await this.cache.set("menu:v1", JSON.stringify(rows), "EX", 30);
    return { source: "database", items: rows };
  }
}
api/src/infra.ts
import { Inject, Injectable, type OnApplicationShutdown } from "@nestjs/common";
import { Redis } from "ioredis";
import pg from "pg";

export const PG = Symbol("PG");
export const REDIS = Symbol("REDIS");

// Connection settings come from the environment – the same image runs in dev, CI and production.
export const infraProviders = [
  { provide: PG, useFactory: () => new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 }) },
  { provide: REDIS, useFactory: () => new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", { lazyConnect: false, maxRetriesPerRequest: 2 }) },
];

// Close connections on SIGTERM (docker stop, Kubernetes rolling update).
@Injectable()
export class InfraShutdown implements OnApplicationShutdown {
  constructor(
    @Inject(PG) private readonly pool: pg.Pool,
    @Inject(REDIS) private readonly redis: Redis,
  ) {}

  async onApplicationShutdown(signal?: string) {
    console.log(`shutting down (${signal ?? "no signal"}) – closing connections`);
    await Promise.allSettled([this.pool.end(), this.redis.quit()]);
  }
}
api/src/main.ts
import "reflect-metadata";
import { Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppController } from "./app.controller.js";
import { InfraShutdown, infraProviders } from "./infra.js";

@Module({ controllers: [AppController], providers: [...infraProviders, InfraShutdown] })
class AppModule {}

const app = await NestFactory.create(AppModule);
app.setGlobalPrefix("api");
app.enableShutdownHooks(); // react to SIGTERM/SIGINT: finish requests, close connections
await app.listen(Number(process.env.PORT ?? 3000), "0.0.0.0");
console.log(`pierogi-api listening on :${process.env.PORT ?? 3000}`);
api/package.json
{
  "name": "pierogi-api",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "engines": {
    "node": ">=24"
  },
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "dev": "tsc -p tsconfig.json && (tsc -p tsconfig.json --watch --preserveWatchOutput > /dev/null & node --watch dist/main.js)",
    "start": "node dist/main.js"
  },
  "dependencies": {
    "@nestjs/common": "^12.6.3",
    "@nestjs/core": "^12.6.3",
    "@nestjs/platform-express": "^12.6.3",
    "ioredis": "^6.1.0",
    "pg": "^8.23.1",
    "reflect-metadata": "^0.2.2",
    "rxjs": "^7.8.2"
  },
  "devDependencies": {
    "@types/express": "^5.0.6",
    "@types/node": "^24.19.4",
    "@types/pg": "^8.23.1",
    "typescript": "~6.0.3"
  }
}
api/tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": ["node"],
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "sourceMap": false
  },
  "include": ["src"]
}

And this is the Dockerfile many projects start with:

Starting point: a naive Dockerfile

api/Dockerfile.naive
# "Before": the Dockerfile many projects start with. Works – and that is its only virtue.
FROM node:24
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
EXPOSE 3000
CMD npm start

What is wrong with it? node:24 is a full Debian with compilers (over 1 GB), COPY . . before npm install invalidates the dependency cache on every code change, the image keeps devDependencies, TypeScript sources and everything that was lying around in the directory (including .env), the process runs as root, and the shell form CMD npm start starts the app through sh and npm – extra processes in the signal path, so whether SIGTERM reaches Node depends on the shell and the npm version.

Step 2. A multi-stage Dockerfile for NestJS

API Dockerfile and .dockerignore

api/Dockerfile
# syntax=docker/dockerfile:1
ARG NODE_VERSION=24

# --- dependencies (cached as long as package*.json does not change) ---
FROM node:${NODE_VERSION}-alpine AS deps
WORKDIR /app
# npm ci installs exactly what package-lock.json says (commit the lock file!)
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

# --- development: used by docker compose (source synced by "develop.watch") ---
FROM deps AS dev
COPY tsconfig.json ./
COPY src ./src
CMD ["npm", "run", "dev"]

# --- build: compile TypeScript, then drop devDependencies ---
FROM deps AS build
COPY tsconfig.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev

# --- runtime: only what is needed to run, as a non-root user ---
FROM node:${NODE_VERSION}-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/package.json ./
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
USER node
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
# exec form: node is PID 1 and receives SIGTERM directly (use `docker run --init` / tini for zombie reaping)
CMD ["node", "dist/main.js"]
api/.dockerignore
# Keep the build context small and secrets out of the image.
node_modules
dist
coverage
.git
.github
.env*
*.log
*.md
Dockerfile*
.dockerignore
compose*.yaml

Stage by stage:

  1. deps copies only package.json and package-lock.json, then runs npm ci. This layer is rebuilt only when dependencies change. --mount=type=cache,target=/root/.npm keeps the npm cache between builds outside the image – even when dependencies change you only download what is missing.
  2. dev – the image for docker compose: sources and npm run dev (compiler in watch mode + node --watch).
  3. build compiles TypeScript and removes devDependencies (npm prune --omit=dev).
  4. runtime starts from a clean node:24-alpine and copies only package.json, production node_modules and dist. The files belong to the node user (--chown), the process runs as node (UID 1000), and HEALTHCHECK polls /api/health.
Rebuild after changing one file in src/ (docker build --progress=plain, selected lines)
#8 [deps 4/4] RUN --mount=type=cache,target=/root/.npm npm ci
#8 CACHED
#9 [deps 3/4] COPY package.json package-lock.json ./
#9 CACHED
#11 [build 1/3] COPY tsconfig.json ./
#11 CACHED
#12 [build 2/3] COPY src ./src
#13 [build 3/3] RUN npm run build && npm prune --omit=dev
#14 [runtime 3/5] COPY --from=build --chown=node:node /app/package.json ./
#14 CACHED
#15 [runtime 4/5] COPY --from=build --chown=node:node /app/node_modules ./node_modules
#15 CACHED
#16 [runtime 5/5] COPY --from=build --chown=node:node /app/dist ./dist

Notice #15 CACHED: the build stage ran again, but the production node_modules came out identical, so BuildKit reused the cached layer in the runtime stage as well. Times of consecutive builds on a laptop (Docker 27, BuildKit):

docker build time for the runtime image in different scenarios
no file changes                                   1.4 s
change in src/ (compile, dependencies cached)     5.9 s
change in package.json (npm ci, cache mount)      8.3 s
--no-cache (npm cache mount still warm)           8.8 s

PID 1, signals and the healthcheck

  • The exec form (CMD ["node", "dist/main.js"]) makes Node PID 1, receiving SIGTERM directly. A PID 1 process has no default signal handling – if the application does not handle SIGTERM itself, docker stop sends SIGKILL after 10 seconds. NestJS with enableShutdownHooks() closes the HTTP server and database connections (onApplicationShutdown). To reap zombie processes, run the container with --init (tini).
  • HEALTHCHECK is used by Docker and compose (depends_on: condition: service_healthy). Kubernetes ignores it and uses its own probes – covered in the Kubernetes tutorial.
  • Alpine or slim? Alpine (musl) gives the smallest images. If you use native modules without prebuilt musl binaries, pick node:24-slim (Debian, glibc). An even smaller attack surface comes from distroless and hardened images (Chainguard, Docker Hardened Images) – no shell, no package manager.

Step 3. Frontend: Vite + nginx without root

After building, the frontend is just static files – the production image does not need Node.js. You build them in a Node stage and serve them from nginxinc/nginx-unprivileged (port 8080, the nginx user instead of root).

Frontend Dockerfile, nginx config and the app

web/Dockerfile
# syntax=docker/dockerfile:1
FROM node:24-alpine AS deps
WORKDIR /app
# npm ci installs exactly what package-lock.json says (commit the lock file!)
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

# Development: Vite dev server, source synced by compose "develop.watch".
FROM deps AS dev
COPY . .
EXPOSE 5173
CMD ["npm", "run", "dev"]

# Build the static files with Node…
FROM deps AS build
COPY . .
RUN npm run build

# …and serve them with nginx running as a non-root user. No Node.js in the final image.
FROM nginxinc/nginx-unprivileged:1.29-alpine AS runtime
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1
web/nginx.conf
# nginx-unprivileged listens on 8080 and runs as a non-root user.
server {
  listen 8080;
  server_name _;
  root /usr/share/nginx/html;
  index index.html;

  # Vite puts content hashes in file names → cache "forever".
  location /assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    try_files $uri =404;
  }

  # API requests go to the backend container (service name "api" in compose/Kubernetes).
  location /api/ {
    proxy_pass http://api:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }

  # SPA fallback: unknown paths return index.html, which must never be cached.
  location / {
    add_header Cache-Control "no-cache";
    try_files $uri $uri/ /index.html;
  }

  location = /healthz {
    access_log off;
    return 200 "ok\n";
  }
}
web/.dockerignore
node_modules
dist
.git
.env*
*.log
Dockerfile
.dockerignore
web/src/main.tsx
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

type Menu = { source: string; items: { id: string; name: string; price_cents: number }[] };

function App() {
  const [menu, setMenu] = useState<Menu | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    fetch("/api/menu", { signal: controller.signal })
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
      .then(setMenu)
      .catch((e: Error) => e.name !== "AbortError" && setError(e.message));
    return () => controller.abort();
  }, []);

  if (error) return <p role="alert">Menu unavailable: {error}</p>;
  if (!menu) return <p>Loading…</p>;
  return (
    <main style={{ fontFamily: "system-ui", padding: "1rem" }}>
      <h1>Pierogi menu</h1>
      <ul>{menu.items.map((i) => <li key={i.id}>{i.name} – {(i.price_cents / 100).toFixed(2)} zł</li>)}</ul>
      <small>served from: {menu.source}</small>
    </main>
  );
}

createRoot(document.getElementById("root")!).render(<StrictMode><App /></StrictMode>);
web/vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// In docker compose the API is reachable as http://api:3000; locally as localhost:3000.
export default defineConfig({
  plugins: [react()],
  server: { proxy: { "/api": process.env.API_URL ?? "http://localhost:3000" } },
});
web/package.json
{
  "name": "pierogi-web",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite --host 0.0.0.0",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^19.3.1",
    "react-dom": "^19.3.1"
  },
  "devDependencies": {
    "@types/react": "^19.3.3",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
web/index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogi menu</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
web/tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true
  },
  "include": ["src", "vite.config.ts"]
}
  • Long cache for /assets/ – Vite adds a content hash to file names, so they can be cached "forever" (immutable). index.html gets no-cache, so a new app version is visible right away.
  • try_files … /index.html – a fallback for client-side routing (refreshing /orders/42 does not end in 404).
  • /api/ through nginx – frontend and API share one domain, no CORS. In Kubernetes the Gateway API can take over this role.
Image size: before and after (MB) – Measured for the images in this tutorial (Docker 27, BuildKit, linux/arm64): docker image inspect (compressed content size) and docker images (disk usage).
compressed (registry download)on disk after unpacking
API: FROM node:24, npm install418 MB1710 MB
API: multi-stage, alpine, prod only65 MB268 MB
Frontend: nginx-unprivileged + dist23 MB82 MB

Step 4. docker compose for developers

compose.yaml and database initialization

compose.yaml
# Local development: docker compose up --watch
name: pierogi

services:
  db:
    image: postgres:18-alpine
    environment:
      POSTGRES_DB: pierogi
      POSTGRES_USER: pierogi
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-local-dev-only} # never reuse outside your laptop
    volumes:
      - db-data:/var/lib/postgresql # PostgreSQL 18 images keep data under /var/lib/postgresql/18/docker
      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U pierogi -d pierogi"]
      interval: 5s
      timeout: 3s
      retries: 10

  cache:
    image: redis:8-alpine
    command: ["redis-server", "--save", "", "--appendonly", "no"] # a cache, not a database
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 10

  api:
    build: { context: ./api, target: dev }
    environment:
      DATABASE_URL: postgres://pierogi:${POSTGRES_PASSWORD:-local-dev-only}@db:5432/pierogi
      REDIS_URL: redis://cache:6379
      PORT: "3000"
    ports: ["${API_PORT:-3000}:3000"]
    depends_on:
      db: { condition: service_healthy }
      cache: { condition: service_healthy }
    develop:
      watch:
        - action: sync # copy changed files into the running container (tsc --watch + node --watch restart)
          path: ./api/src
          target: /app/src
        - action: rebuild # new dependency → rebuild the image
          path: ./api/package.json

  web:
    build: { context: ./web, target: dev }
    environment:
      API_URL: http://api:3000
    ports: ["${WEB_PORT:-5173}:5173"]
    depends_on: [api]
    develop:
      watch:
        - action: sync
          path: ./web/src
          target: /app/src
        - action: rebuild
          path: ./web/package.json

volumes:
  db-data:
db/init.sql
-- Runs once, when the PostgreSQL volume is empty (docker-entrypoint-initdb.d).
CREATE TABLE IF NOT EXISTS menu (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL CHECK (price_cents > 0)
);
INSERT INTO menu (id, name, price_cents) VALUES
  ('ruskie', 'Ruskie', 2400),
  ('meat', 'With meat', 2700),
  ('spinach', 'Spinach & feta', 2600)
ON CONFLICT (id) DO NOTHING;
docker compose up --watch        # builds dev images, starts db and cache, waits for healthy, watches changes
docker compose logs -f api       # logs of one service
docker compose exec db psql -U pierogi pierogi
docker compose down -v           # stops everything and removes the database volume
  • depends_on with condition: service_healthy – the API starts only when pg_isready and redis-cli ping answer. Without the condition compose waits only for the container to start, not for the database to be ready.
  • develop.watch: sync copies changed files into the running container (here tsc --watch + node --watch restart the API), and rebuild rebuilds the image after a package.json change. It is faster and more predictable than bind-mounting the whole directory with node_modules from the host.
  • PostgreSQL 18 changed the directory layout in the official image: data lives in /var/lib/postgresql/18/docker, and you mount the volume at /var/lib/postgresql. A volume at the old location (/var/lib/postgresql/data) does not cover the new data directory – check this when moving from version 17.
  • init.sql in docker-entrypoint-initdb.d runs only with an empty volume – after a schema change use migrations or docker compose down -v.
  • A password defaulting to local-dev-only is fine on a laptop. On servers, compose is not a secret management tool.
docker compose config – file validation and the list of services
$ docker compose config -q && echo valid
valid
$ docker compose config --services
cache
db
api
web

Step 5. Image scanning and the supply chain

An image is your code plus hundreds of OS and npm packages you don't think about day to day. A scanner compares them with vulnerability databases:

trivy image --severity HIGH,CRITICAL --ignore-unfixed pierogi-api:1.0.0   # vulnerabilities in the image
trivy config .                                                             # Dockerfile/K8s misconfigurations (e.g. no USER)
trivy image --format cyclonedx --output sbom.cdx.json pierogi-api:1.0.0    # SBOM – a bill of materials
docker scout cves pierogi-api:1.0.0                                        # an alternative built into Docker

In CI you scan after building and before pushing the image to the registry:

GitHub Actions workflow: build and scan

.github/workflows/images.yml
name: images
on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  api-image:
    runs-on: ubuntu-latest
    steps:
      # Third-party actions pinned to a full commit SHA (a tag can be moved – see the Trivy incident of March 2026).
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1

      - name: Build the runtime image
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: ./api
          target: runtime
          tags: pierogi-api:${{ github.sha }}
          load: true
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Scan the image (fail on fixable HIGH/CRITICAL)
        uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
        with:
          image-ref: pierogi-api:${{ github.sha }}
          severity: HIGH,CRITICAL
          ignore-unfixed: true
          exit-code: "1"
          version: v0.76.2

Alpine image + multi-stage build – pros

  • Small images: faster pulls, quicker start when autoscaling, lower registry cost
  • Fewer packages = fewer vulnerabilities to patch
  • A clear split: build tools never reach production

Alpine image + multi-stage build – cons

  • musl instead of glibc – sometimes missing native module binaries or different DNS behaviour
  • No diagnostic tools in the container – you debug with `docker debug` or a helper container

Common mistakes

  • latest as the base and production image tag – yesterday's and today's builds may produce different images, and a rollback does not know what to go back to. Pin the version (node:24-alpine, and a digest in production) and tag images with a version or commit SHA.
  • No .dockerignore – node_modules from macOS ends up in the context (and the image), builds take longer, and .env lands in a layer.
  • COPY . . before installing dependencies – every code change reinstalls everything.
  • A container running as root – a vulnerability in the app gives the attacker root in the container and an easier path to the host.
  • version: at the top of compose.yaml – the field is obsolete and ignored; modern Compose does not need it.
  • Database data without a volume – docker compose down and the database disappears with the container.
  • One container with the API, the database and cron – one process per container; compose or an orchestrator handles the rest.

Check yourself

Question: You change one line in `src/app.controller.ts`. Which instruction order gives the fastest rebuild?

  • `COPY . .`, then `RUN npm ci`, then `RUN npm run build`
  • `COPY package.json package-lock.json ./`, `RUN npm ci`, then `COPY src ./src` and `RUN npm run build`
  • Order does not matter with BuildKit

Question: Why is `CMD npm start` (shell form) worse than `CMD ["node", "dist/main.js"]`?

  • Because npm is slower than node
  • Because `sh` and npm sit between Docker and Node – `SIGTERM` may never reach the app, so it does not shut down gracefully and `docker stop` waits until `SIGKILL`
  • Because the shell form does not support environment variables
Interview question: "How do you build a secure and small image for a Node.js application?"

A multi-stage Dockerfile: a dependency stage copies only package.json and the lockfile and runs npm ci with a BuildKit cache mount, a build stage compiles and removes devDependencies, and a runtime stage starts from a small image (alpine, slim or distroless) and copies only dist, production node_modules and package.json. The process runs as an ordinary user, CMD is in exec form, the app handles SIGTERM, and there is a healthcheck. .dockerignore excludes node_modules, .git and .env; I pass build secrets with --mount=type=secret and application secrets at run time. I pin the base image by version (by digest in production), tag images with a version or commit SHA, scan with Trivy in CI (with a pinned Trivy version and the action pinned by SHA), generate an SBOM and block deployment on critical vulnerabilities that have a fix.

What next