Skip to content

Menu

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:1

First line of the file: build with the latest stable 1.x Dockerfile frontend

From the docs, not run by us
FROM node:22-slim AS build

Start a stage from a base image and name it so later stages can copy from it

From the docs, not run by us
FROM python:3.13-slim@sha256:<digest>

Pin the base image by digest so a re-pushed tag can't change your build

From the docs, not run by us
ARG NODE_VERSION=22

Declare a build argument with a default; override it with --build-arg at build time

From the docs, not run by us
ENV NODE_ENV=production

Set an environment variable for later instructions and for the running container

From the docs, not run by us
WORKDIR /app

Set the working directory for later instructions, creating it if needed

From the docs, not run by us
USER 10001:10001

Run later instructions and the container as a non-root user and group ID

From the docs, not run by us

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

From the docs, not run by us
RUN set -o pipefail && wget -O - https://example.com | wc -l

Make a piped command fail when any stage of the pipe fails, not just the last one

From the docs, not run by us
COPY package.json package-lock.json ./

Copy dependency manifests first so the install layer stays cached until they change

From the docs, not run by us
COPY --chown=10001:10001 --chmod=755 entrypoint.sh /usr/local/bin/

Copy a file and set its owner and permissions in the same step

From the docs, not run by us
COPY --exclude=*.md docs/ /docs/

Copy a directory but skip files that match a pattern (syntax 1.19+)

From the docs, not run by us
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+)

From the docs, not run by us
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

From the docs, not run by us
ADD https://github.com/org/repo.git#v1.2.0 /src

Clone a git repository at a tag into the image without installing git

From the docs, not run by us

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

From the docs, not run by us
CMD ["--port", "8080"]

Default arguments appended to the ENTRYPOINT; docker run image --port 9000 replaces them

From the docs, not run by us
CMD node server.js

Shell form: runs under /bin/sh -c, which expands variables but doesn't forward signals to node

From the docs, not run by us
EXPOSE 8080/tcp

Document the port the app listens on; it doesn't publish the port, -p does that

From the docs, not run by us
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/health || exit 1

Mark the container unhealthy when the health endpoint stops answering

From the docs, not run by us
STOPSIGNAL SIGQUIT

Change the signal docker stop sends; the default is SIGTERM

From the docs, not run by us
FROM golang:1.26 AS build

Name the build stage that has the compiler and dev tools

From the docs, not run by us
COPY --from=build /bin/app /bin/app

Copy only the build output from a named stage into the final image

From the docs, not run by us
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf

Copy a file out of another image without making it a stage

From the docs, not run by us
docker build --target build -t app:build .

Stop at a named stage, for example to run tests inside the build environment

From the docs, not run by us

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

From the docs, not run by us
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked apt-get update && apt-get install -y gcc

Share an apt cache across builds; sharing=locked stops parallel builds from colliding

From the docs, not run by us
RUN --mount=type=secret,id=API_KEY,env=API_KEY ./fetch-deps.sh

Expose a build secret as an environment variable for one command only

From the docs, not run by us
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=...

From the docs, not run by us
RUN --mount=type=bind,target=. go build -o /bin/app

Read the build context in place instead of copying it into a layer

From the docs, not run by us
RUN --mount=type=ssh git clone [email protected]:org/private.git

Use the host's SSH agent to fetch private repositories during the build

From the docs, not run by us

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 *.log

Keep dependencies, git history and logs out of the build context

Try it: docker-ignore-generatorFrom the docs, not run by us
**/*.tmp

** matches any number of directories, including none

From the docs, not run by us
*.md !README.md

Ignore all Markdown files except README.md; later lines override earlier ones

From the docs, not run by us
docker build --check .

Run the Dockerfile checks and report warnings without building

Try it: Dockerfile LinterFrom the docs, not run by us
# check=error=true

Parser directive at the top of the Dockerfile that turns check warnings into build failures

From the docs, not run by us
# check=skip=JSONArgsRecommended

Silence one named check for this Dockerfile

From the docs, not run by us

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 start in shell form and then wondering why docker stop takes 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 ARG or ENV so a RUN step can use them.

    Build args show up in docker history and in provenance attestations, and ENV values stay in the image. Use RUN --mount=type=secret and docker build --secret instead.

  • Declaring ARG VERSION=1.0 above FROM and using $VERSION in a later RUN, where it comes out empty.

    Repeat ARG VERSION after the FROM. An ARG declared before the first FROM is only visible to FROM lines.

  • Splitting apt-get update and apt-get install into two RUN lines.

    Combine them in one RUN and 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_modules and local .env files go into the build context.

    Add a .dockerignore at the context root listing them. It speeds up builds and keeps secrets out of COPY . ..