Dockerfile Cheat Sheet: Instructions, Multi-Stage Builds and Cache Mounts
Checked against Dockerfile Dockerfile frontend 1.29.0 (docker/dockerfile:1) on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for anyone writing or reviewing a Dockerfile who wants the instructions, their flags and the habits that keep images small and builds fast. It follows the Dockerfile reference and Docker's build best-practices pages as of 28 Nov 2026, when the newest Dockerfile frontend was 1.29.0. Docker isn't allowed in the shell used to write it, so the rows are checked against the docs, not run.
When to use what
Start every Dockerfile with # syntax=docker/dockerfile:1. That line makes BuildKit fetch the latest stable 1.x frontend, so flags like COPY --link or RUN --mount work even on an older Docker engine.
Use COPY unless you need what only ADD does: fetching a URL or git repository, or unpacking a local tar archive. Docker's best-practices page also points you to COPY for moving files between stages, and it is easier to read because it does one thing.
Write ENTRYPOINT and CMD in exec form, the JSON array with double quotes. In shell form your program runs under /bin/sh -c, so it isn't PID 1 and won't get the SIGTERM that docker stop sends; the container then sits until it's killed. A common pattern is ENTRYPOINT for the executable and CMD for default arguments people can override.
For anything compiled or bundled, use a multi-stage build: install tools and build in one stage, then COPY --from only the output into a small runtime image. Add RUN --mount=type=cache for package manager caches so rebuilds don't download everything again. The Docker multi-stage builds guide walks through a full example, the Dockerfile generator gives you a starting file per language, and the Dockerfile linter catches common problems before you build.
An ARG declared before the first FROM can be used in FROM lines only. To use it inside a stage, declare ARG NAME again (without a value) after that FROM.
# syntax=docker/dockerfile:1First line of the file: build with the latest stable 1.x Dockerfile frontend
FROM node:22-slim AS buildStart a stage from a base image and name it so later stages can copy from it
FROM python:3.13-slim@sha256:<digest>Pin the base image by digest so a re-pushed tag can't change your build
ARG NODE_VERSION=22Declare a build argument with a default; override it with --build-arg at build time
ENV NODE_ENV=productionSet an environment variable for later instructions and for the running container
WORKDIR /appSet the working directory for later instructions, creating it if needed
USER 10001:10001Run later instructions and the container as a non-root user and group ID
Put apt-get update and apt-get install in the same RUN, then delete /var/lib/apt/lists/*. Split across two RUN lines, the cached update layer goes stale and installs old packages.
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Install packages in one layer and clean the apt lists so they don't bloat the image
RUN set -o pipefail && wget -O - https://example.com | wc -lMake a piped command fail when any stage of the pipe fails, not just the last one
COPY package.json package-lock.json ./Copy dependency manifests first so the install layer stays cached until they change
COPY --chown=10001:10001 --chmod=755 entrypoint.sh /usr/local/bin/Copy a file and set its owner and permissions in the same step
COPY --exclude=*.md docs/ /docs/Copy a directory but skip files that match a pattern (syntax 1.19+)
COPY --link dist/ /app/dist/Copy into an independent layer that can be reused with --cache-from even when earlier layers changed (syntax 1.4+)
ADD --checksum=sha256:<hash> https://example.com/tool.tar.gz /tmp/Download a remote file and fail the build if its checksum doesn't match
ADD https://github.com/org/repo.git#v1.2.0 /srcClone a git repository at a tag into the image without installing git
HEALTHCHECK defaults: interval 30s, timeout 30s, start period 0s, start interval 5s, retries 3. Only the last CMD and the last HEALTHCHECK in a file take effect.
ENTRYPOINT ["/usr/local/bin/server"]Exec form: run the binary directly as PID 1 so it receives stop signals
CMD ["--port", "8080"]Default arguments appended to the ENTRYPOINT; docker run image --port 9000 replaces them
CMD node server.jsShell form: runs under /bin/sh -c, which expands variables but doesn't forward signals to node
EXPOSE 8080/tcpDocument the port the app listens on; it doesn't publish the port, -p does that
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/health || exit 1Mark the container unhealthy when the health endpoint stops answering
STOPSIGNAL SIGQUITChange the signal docker stop sends; the default is SIGTERM
FROM golang:1.26 AS buildName the build stage that has the compiler and dev tools
COPY --from=build /bin/app /bin/appCopy only the build output from a named stage into the final image
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.confCopy a file out of another image without making it a stage
docker build --target build -t app:build .Stop at a named stage, for example to run tests inside the build environment
Mounts exist only while that RUN executes, so nothing in them ends up in an image layer. That's why secrets belong in a secret mount, not in ARG or ENV.
RUN --mount=type=cache,target=/root/.cache/go-build go build -o /bin/app .Keep the Go build cache between builds without storing it in the image
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked apt-get update && apt-get install -y gccShare an apt cache across builds; sharing=locked stops parallel builds from colliding
RUN --mount=type=secret,id=API_KEY,env=API_KEY ./fetch-deps.shExpose a build secret as an environment variable for one command only
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials aws s3 cp s3://bucket/file .Mount a secret file at a path for one command; pass it with docker build --secret id=aws,src=...
RUN --mount=type=bind,target=. go build -o /bin/appRead the build context in place instead of copying it into a layer
RUN --mount=type=ssh git clone [email protected]:org/private.gitUse the host's SSH agent to fetch private repositories during the build
The .dockerignore file lives at the root of the build context. With several Dockerfiles, put name.Dockerfile.dockerignore next to each one and it takes priority.
node_modules
.git
*.logKeep dependencies, git history and logs out of the build context
**/*.tmp** matches any number of directories, including none
*.md
!README.mdIgnore all Markdown files except README.md; later lines override earlier ones
docker build --check .Run the Dockerfile checks and report warnings without building
# check=error=trueParser directive at the top of the Dockerfile that turns check warnings into build failures
# check=skip=JSONArgsRecommendedSilence one named check for this Dockerfile
Worked example: A small, cache-friendly image for a Node.js app
Goal: a production image that rebuilds fast when only source changes, runs as non-root and stops cleanly.
# syntax=docker/dockerfile:1
# check=error=true
FROM node:22-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
FROM node:22-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
# .dockerignore
node_modules
.git
dist
*.log
How it behaves: the deps stage installs only production packages, and its layer is reused until a lockfile changes. The build stage has dev dependencies and the source, but none of it reaches the final image except dist. The npm cache mount means a lockfile change still doesn't download every package again. The final stage runs as the node user that the official image provides, and the exec-form CMD makes node PID 1, so docker stop ends it with SIGTERM instead of waiting for the kill timeout. When you edit a source file and rebuild, look for the deps steps reported as cached and only the COPY . . step onward running again. The check=error=true line makes the build fail on any check warning. This wasn't built here, because Docker isn't available in this shell.
Common mistakes
Writing
CMD npm startin shell form and then wondering whydocker stoptakes ten seconds.Use the exec form,
CMD ["node", "server.js"], so the app is PID 1 and gets SIGTERM. Calling node directly also skips npm as an extra process in the middle.Running
COPY . .before installing dependencies.Copy the lockfile and manifest first, install, then copy the rest. Otherwise every source edit throws away the dependency layer.
Passing tokens with
ARGorENVso aRUNstep can use them.Build args show up in
docker historyand in provenance attestations, and ENV values stay in the image. UseRUN --mount=type=secretanddocker build --secretinstead.Declaring
ARG VERSION=1.0aboveFROMand using$VERSIONin a laterRUN, where it comes out empty.Repeat
ARG VERSIONafter theFROM. An ARG declared before the first FROM is only visible to FROM lines.Splitting
apt-get updateandapt-get installinto twoRUNlines.Combine them in one
RUNand delete/var/lib/apt/lists/*in the same step, so the update is never served from a stale cache.Shipping without a
.dockerignore, so.git,node_modulesand local.envfiles go into the build context.Add a
.dockerignoreat the context root listing them. It speeds up builds and keeps secrets out ofCOPY . ..
Related cheat sheets
Sources
- https://docs.docker.com/reference/dockerfile/
- https://docs.docker.com/build/building/best-practices/
- https://docs.docker.com/build/building/multi-stage/
- https://docs.docker.com/build/concepts/context/
- https://docs.docker.com/build/cache/optimize/
- https://docs.docker.com/build/checks/
- https://github.com/moby/buildkit/releases/tag/dockerfile%2F1.29.0
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.