{"id":"6b09aa7d5a5e2dbc3f20a471","slug":"docker-for-developers","title":"Docker for developers – multi-stage Node/NestJS and React images, layer caching, docker compose and image scanning","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["docker","nodejs","secure-sdlc"],"techs":["node","typescript"],"tags":["docker","dockerfile","multi-stage-build","buildkit","docker-compose","nginx","postgresql-18","redis","trivy","sbom","supply-chain"],"level":"intermediate","kind":"tutorial","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":19,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:21.811Z","updatedAt":"2026-11-27T17:23:22.593Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Docker step by step for Node.js and React developers – image vs container, a multi-stage Dockerfile for NestJS and Vite + nginx, layer order and BuildKit cache mounts, .dockerignore, USER node, HEALTHCHECK, signals and PID 1, docker compose watch, depends_on healthy, PostgreSQL 18, Trivy and SBOM, i","wordCount":3790,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"The first Dockerfile in a project usually looks the same: "},{"type":"text","text":"FROM node","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"COPY . .","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"npm install","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"npm start","marks":[{"type":"code"}]},{"type":"text","text":". 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 "},{"type":"text","text":"docker stop","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"An image is a recipe plus a frozen filesystem; a container is a running process.","marks":[{"type":"bold"}]},{"type":"text","text":" An image consists of layers; every "},{"type":"text","text":"RUN","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"COPY","marks":[{"type":"code"}]},{"type":"text","text":" instruction creates a new layer, and the cache works up to the first changed one."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A multi-stage build","marks":[{"type":"bold"}]},{"type":"text","text":" separates the tools (TypeScript compiler, devDependencies, Vite) from what goes to production. The API image dropped from 418 MB to 65 MB (compressed), and the frontend is a 23 MB nginx image without Node.js."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Security means defaults, not extras","marks":[{"type":"bold"}]},{"type":"text","text":": an ordinary user instead of root, no secrets in layers, "},{"type":"text","text":".dockerignore","marks":[{"type":"code"}]},{"type":"text","text":", a healthcheck, pinned image and CI action versions, and scanning (Trivy) before deployment."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Two images and a development environment: an "},{"type":"text","text":"API","marks":[{"type":"bold"}]},{"type":"text","text":" in NestJS 12 ("},{"type":"text","text":"/api/health","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"/api/menu","marks":[{"type":"code"}]},{"type":"text","text":" cached in Redis), a React 19 "},{"type":"text","text":"frontend","marks":[{"type":"bold"}]},{"type":"text","text":" served by nginx running without root privileges, a "},{"type":"text","text":"compose.yaml","marks":[{"type":"code"}]},{"type":"text","text":" with PostgreSQL 18, Redis 8 and automatic code reloading ("},{"type":"text","text":"docker compose up --watch","marks":[{"type":"code"}]},{"type":"text","text":"), and a GitHub Actions workflow that builds the image and blocks deployment on HIGH/CRITICAL vulnerabilities. You can download the code as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" Docker Desktop or Docker Engine with Compose v2, Node.js 24 LTS, "},{"type":"text","text":"NestJS","marks":[{"type":"link","attrs":{"href":"/en/articles/nestjs"}}]},{"type":"text","text":" and "},{"type":"text","text":"React","marks":[{"type":"link","attrs":{"href":"/en/articles/react"}}]},{"type":"text","text":" basics. "},{"type":"text","text":"Node.js under the hood","marks":[{"type":"link","attrs":{"href":"/en/articles/nodejs-runtime"}}]},{"type":"text","text":" helps – it explains signals and process memory."}]},{"type":"stats","attrs":{"items":[{"value":"418 → 65 MB","label":"API image (compressed)","hint":"naive vs multi-stage"},{"value":"1.7 GB → 268 MB","label":"API image on disk","hint":"the same, unpacked"},{"value":"23 MB","label":"frontend image","hint":"nginx + static files, no Node.js"},{"value":"1.4 s","label":"rebuild without changes","hint":"BuildKit layer cache"}]}},{"type":"heading","attrs":{"level":2,"id":"image-container-layers"},"content":[{"type":"text","text":"Image, container, layers"}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  DF[\"Dockerfile<br/>+ build context\"] -->|\"docker build\"| IMG[\"Image<br/>read-only layers<br/>+ metadata (CMD, USER, ENV)\"]\n  IMG -->|\"docker push\"| REG[(\"Registry<br/>GHCR, ECR, Docker Hub\")]\n  REG -->|\"docker pull\"| IMG2[\"Image on the server\"]\n  IMG2 -->|\"docker run\"| C1[\"Container 1<br/>process + writable layer\"]\n  IMG2 -->|\"docker run\"| C2[\"Container 2\"]","caption":"From a Dockerfile to a running container"}},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"An image","marks":[{"type":"bold"}]},{"type":"text","text":" 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 ("},{"type":"text","text":"sha256:…","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A container","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The layer cache","marks":[{"type":"bold"}]},{"type":"text","text":": 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."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-1-the-application-and-the-starting-point"},"content":[{"type":"text","text":"Step 1. The application and the starting point"}]},{"type":"paragraph","content":[{"type":"text","text":"We containerize a small API: "},{"type":"text","text":"GET /api/live","marks":[{"type":"code"}]},{"type":"text","text":" (is the process alive), "},{"type":"text","text":"GET /api/health","marks":[{"type":"code"}]},{"type":"text","text":" (are the database and Redis working) and "},{"type":"text","text":"GET /api/menu","marks":[{"type":"code"}]},{"type":"text","text":" (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."}]},{"type":"codeGroup","attrs":{"title":"API code"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"api/src/app.controller.ts"},"content":[{"type":"text","text":"import { Controller, Get, Inject, ServiceUnavailableException } from \"@nestjs/common\";\nimport type { Redis } from \"ioredis\";\nimport type pg from \"pg\";\nimport { PG, REDIS } from \"./infra.js\";\n\ntype MenuItem = { id: string; name: string; price_cents: number };\n\n@Controller()\nexport class AppController {\n  constructor(\n    @Inject(PG) private readonly db: pg.Pool,\n    @Inject(REDIS) private readonly cache: Redis,\n  ) {}\n\n  // Liveness: \"is the process alive?\" – deliberately WITHOUT database checks,\n  // otherwise a database outage would make Kubernetes restart every API pod.\n  @Get(\"live\")\n  live() {\n    return { status: \"ok\" };\n  }\n\n  // Readiness: \"can I serve traffic?\" – used by the Dockerfile HEALTHCHECK, compose and Kubernetes.\n  @Get(\"health\")\n  async health() {\n    const [db, cache] = await Promise.allSettled([this.db.query(\"SELECT 1\"), this.cache.ping()]);\n    const status = { db: db.status === \"fulfilled\" ? \"up\" : \"down\", cache: cache.status === \"fulfilled\" ? \"up\" : \"down\" };\n    if (status.db === \"down\" || status.cache === \"down\") throw new ServiceUnavailableException(status);\n    return { status: \"ok\", ...status, uptimeSec: Math.round(process.uptime()) };\n  }\n\n  // Cache-aside: Redis first, PostgreSQL on a miss, then store for 30 s.\n  @Get(\"menu\")\n  async menu() {\n    const cached = await this.cache.get(\"menu:v1\");\n    if (cached) return { source: \"cache\", items: JSON.parse(cached) as MenuItem[] };\n    const { rows } = await this.db.query<MenuItem>(\"SELECT id, name, price_cents FROM menu ORDER BY name\");\n    await this.cache.set(\"menu:v1\", JSON.stringify(rows), \"EX\", 30);\n    return { source: \"database\", items: rows };\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"api/src/infra.ts"},"content":[{"type":"text","text":"import { Inject, Injectable, type OnApplicationShutdown } from \"@nestjs/common\";\nimport { Redis } from \"ioredis\";\nimport pg from \"pg\";\n\nexport const PG = Symbol(\"PG\");\nexport const REDIS = Symbol(\"REDIS\");\n\n// Connection settings come from the environment – the same image runs in dev, CI and production.\nexport const infraProviders = [\n  { provide: PG, useFactory: () => new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 }) },\n  { provide: REDIS, useFactory: () => new Redis(process.env.REDIS_URL ?? \"redis://localhost:6379\", { lazyConnect: false, maxRetriesPerRequest: 2 }) },\n];\n\n// Close connections on SIGTERM (docker stop, Kubernetes rolling update).\n@Injectable()\nexport class InfraShutdown implements OnApplicationShutdown {\n  constructor(\n    @Inject(PG) private readonly pool: pg.Pool,\n    @Inject(REDIS) private readonly redis: Redis,\n  ) {}\n\n  async onApplicationShutdown(signal?: string) {\n    console.log(`shutting down (${signal ?? \"no signal\"}) – closing connections`);\n    await Promise.allSettled([this.pool.end(), this.redis.quit()]);\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"api/src/main.ts"},"content":[{"type":"text","text":"import \"reflect-metadata\";\nimport { Module } from \"@nestjs/common\";\nimport { NestFactory } from \"@nestjs/core\";\nimport { AppController } from \"./app.controller.js\";\nimport { InfraShutdown, infraProviders } from \"./infra.js\";\n\n@Module({ controllers: [AppController], providers: [...infraProviders, InfraShutdown] })\nclass AppModule {}\n\nconst app = await NestFactory.create(AppModule);\napp.setGlobalPrefix(\"api\");\napp.enableShutdownHooks(); // react to SIGTERM/SIGINT: finish requests, close connections\nawait app.listen(Number(process.env.PORT ?? 3000), \"0.0.0.0\");\nconsole.log(`pierogi-api listening on :${process.env.PORT ?? 3000}`);"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"api/package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-api\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"engines\": {\n    \"node\": \">=24\"\n  },\n  \"scripts\": {\n    \"build\": \"tsc -p tsconfig.json\",\n    \"dev\": \"tsc -p tsconfig.json && (tsc -p tsconfig.json --watch --preserveWatchOutput > /dev/null & node --watch dist/main.js)\",\n    \"start\": \"node dist/main.js\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^12.6.3\",\n    \"@nestjs/core\": \"^12.6.3\",\n    \"@nestjs/platform-express\": \"^12.6.3\",\n    \"ioredis\": \"^6.1.0\",\n    \"pg\": \"^8.23.1\",\n    \"reflect-metadata\": \"^0.2.2\",\n    \"rxjs\": \"^7.8.2\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.19.4\",\n    \"@types/pg\": \"^8.23.1\",\n    \"typescript\": \"~6.0.3\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"api/tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"types\": [\"node\"],\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": false\n  },\n  \"include\": [\"src\"]\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"And this is the Dockerfile many projects start with:"}]},{"type":"codeGroup","attrs":{"title":"Starting point: a naive Dockerfile"},"content":[{"type":"codeBlock","attrs":{"language":"dockerfile","filename":"api/Dockerfile.naive"},"content":[{"type":"text","text":"# \"Before\": the Dockerfile many projects start with. Works – and that is its only virtue.\nFROM node:24\nWORKDIR /app\nCOPY . .\nRUN npm install\nRUN npm run build\nEXPOSE 3000\nCMD npm start"}]}]},{"type":"paragraph","content":[{"type":"text","text":"What is wrong with it? "},{"type":"text","text":"node:24","marks":[{"type":"code"}]},{"type":"text","text":" is a full Debian with compilers (over 1 GB), "},{"type":"text","text":"COPY . .","marks":[{"type":"code"}]},{"type":"text","text":" before "},{"type":"text","text":"npm install","marks":[{"type":"code"}]},{"type":"text","text":" invalidates the dependency cache on every code change, the image keeps devDependencies, TypeScript sources and everything that was lying around in the directory (including "},{"type":"text","text":".env","marks":[{"type":"code"}]},{"type":"text","text":"), the process runs as root, and the shell form "},{"type":"text","text":"CMD npm start","marks":[{"type":"code"}]},{"type":"text","text":" starts the app through "},{"type":"text","text":"sh","marks":[{"type":"code"}]},{"type":"text","text":" and npm – extra processes in the signal path, so whether "},{"type":"text","text":"SIGTERM","marks":[{"type":"code"}]},{"type":"text","text":" reaches Node depends on the shell and the npm version."}]},{"type":"heading","attrs":{"level":2,"id":"step-2-a-multi-stage-dockerfile-for-nestjs"},"content":[{"type":"text","text":"Step 2. A multi-stage Dockerfile for NestJS"}]},{"type":"codeGroup","attrs":{"title":"API Dockerfile and .dockerignore"},"content":[{"type":"codeBlock","attrs":{"language":"dockerfile","filename":"api/Dockerfile"},"content":[{"type":"text","text":"# syntax=docker/dockerfile:1\nARG NODE_VERSION=24\n\n# --- dependencies (cached as long as package*.json does not change) ---\nFROM node:${NODE_VERSION}-alpine AS deps\nWORKDIR /app\n# npm ci installs exactly what package-lock.json says (commit the lock file!)\nCOPY package.json package-lock.json ./\nRUN --mount=type=cache,target=/root/.npm npm ci\n\n# --- development: used by docker compose (source synced by \"develop.watch\") ---\nFROM deps AS dev\nCOPY tsconfig.json ./\nCOPY src ./src\nCMD [\"npm\", \"run\", \"dev\"]\n\n# --- build: compile TypeScript, then drop devDependencies ---\nFROM deps AS build\nCOPY tsconfig.json ./\nCOPY src ./src\nRUN npm run build && npm prune --omit=dev\n\n# --- runtime: only what is needed to run, as a non-root user ---\nFROM node:${NODE_VERSION}-alpine AS runtime\nENV NODE_ENV=production\nWORKDIR /app\nCOPY --from=build --chown=node:node /app/package.json ./\nCOPY --from=build --chown=node:node /app/node_modules ./node_modules\nCOPY --from=build --chown=node:node /app/dist ./dist\nUSER node\nEXPOSE 3000\nHEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \\\n  CMD node -e \"fetch('http://127.0.0.1:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\"\n# exec form: node is PID 1 and receives SIGTERM directly (use `docker run --init` / tini for zombie reaping)\nCMD [\"node\", \"dist/main.js\"]"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":"api/.dockerignore"},"content":[{"type":"text","text":"# Keep the build context small and secrets out of the image.\nnode_modules\ndist\ncoverage\n.git\n.github\n.env*\n*.log\n*.md\nDockerfile*\n.dockerignore\ncompose*.yaml"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Stage by stage:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"deps","marks":[{"type":"code"}]},{"type":"text","text":" copies only "},{"type":"text","text":"package.json","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"package-lock.json","marks":[{"type":"code"}]},{"type":"text","text":", then runs "},{"type":"text","text":"npm ci","marks":[{"type":"code"}]},{"type":"text","text":". This layer is rebuilt only when dependencies change. "},{"type":"text","text":"--mount=type=cache,target=/root/.npm","marks":[{"type":"code"}]},{"type":"text","text":" keeps the npm cache between builds outside the image – even when dependencies change you only download what is missing."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"dev","marks":[{"type":"code"}]},{"type":"text","text":" – the image for docker compose: sources and "},{"type":"text","text":"npm run dev","marks":[{"type":"code"}]},{"type":"text","text":" (compiler in watch mode + "},{"type":"text","text":"node --watch","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"build","marks":[{"type":"code"}]},{"type":"text","text":" compiles TypeScript and removes devDependencies ("},{"type":"text","text":"npm prune --omit=dev","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"runtime","marks":[{"type":"code"}]},{"type":"text","text":" starts from a clean "},{"type":"text","text":"node:24-alpine","marks":[{"type":"code"}]},{"type":"text","text":" and copies only "},{"type":"text","text":"package.json","marks":[{"type":"code"}]},{"type":"text","text":", production "},{"type":"text","text":"node_modules","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"dist","marks":[{"type":"code"}]},{"type":"text","text":". The files belong to the "},{"type":"text","text":"node","marks":[{"type":"code"}]},{"type":"text","text":" user ("},{"type":"text","text":"--chown","marks":[{"type":"code"}]},{"type":"text","text":"), the process runs as "},{"type":"text","text":"node","marks":[{"type":"code"}]},{"type":"text","text":" (UID 1000), and "},{"type":"text","text":"HEALTHCHECK","marks":[{"type":"code"}]},{"type":"text","text":" polls "},{"type":"text","text":"/api/health","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"output","attrs":{"title":"Rebuild after changing one file in src/ (docker build --progress=plain, selected lines)","language":"bash","content":"#8 [deps 4/4] RUN --mount=type=cache,target=/root/.npm npm ci\n#8 CACHED\n#9 [deps 3/4] COPY package.json package-lock.json ./\n#9 CACHED\n#11 [build 1/3] COPY tsconfig.json ./\n#11 CACHED\n#12 [build 2/3] COPY src ./src\n#13 [build 3/3] RUN npm run build && npm prune --omit=dev\n#14 [runtime 3/5] COPY --from=build --chown=node:node /app/package.json ./\n#14 CACHED\n#15 [runtime 4/5] COPY --from=build --chown=node:node /app/node_modules ./node_modules\n#15 CACHED\n#16 [runtime 5/5] COPY --from=build --chown=node:node /app/dist ./dist"}},{"type":"paragraph","content":[{"type":"text","text":"Notice "},{"type":"text","text":"#15 CACHED","marks":[{"type":"code"}]},{"type":"text","text":": the "},{"type":"text","text":"build","marks":[{"type":"code"}]},{"type":"text","text":" stage ran again, but the production "},{"type":"text","text":"node_modules","marks":[{"type":"code"}]},{"type":"text","text":" came out identical, so BuildKit reused the cached layer in the "},{"type":"text","text":"runtime","marks":[{"type":"code"}]},{"type":"text","text":" stage as well. Times of consecutive builds on a laptop (Docker 27, BuildKit):"}]},{"type":"output","attrs":{"title":"docker build time for the runtime image in different scenarios","language":"bash","content":"no file changes                                   1.4 s\nchange in src/ (compile, dependencies cached)     5.9 s\nchange in package.json (npm ci, cache mount)      8.3 s\n--no-cache (npm cache mount still warm)           8.8 s"}},{"type":"callout","attrs":{"variant":"warning","title":"Common mistake: secrets in layers"},"content":[{"type":"paragraph","content":[{"type":"text","text":"COPY .env .","marks":[{"type":"code"}]},{"type":"text","text":" or "},{"type":"text","text":"ARG NPM_TOKEN","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"RUN npm ci","marks":[{"type":"code"}]},{"type":"text","text":" leaves the secret in the image history – even if you delete it in a later layer. "},{"type":"text","text":"docker history","marks":[{"type":"code"}]},{"type":"text","text":" and anyone who pulls the image can read it. Pass build-time secrets with "},{"type":"text","text":"RUN --mount=type=secret,id=npm_token …","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"docker build --secret id=npm_token,env=NPM_TOKEN","marks":[{"type":"code"}]},{"type":"text","text":"), and application secrets as environment variables or files mounted at run time."}]}]},{"type":"heading","attrs":{"level":3,"id":"pid-1-signals-and-the-healthcheck"},"content":[{"type":"text","text":"PID 1, signals and the healthcheck"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The exec form (","marks":[{"type":"bold"}]},{"type":"text","text":"CMD [\"node\", \"dist/main.js\"]","marks":[{"type":"code"}]},{"type":"text","text":")","marks":[{"type":"bold"}]},{"type":"text","text":" makes Node PID 1, receiving "},{"type":"text","text":"SIGTERM","marks":[{"type":"code"}]},{"type":"text","text":" directly. A PID 1 process has no default signal handling – if the application does not handle "},{"type":"text","text":"SIGTERM","marks":[{"type":"code"}]},{"type":"text","text":" itself, "},{"type":"text","text":"docker stop","marks":[{"type":"code"}]},{"type":"text","text":" sends "},{"type":"text","text":"SIGKILL","marks":[{"type":"code"}]},{"type":"text","text":" after 10 seconds. NestJS with "},{"type":"text","text":"enableShutdownHooks()","marks":[{"type":"code"}]},{"type":"text","text":" closes the HTTP server and database connections ("},{"type":"text","text":"onApplicationShutdown","marks":[{"type":"code"}]},{"type":"text","text":"). To reap zombie processes, run the container with "},{"type":"text","text":"--init","marks":[{"type":"code"}]},{"type":"text","text":" (tini)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"HEALTHCHECK","marks":[{"type":"code"}]},{"type":"text","text":" is used by Docker and compose ("},{"type":"text","text":"depends_on: condition: service_healthy","marks":[{"type":"code"}]},{"type":"text","text":"). Kubernetes ignores it and uses its own probes – covered in the "},{"type":"text","text":"Kubernetes tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/kubernetes-basics"}}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Alpine or slim?","marks":[{"type":"bold"}]},{"type":"text","text":" Alpine (musl) gives the smallest images. If you use native modules without prebuilt musl binaries, pick "},{"type":"text","text":"node:24-slim","marks":[{"type":"code"}]},{"type":"text","text":" (Debian, glibc). An even smaller attack surface comes from distroless and hardened images (Chainguard, Docker Hardened Images) – no shell, no package manager."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-3-frontend-vite-nginx-without-root"},"content":[{"type":"text","text":"Step 3. Frontend: Vite + nginx without root"}]},{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"nginxinc/nginx-unprivileged","marks":[{"type":"code"}]},{"type":"text","text":" (port 8080, the nginx user instead of root)."}]},{"type":"codeGroup","attrs":{"title":"Frontend Dockerfile, nginx config and the app"},"content":[{"type":"codeBlock","attrs":{"language":"dockerfile","filename":"web/Dockerfile"},"content":[{"type":"text","text":"# syntax=docker/dockerfile:1\nFROM node:24-alpine AS deps\nWORKDIR /app\n# npm ci installs exactly what package-lock.json says (commit the lock file!)\nCOPY package.json package-lock.json ./\nRUN --mount=type=cache,target=/root/.npm npm ci\n\n# Development: Vite dev server, source synced by compose \"develop.watch\".\nFROM deps AS dev\nCOPY . .\nEXPOSE 5173\nCMD [\"npm\", \"run\", \"dev\"]\n\n# Build the static files with Node…\nFROM deps AS build\nCOPY . .\nRUN npm run build\n\n# …and serve them with nginx running as a non-root user. No Node.js in the final image.\nFROM nginxinc/nginx-unprivileged:1.29-alpine AS runtime\nCOPY nginx.conf /etc/nginx/conf.d/default.conf\nCOPY --from=build /app/dist /usr/share/nginx/html\nEXPOSE 8080\nHEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":"web/nginx.conf"},"content":[{"type":"text","text":"# nginx-unprivileged listens on 8080 and runs as a non-root user.\nserver {\n  listen 8080;\n  server_name _;\n  root /usr/share/nginx/html;\n  index index.html;\n\n  # Vite puts content hashes in file names → cache \"forever\".\n  location /assets/ {\n    add_header Cache-Control \"public, max-age=31536000, immutable\";\n    try_files $uri =404;\n  }\n\n  # API requests go to the backend container (service name \"api\" in compose/Kubernetes).\n  location /api/ {\n    proxy_pass http://api:3000;\n    proxy_set_header Host $host;\n    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header X-Forwarded-Proto $scheme;\n  }\n\n  # SPA fallback: unknown paths return index.html, which must never be cached.\n  location / {\n    add_header Cache-Control \"no-cache\";\n    try_files $uri $uri/ /index.html;\n  }\n\n  location = /healthz {\n    access_log off;\n    return 200 \"ok\\n\";\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":"web/.dockerignore"},"content":[{"type":"text","text":"node_modules\ndist\n.git\n.env*\n*.log\nDockerfile\n.dockerignore"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"web/src/main.tsx"},"content":[{"type":"text","text":"import { StrictMode, useEffect, useState } from \"react\";\nimport { createRoot } from \"react-dom/client\";\n\ntype Menu = { source: string; items: { id: string; name: string; price_cents: number }[] };\n\nfunction App() {\n  const [menu, setMenu] = useState<Menu | null>(null);\n  const [error, setError] = useState<string | null>(null);\n\n  useEffect(() => {\n    const controller = new AbortController();\n    fetch(\"/api/menu\", { signal: controller.signal })\n      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))\n      .then(setMenu)\n      .catch((e: Error) => e.name !== \"AbortError\" && setError(e.message));\n    return () => controller.abort();\n  }, []);\n\n  if (error) return <p role=\"alert\">Menu unavailable: {error}</p>;\n  if (!menu) return <p>Loading…</p>;\n  return (\n    <main style={{ fontFamily: \"system-ui\", padding: \"1rem\" }}>\n      <h1>Pierogi menu</h1>\n      <ul>{menu.items.map((i) => <li key={i.id}>{i.name} – {(i.price_cents / 100).toFixed(2)} zł</li>)}</ul>\n      <small>served from: {menu.source}</small>\n    </main>\n  );\n}\n\ncreateRoot(document.getElementById(\"root\")!).render(<StrictMode><App /></StrictMode>);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"web/vite.config.ts"},"content":[{"type":"text","text":"import react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\n// In docker compose the API is reachable as http://api:3000; locally as localhost:3000.\nexport default defineConfig({\n  plugins: [react()],\n  server: { proxy: { \"/api\": process.env.API_URL ?? \"http://localhost:3000\" } },\n});"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"web/package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-web\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite --host 0.0.0.0\",\n    \"build\": \"vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"react\": \"^19.3.1\",\n    \"react-dom\": \"^19.3.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.3.3\",\n    \"@types/react-dom\": \"^19.3.0\",\n    \"@vitejs/plugin-react\": \"^6.3.0\",\n    \"typescript\": \"~7.0.2\",\n    \"vite\": \"^8.4.0\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"web/index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Pierogi menu</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"web/tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"types\": [\"vite/client\"],\n    \"jsx\": \"react-jsx\",\n    \"strict\": true,\n    \"noEmit\": true,\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"src\", \"vite.config.ts\"]\n}"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Long cache for ","marks":[{"type":"bold"}]},{"type":"text","text":"/assets/","marks":[{"type":"code"}]},{"type":"text","text":" – Vite adds a content hash to file names, so they can be cached \"forever\" ("},{"type":"text","text":"immutable","marks":[{"type":"code"}]},{"type":"text","text":"). "},{"type":"text","text":"index.html","marks":[{"type":"code"}]},{"type":"text","text":" gets "},{"type":"text","text":"no-cache","marks":[{"type":"code"}]},{"type":"text","text":", so a new app version is visible right away."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"try_files … /index.html","marks":[{"type":"code"}]},{"type":"text","text":" – a fallback for client-side routing (refreshing "},{"type":"text","text":"/orders/42","marks":[{"type":"code"}]},{"type":"text","text":" does not end in 404)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"/api/","marks":[{"type":"code"}]},{"type":"text","text":" through nginx","marks":[{"type":"bold"}]},{"type":"text","text":" – frontend and API share one domain, no CORS. In Kubernetes the Gateway API can take over this role."}]}]}]},{"type":"chart","attrs":{"type":"bar","title":"Image size: before and after (MB)","caption":"Measured for the images in this tutorial (Docker 27, BuildKit, linux/arm64): docker image inspect (compressed content size) and docker images (disk usage).","unit":"MB","data":{"labels":["API: FROM node:24, npm install","API: multi-stage, alpine, prod only","Frontend: nginx-unprivileged + dist"],"series":[{"name":"compressed (registry download)","values":[418,65,23]},{"name":"on disk after unpacking","values":[1710,268,82]}]}}},{"type":"heading","attrs":{"level":2,"id":"step-4-docker-compose-for-developers"},"content":[{"type":"text","text":"Step 4. docker compose for developers"}]},{"type":"codeGroup","attrs":{"title":"compose.yaml and database initialization"},"content":[{"type":"codeBlock","attrs":{"language":"yaml","filename":"compose.yaml"},"content":[{"type":"text","text":"# Local development: docker compose up --watch\nname: pierogi\n\nservices:\n  db:\n    image: postgres:18-alpine\n    environment:\n      POSTGRES_DB: pierogi\n      POSTGRES_USER: pierogi\n      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-local-dev-only} # never reuse outside your laptop\n    volumes:\n      - db-data:/var/lib/postgresql # PostgreSQL 18 images keep data under /var/lib/postgresql/18/docker\n      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U pierogi -d pierogi\"]\n      interval: 5s\n      timeout: 3s\n      retries: 10\n\n  cache:\n    image: redis:8-alpine\n    command: [\"redis-server\", \"--save\", \"\", \"--appendonly\", \"no\"] # a cache, not a database\n    healthcheck:\n      test: [\"CMD\", \"redis-cli\", \"ping\"]\n      interval: 5s\n      retries: 10\n\n  api:\n    build: { context: ./api, target: dev }\n    environment:\n      DATABASE_URL: postgres://pierogi:${POSTGRES_PASSWORD:-local-dev-only}@db:5432/pierogi\n      REDIS_URL: redis://cache:6379\n      PORT: \"3000\"\n    ports: [\"${API_PORT:-3000}:3000\"]\n    depends_on:\n      db: { condition: service_healthy }\n      cache: { condition: service_healthy }\n    develop:\n      watch:\n        - action: sync # copy changed files into the running container (tsc --watch + node --watch restart)\n          path: ./api/src\n          target: /app/src\n        - action: rebuild # new dependency → rebuild the image\n          path: ./api/package.json\n\n  web:\n    build: { context: ./web, target: dev }\n    environment:\n      API_URL: http://api:3000\n    ports: [\"${WEB_PORT:-5173}:5173\"]\n    depends_on: [api]\n    develop:\n      watch:\n        - action: sync\n          path: ./web/src\n          target: /app/src\n        - action: rebuild\n          path: ./web/package.json\n\nvolumes:\n  db-data:"}]},{"type":"codeBlock","attrs":{"language":"sql","filename":"db/init.sql"},"content":[{"type":"text","text":"-- Runs once, when the PostgreSQL volume is empty (docker-entrypoint-initdb.d).\nCREATE TABLE IF NOT EXISTS menu (\n  id TEXT PRIMARY KEY,\n  name TEXT NOT NULL,\n  price_cents INTEGER NOT NULL CHECK (price_cents > 0)\n);\nINSERT INTO menu (id, name, price_cents) VALUES\n  ('ruskie', 'Ruskie', 2400),\n  ('meat', 'With meat', 2700),\n  ('spinach', 'Spinach & feta', 2600)\nON CONFLICT (id) DO NOTHING;"}]}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"docker compose up --watch        # builds dev images, starts db and cache, waits for healthy, watches changes\ndocker compose logs -f api       # logs of one service\ndocker compose exec db psql -U pierogi pierogi\ndocker compose down -v           # stops everything and removes the database volume"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"depends_on","marks":[{"type":"code"}]},{"type":"text","text":" with ","marks":[{"type":"bold"}]},{"type":"text","text":"condition: service_healthy","marks":[{"type":"code"}]},{"type":"text","text":" – the API starts only when "},{"type":"text","text":"pg_isready","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"redis-cli ping","marks":[{"type":"code"}]},{"type":"text","text":" answer. Without the condition compose waits only for the container to "},{"type":"text","text":"start","marks":[{"type":"italic"}]},{"type":"text","text":", not for the database to be ready."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"develop.watch","marks":[{"type":"code"}]},{"type":"text","text":": "},{"type":"text","text":"sync","marks":[{"type":"code"}]},{"type":"text","text":" copies changed files into the running container (here "},{"type":"text","text":"tsc --watch","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"node --watch","marks":[{"type":"code"}]},{"type":"text","text":" restart the API), and "},{"type":"text","text":"rebuild","marks":[{"type":"code"}]},{"type":"text","text":" rebuilds the image after a "},{"type":"text","text":"package.json","marks":[{"type":"code"}]},{"type":"text","text":" change. It is faster and more predictable than bind-mounting the whole directory with "},{"type":"text","text":"node_modules","marks":[{"type":"code"}]},{"type":"text","text":" from the host."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"PostgreSQL 18","marks":[{"type":"bold"}]},{"type":"text","text":" changed the directory layout in the official image: data lives in "},{"type":"text","text":"/var/lib/postgresql/18/docker","marks":[{"type":"code"}]},{"type":"text","text":", and you mount the volume at "},{"type":"text","text":"/var/lib/postgresql","marks":[{"type":"code"}]},{"type":"text","text":". A volume at the old location ("},{"type":"text","text":"/var/lib/postgresql/data","marks":[{"type":"code"}]},{"type":"text","text":") does not cover the new data directory – check this when moving from version 17."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"init.sql","marks":[{"type":"code"}]},{"type":"text","text":" in ","marks":[{"type":"bold"}]},{"type":"text","text":"docker-entrypoint-initdb.d","marks":[{"type":"code"}]},{"type":"text","text":" runs only with an empty volume – after a schema change use migrations or "},{"type":"text","text":"docker compose down -v","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A password defaulting to ","marks":[{"type":"bold"}]},{"type":"text","text":"local-dev-only","marks":[{"type":"code"}]},{"type":"text","text":" is fine on a laptop. On servers, compose is not a secret management tool."}]}]}]},{"type":"output","attrs":{"title":"docker compose config – file validation and the list of services","language":"bash","content":"$ docker compose config -q && echo valid\nvalid\n$ docker compose config --services\ncache\ndb\napi\nweb"}},{"type":"heading","attrs":{"level":2,"id":"step-5-image-scanning-and-the-supply-chain"},"content":[{"type":"text","text":"Step 5. Image scanning and the supply chain"}]},{"type":"paragraph","content":[{"type":"text","text":"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:"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"trivy image --severity HIGH,CRITICAL --ignore-unfixed pierogi-api:1.0.0   # vulnerabilities in the image\ntrivy config .                                                             # Dockerfile/K8s misconfigurations (e.g. no USER)\ntrivy image --format cyclonedx --output sbom.cdx.json pierogi-api:1.0.0    # SBOM – a bill of materials\ndocker scout cves pierogi-api:1.0.0                                        # an alternative built into Docker"}]},{"type":"paragraph","content":[{"type":"text","text":"In CI you scan after building and before pushing the image to the registry:"}]},{"type":"codeGroup","attrs":{"title":"GitHub Actions workflow: build and scan"},"content":[{"type":"codeBlock","attrs":{"language":"yaml","filename":".github/workflows/images.yml"},"content":[{"type":"text","text":"name: images\non:\n  push:\n    branches: [main]\n  pull_request:\n\npermissions:\n  contents: read\n\njobs:\n  api-image:\n    runs-on: ubuntu-latest\n    steps:\n      # Third-party actions pinned to a full commit SHA (a tag can be moved – see the Trivy incident of March 2026).\n      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\n      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1\n\n      - name: Build the runtime image\n        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0\n        with:\n          context: ./api\n          target: runtime\n          tags: pierogi-api:${{ github.sha }}\n          load: true\n          cache-from: type=gha\n          cache-to: type=gha,mode=max\n\n      - name: Scan the image (fail on fixable HIGH/CRITICAL)\n        uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0\n        with:\n          image-ref: pierogi-api:${{ github.sha }}\n          severity: HIGH,CRITICAL\n          ignore-unfixed: true\n          exit-code: \"1\"\n          version: v0.76.2"}]}]},{"type":"callout","attrs":{"variant":"danger","title":"Pin security tools by digest, not by tag"},"content":[{"type":"paragraph","content":[{"type":"text","text":"In March 2026 an attacker with stolen credentials overwrote most tags of "},{"type":"text","text":"aquasecurity/trivy-action","marks":[{"type":"code"}]},{"type":"text","text":" with malicious code that stole secrets from CI runners, published a malicious Trivy 0.69.4 release, and a few days later swapped images on Docker Hub. Workflows that used "},{"type":"text","text":"@v0.x","marks":[{"type":"code"}]},{"type":"text","text":" or "},{"type":"text","text":"latest","marks":[{"type":"code"}]},{"type":"text","text":" ran the malicious code. That is why you pin actions to a full commit SHA (with the version in a comment), images to a "},{"type":"text","text":"@sha256:…","marks":[{"type":"code"}]},{"type":"text","text":" digest, and set the Trivy version explicitly. Leave updates to Dependabot or Renovate – a SHA change then goes through code review."}]}]},{"type":"prosCons","attrs":{"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"],"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"],"prosTitle":"Alpine image + multi-stage build – pros","consTitle":"Alpine image + multi-stage build – cons"}},{"type":"heading","attrs":{"level":2,"id":"common-mistakes"},"content":[{"type":"text","text":"Common mistakes"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"latest","marks":[{"type":"code"}]},{"type":"text","text":" as the base and production image tag","marks":[{"type":"bold"}]},{"type":"text","text":" – yesterday's and today's builds may produce different images, and a rollback does not know what to go back to. Pin the version ("},{"type":"text","text":"node:24-alpine","marks":[{"type":"code"}]},{"type":"text","text":", and a digest in production) and tag images with a version or commit SHA."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"No ","marks":[{"type":"bold"}]},{"type":"text","text":".dockerignore","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"node_modules","marks":[{"type":"code"}]},{"type":"text","text":" from macOS ends up in the context (and the image), builds take longer, and "},{"type":"text","text":".env","marks":[{"type":"code"}]},{"type":"text","text":" lands in a layer."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"COPY . .","marks":[{"type":"code"}]},{"type":"text","text":" before installing dependencies","marks":[{"type":"bold"}]},{"type":"text","text":" – every code change reinstalls everything."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A container running as root","marks":[{"type":"bold"}]},{"type":"text","text":" – a vulnerability in the app gives the attacker root in the container and an easier path to the host."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"version:","marks":[{"type":"code"}]},{"type":"text","text":" at the top of ","marks":[{"type":"bold"}]},{"type":"text","text":"compose.yaml","marks":[{"type":"code"}]},{"type":"text","text":" – the field is obsolete and ignored; modern Compose does not need it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Database data without a volume","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"docker compose down","marks":[{"type":"code"}]},{"type":"text","text":" and the database disappears with the container."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"One container with the API, the database and cron","marks":[{"type":"bold"}]},{"type":"text","text":" – one process per container; compose or an orchestrator handles the rest."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"check-yourself"},"content":[{"type":"text","text":"Check yourself"}]},{"type":"quiz","attrs":{"question":"You change one line in `src/app.controller.ts`. Which instruction order gives the fastest rebuild?","multiple":false,"options":[{"text":"`COPY . .`, then `RUN npm ci`, then `RUN npm run build`","correct":false,"explanation":"Copying the whole directory invalidates the `npm ci` layer on every code change."},{"text":"`COPY package.json package-lock.json ./`, `RUN npm ci`, then `COPY src ./src` and `RUN npm run build`","correct":true,"explanation":"Yes. The dependency layer stays cached; only compilation is rebuilt."},{"text":"Order does not matter with BuildKit","correct":false,"explanation":"BuildKit caches layers, but invalidates everything after the first changed one."}]}},{"type":"quiz","attrs":{"question":"Why is `CMD npm start` (shell form) worse than `CMD [\"node\", \"dist/main.js\"]`?","multiple":false,"options":[{"text":"Because npm is slower than node","correct":false,"explanation":"The startup difference is negligible."},{"text":"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`","correct":true,"explanation":"Yes. In exec form Node is PID 1, receives the signal directly and can close its connections."},{"text":"Because the shell form does not support environment variables","correct":false,"explanation":"It does – which is exactly why it is tempting."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: \"How do you build a secure and small image for a Node.js application?\""}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"A multi-stage Dockerfile: a dependency stage copies only "},{"type":"text","text":"package.json","marks":[{"type":"code"}]},{"type":"text","text":" and the lockfile and runs "},{"type":"text","text":"npm ci","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"dist","marks":[{"type":"code"}]},{"type":"text","text":", production "},{"type":"text","text":"node_modules","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"package.json","marks":[{"type":"code"}]},{"type":"text","text":". The process runs as an ordinary user, CMD is in exec form, the app handles "},{"type":"text","text":"SIGTERM","marks":[{"type":"code"}]},{"type":"text","text":", and there is a healthcheck. "},{"type":"text","text":".dockerignore","marks":[{"type":"code"}]},{"type":"text","text":" excludes "},{"type":"text","text":"node_modules","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":".git","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":".env","marks":[{"type":"code"}]},{"type":"text","text":"; I pass build secrets with "},{"type":"text","text":"--mount=type=secret","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"what-next"},"content":[{"type":"text","text":"What next"}]},{"type":"linkCard","attrs":{"url":"/en/articles/kubernetes-basics","title":"Kubernetes basics","description":"The same images in a cluster: Deployment, Service, probes, HPA","kind":"article","ref":"kubernetes-basics"}},{"type":"linkCard","attrs":{"url":"/en/articles/kubernetes-production","title":"Kubernetes in production","description":"Helm, RBAC, NetworkPolicy, autoscaling and GitOps","kind":"article","ref":"kubernetes-production"}},{"type":"linkCard","attrs":{"url":"/en/articles/nodejs-runtime","title":"Node.js under the hood","description":"Signals, memory and the event loop of a containerized process","kind":"article","ref":"nodejs-runtime"}},{"type":"linkCard","attrs":{"url":"/en/topics/secure-sdlc","title":"Secure SDLC","description":"Scanning, SBOM and the supply chain in practice","kind":"topic","ref":"secure-sdlc"}}]},"toc":[{"id":"image-container-layers","text":"Image, container, layers","level":2,"locked":false},{"id":"step-1-the-application-and-the-starting-point","text":"Step 1. The application and the starting point","level":2,"locked":false},{"id":"step-2-a-multi-stage-dockerfile-for-nestjs","text":"Step 2. A multi-stage Dockerfile for NestJS","level":2,"locked":false},{"id":"pid-1-signals-and-the-healthcheck","text":"PID 1, signals and the healthcheck","level":3,"locked":false},{"id":"step-3-frontend-vite-nginx-without-root","text":"Step 3. Frontend: Vite + nginx without root","level":2,"locked":false},{"id":"step-4-docker-compose-for-developers","text":"Step 4. docker compose for developers","level":2,"locked":false},{"id":"step-5-image-scanning-and-the-supply-chain","text":"Step 5. Image scanning and the supply chain","level":2,"locked":false},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":false},{"id":"check-yourself","text":"Check yourself","level":2,"locked":false},{"id":"what-next","text":"What next","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":52,"visibleBlocks":52,"resources":[{"id":"6b0857b23c96f2d34d0b34d4","type":"repo","provider":"github","url":"https://github.com/Haxxnet/Compose-Examples","embedUrl":null,"title":"Haxxnet/Compose-Examples","description":"Various Docker Compose examples of selfhosted FOSS and proprietary projects.","author":"Haxxnet","thumbnailUrl":"https://opengraph.githubassets.com/1/Haxxnet/Compose-Examples","durationSec":null,"lang":"en","topics":["microservices"],"techs":["general"],"tags":["automation","awesome","awesome-docker","compose","compose-files","container","devops","containerization","docker","docker-compose"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-02-13T20:49:59.000Z","popularity":75,"verifiedAt":"2026-11-26T10:58:32.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"},{"id":"6b0857c63c96f2d34d0b48c9","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=iv32wI3MBpw","embedUrl":"https://www.youtube-nocookie.com/embed/iv32wI3MBpw","title":"Software Supply Chain Security: What AI Coding Changes","description":"Learn more about Supply Chain Security here → https://ibm.biz/~k518Rj9sC Your code is only part of what reaches production. Cedric Clyburn explains how dependencies, CI/CD pipelines, open source, and AI-generated code expand the software supply chain. Learn how SBOMs, automated checks, independent…","author":"IBM Technology","thumbnailUrl":"https://i.ytimg.com/vi/iv32wI3MBpw/hqdefault.jpg","durationSec":null,"lang":"en","topics":["ai-coding-assistants"],"techs":["general"],"tags":["security","devops","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-11-16T14:45:14.000Z","popularity":69,"verifiedAt":"2026-11-26T10:59:34.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bb3c96f2d34d0b3f81","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/time-to-exploit-is-negative-ai-broke-the-patch-cycle/id1776879655?i=1000784344048","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1776879655?i=1000784344048","title":"Time to Exploit is Negative: AI Broke the Patch Cycle | Dan Lorenc, Chainguard","description":"Attackers used to take months, sometimes 270 days, to weaponize a disclosed vulnerability. Now it happens in weeks, minutes if the incentive is there, and independent reports from Mandiant and CrowdStrike show the average time to exploit has gone negative. Full transcript and chapters…","author":"Chain of Thought | AI Agents, Infrastructure & Engineering","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/8a/54/ab/8a54ab02-a542-e9e4-20fe-c0044e3a72fe/mza_2334570213970843770.jpg/600x600bb.jpg","durationSec":2831,"lang":"en","topics":[],"techs":["general"],"tags":["podcast","security","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2026-08-19T12:48:53.000Z","popularity":49,"verifiedAt":"2026-11-26T11:06:30.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:57.868Z","updatedAt":"2026-11-26T16:00:57.868Z"},{"id":"6b0857b13c96f2d34d0b3399","type":"repo","provider":"github","url":"https://github.com/goldbergyoni/nodebestpractices","embedUrl":null,"title":"goldbergyoni/nodebestpractices","description":"✅ The Node.js best practices list (July 2026)","author":"goldbergyoni","thumbnailUrl":"https://opengraph.githubassets.com/1/goldbergyoni/nodebestpractices","durationSec":null,"lang":"en","topics":["microservices"],"techs":["node","javascript"],"tags":["best-practices","es6","eslint","express","expressjs","javascript","testing","jest","microservices","mocha"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2017-09-15T08:33:19.000Z","popularity":97,"verifiedAt":"2026-11-26T10:52:30.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857bf3c96f2d34d0b4255","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/microservices/design/orchestration","embedUrl":null,"title":"Container orchestration for microservices","description":"Learn how container orchestration makes it easy to manage complex multi-container microservice deployments, scaling, and cluster health.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":["microservices"],"techs":["general"],"tags":["azure","cloud","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":67,"verifiedAt":"2026-11-26T11:07:37.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":46}]}}