Dockerfile Best Practices
Write small, deterministic, and secure container images using pinned tags, non-root users, .dockerignore, layer ordering, healthchecks, and BuildKit secrets.
TL;DR
Keep production images small, reproducible, and least-privileged: pin base image tags, exclude junk with .dockerignore, order layers from least- to most-frequently changed, run as a non-root USER, use HEALTHCHECK, and never bake secrets into ARG or ENV.
Why it exists
A naive Dockerfile (FROM node:latest, COPY . ., RUN npm install as root) produces bloated images, busts the build cache on every edit, leaks .git or .env files into layers, and gives an attacker root inside the container if the app is compromised.
Mental model
Every Dockerfile instruction creates an immutable layer. Anything written in an earlier layer stays in the image history even if deleted later, and any change to an instruction invalidates the cache for every instruction after it.
labs/docker-multistage-nextWorking multi-stage Dockerfile with pinned Alpine tag, non-root user, and .dockerignore — linted with hadolint in CI.
docker build -t mt-multistage-next:lab labs/docker-multistage-nextThe core practices
1. Pin base image tags and keep images small
Avoid floating tags like :latest. Pin a specific runtime and OS variant (or even a SHA256 digest in strict environments), and use multi-stage builds so compilers and devDependencies stay out of the final image.
# syntax=docker/dockerfile:1
FROM node:22-alpine3.21 AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts2. Order layers for cache hits
Put instructions that rarely change (base image, OS packages, lockfile + dependency install) above COPY . . so editing application code does not re-download dependencies.
3. Filter the build context with .dockerignore
Without .dockerignore, COPY . . sends node_modules, .git, build artifacts, and local .env files to the Docker daemon.
.git
node_modules
.next
out
.env*
*.log4. Run as a non-root USER
Create a dedicated system user and group, and use COPY --chown so the runtime user owns only what it needs without adding an extra chown -R layer.
FROM node:22-alpine3.21 AS runner
WORKDIR /app
RUN addgroup -g 1001 -S nodejs \
&& adduser -S nextjs -u 1001 -G nodejs
COPY --from=deps --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --chown=nextjs:nodejs server.mjs ./
USER nextjs5. Add a HEALTHCHECK
A HEALTHCHECK lets Docker (and Compose) distinguish a container whose process is merely alive from one that is actually serving traffic.
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget -qO- http://127.0.0.1:3000/healthz || exit 16. Pass build-time secrets with --mount=type=secret
Never use ARG or ENV for tokens or private registry credentials — both are recorded in image metadata (docker history). Use a BuildKit secret mount instead; it is mounted only for that RUN step and never persisted to any layer.
# not run (example requiring a secret file)
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
npm ci --omit=dev# not run
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:1.0.0 .Gotchas
- Deleting secrets in a later
RUN:RUN rm /tmp/tokendoes not remove the secret from the earlier layer; use--mount=type=secretfrom the start. apt-get updatewithoutinstallin the sameRUN: Splitting them caches a stale package index. Always combineapt-get update && apt-get install -y --no-install-recommends ... && rm -rf /var/lib/apt/lists/*.- Using
ADDinstead ofCOPY:ADDsilently unpacks local tarballs and fetches remote URLs; preferCOPYunless you explicitly want tar extraction.
Production checklist
- Base image tag is pinned (no
:latest) and final stage uses a minimal base (alpine,distroless, orslim). -
.dockerignoreexcludes.git,node_modules, and.env*. - Manifests (
package.json, lockfile) are copied and installed before application source. - Container switches to a non-root
USERbeforeCMD/ENTRYPOINT. - Build-time credentials use
--mount=type=secret, neverARGorENV. -
hadolintpasses in CI (labs.ymlcheckslabs/*/Dockerfile).
Check yourself
Check Yourself
1. Why is ARG NPM_TOKEN unsafe for passing a private registry token during docker build?
2. Where should COPY package.json package-lock.json ./ appear relative to COPY . .?
Sources
Related Notes
Multi-Stage Builds for Next.js
Build a minimal production Node/Next.js-style container with a two-stage Dockerfile, non-root user, and .dockerignore.
Docker Compose
Run multi-container stacks locally or on a single host with automatic service DNS, health-gated depends_on, isolated networks, env files, secrets, and profiles.