Skip to the page

Docker for Node and Next.js apps · mid

Image security: small bases, non-root, no secrets

Secure images start from a small, trusted, regularly patched base, run as a non-root user, never contain secrets in any layer, and are scanned and rebuilt often so fixes in the base image actually reach production.

The notes

What you must know

  • Fewer packages = fewer CVEs: slim, alpine, distroless or Docker Hardened Images (made free and open source under Apache 2.0 in December 2025; non-root by default).
  • Secrets: anything in ARG, ENV or a COPY'd .env file is in the image layers or history. Use BuildKit secret mounts (RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci) for build-time secrets, and inject runtime secrets from the platform.
  • Run as non-root (USER node); consider a read-only root filesystem and dropped Linux capabilities in the orchestrator.
  • Scan images (Docker Scout, Trivy, ECR scanning) in CI and on a schedule; rebuild regularly to pick up base-image patches.
  • Pin versions (and, for strict supply-chain control, digests) for base images; use official or verified publisher images.
  • .dockerignore stops .git, .env and keys from entering the build context.

The red pen

Common traps: mistake → fix

  • Mistake: Deleting the .npmrc in a later RUN removes the token

    Fix: it is still in the earlier layer.

  • Mistake: Alpine is always the most secure choice

    Fix: it is small, but musl differences can break native modules; distroless or hardened images are alternatives.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you keep secrets out of Docker images?
  2. Why run containers as non-root?
  3. How do you keep base images patched across 40 services?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview