Andrew Dorokhov
DevOps & Infrastructure

The complete guide to Dockerfiles: building Docker images

How to write Dockerfiles that build small, fast, secure images: every instruction from FROM to ONBUILD with examples, plus caching and multi-stage builds.

Andrew DorokhovAndrew Dorokhov · 10 min read

A Dockerfile is a plain text file of instructions that Docker runs, top to bottom, to build an image. Most Dockerfiles use only five or six of them, but the less common ones (ARG, ONBUILD, HEALTHCHECK, SHELL) are exactly the ones you need to look up. This guide covers every instruction with a working example, then the parts of a build that decide its speed and size: the build context, the layer cache and multi-stage builds.

A minimal Dockerfile

Dockerfile
FROM debian:trixie-slim
RUN apt-get update && apt-get install -y --no-install-recommends cowsay \
    && rm -rf /var/lib/apt/lists/*
ENTRYPOINT ["/usr/games/cowsay"]
CMD ["Hello from Docker"]

Build it from the directory that contains the Dockerfile, then run it:

shell
docker build -t cowsay .
docker run --rm cowsay            # prints "Hello from Docker"
docker run --rm cowsay "Moo"      # arguments replace CMD

Each instruction that changes the filesystem (RUN, COPY, ADD) creates a read-only layer, a diff on top of the layer before it. The image is that stack of layers plus metadata such as the default command, environment and exposed ports.

Instructions at a glance

InstructionWhat it does
FROMStarts a build stage from a base image
RUNRuns a command at build time and saves the result as a layer
WORKDIRSets the working directory for the instructions after it
SHELLChanges the shell used by shell-form commands
COPYCopies files from the build context or another stage
ADDLike COPY, plus remote URLs, Git repos and auto-extracting archives
ENVSets environment variables for the build and the running container
ARGDeclares a build-time variable
CMDDefault command, or default arguments for ENTRYPOINT
ENTRYPOINTThe executable the container always runs
USERSets the user for the instructions after it and for the container
STOPSIGNALSets the signal sent to stop the container
EXPOSEDocuments the ports the container listens on
VOLUMEDeclares a mount point for persistent data
HEALTHCHECKTells Docker how to check that the container still works
LABELAdds metadata to the image
ONBUILDRegisters an instruction to run when the image is used as a base

Base image and build steps

Every build starts from a base image and runs commands on top of it.

FROM

FROM starts a new build stage and sets its base image. It must be the first instruction, apart from comments, parser directives and ARGs used in the FROM line itself.

dockerfile
FROM node:24-alpine

Always pin a tag. Without one Docker uses latest, and the same Dockerfile builds a different image next month. Common bases:

  • alpine: a few megabytes, uses musl libc and apk. Small, but some prebuilt binaries expect glibc.
  • debian:trixie-slim: glibc and apt at a fraction of the size of ubuntu.
  • scratch: an empty filesystem, for statically linked binaries such as Go programs.

When the base image is already present locally, docker build uses it without checking for a newer version. Pull it explicitly, or build with --pull, to pick up security fixes:

shell
docker build --pull -t myapp .

RUN

RUN executes a command in a new layer on top of the current image and commits the result.

dockerfile
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl ca-certificates \
    && rm -rf /var/lib/apt/lists/*

Chain related commands with && in one RUN. A file deleted in a later layer still takes space in the earlier one, so cleanup must happen in the same RUN that created the files. Running apt-get update in its own RUN is a classic bug: the cached layer keeps the old package index, and later installs fail or get stale versions.

With BuildKit (the default builder) a RUN can mount a cache directory that persists between builds without ending up in the image:

dockerfile
RUN --mount=type=cache,target=/root/.npm npm ci

WORKDIR

WORKDIR sets the working directory for every RUN, CMD, ENTRYPOINT, COPY and ADD after it. Docker creates the directory if it doesn't exist. A relative path is resolved against the previous WORKDIR.

dockerfile
WORKDIR /app
COPY . .
RUN npm ci

Use WORKDIR instead of RUN cd /app && ...: a cd only lasts for that one RUN.

SHELL

SHELL changes the shell used by shell-form RUN, CMD and ENTRYPOINT. The default on Linux is ["/bin/sh", "-c"]. Switching to bash with pipefail makes a pipeline fail when any command in it fails, not only the last one:

dockerfile
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN curl -fsSL https://example.com/install.sh | bash

Adding files

Two instructions put files into the image. In most cases you want the first one.

COPY

COPY copies files and directories from the build context into the image.

dockerfile
COPY package.json package-lock.json ./
COPY src/ /app/src/
COPY --chown=node:node --chmod=644 config.json /app/
  • The source must be inside the build context; ../shared/file doesn't work.
  • When the source is a directory, its contents are copied, not the directory itself.
  • A destination ending in / is treated as a directory.
  • Use the JSON form, COPY ["my file.txt", "/app/"], for paths with spaces.
  • COPY --from=<stage> copies from an earlier build stage or any image (see multi-stage builds).

ADD

ADD does everything COPY does, plus three things: it downloads remote URLs, clones Git repositories, and unpacks local tar archives into the destination.

dockerfile
ADD https://example.com/tool-1.4.tar.gz /tmp/
ADD --checksum=sha256:24454f830cdd... https://example.com/tool-1.4.tar.gz /tmp/
ADD https://github.com/moby/buildkit.git#v0.14.0 /src/buildkit
ADD vendor.tar.gz /opt/vendor/   # extracted, not copied as a file

Prefer COPY for local files: it does only what it says. Use ADD when you actually want the download or the extraction, and pin downloads with --checksum.

Variables

ENV values stay in the image; ARG values exist only while it builds.

ENV

ENV sets environment variables. They're available to the instructions after it and inside the running container.

dockerfile
ENV NODE_ENV=production \
    PORT=3000

Use the KEY=value form. The older ENV KEY value form still works but is deprecated. Variables set with ENV are baked into the image and visible with docker inspect, so never put secrets in them.

ARG

ARG declares a variable that exists only during the build. Pass a value with --build-arg, or rely on the default:

dockerfile
ARG NODE_VERSION=24
FROM node:${NODE_VERSION}-alpine
 
ARG APP_VERSION=dev
LABEL org.opencontainers.image.version=$APP_VERSION
shell
docker build --build-arg APP_VERSION=1.4.2 -t myapp:1.4.2 .

An ARG declared before FROM can only be used in FROM lines. To use it inside a stage, declare it again (without a value) after the FROM. Build args are also recorded in the image history, so pass secrets with RUN --mount=type=secret instead.

What the container runs

These instructions decide which process starts, as which user, and how it is stopped.

CMD

CMD sets the default command for the container. Only the last CMD in the Dockerfile counts, and arguments to docker run after the image name replace it.

dockerfile
CMD ["node", "server.js"]

There are two forms, and the difference matters:

  • Exec form, CMD ["node", "server.js"]: runs the program directly as PID 1, so it receives SIGTERM from docker stop and can shut down cleanly.
  • Shell form, CMD node server.js: runs /bin/sh -c "node server.js". Depending on the shell, the shell itself stays PID 1 and doesn't forward SIGTERM, so the app never hears about the stop and is killed after the timeout.

Use the exec form unless you need shell features such as variable expansion or pipes.

ENTRYPOINT

ENTRYPOINT sets the executable the container always runs. Arguments to docker run don't replace it; they're appended to it, replacing CMD. Together, ENTRYPOINT is the command and CMD is its default arguments:

dockerfile
ENTRYPOINT ["/usr/games/cowsay"]
CMD ["Hello"]

A common pattern is an entrypoint script that prepares the environment, then hands over to the main process with exec, so that process becomes PID 1:

docker-entrypoint.sh
#!/bin/sh
set -e
 
# Wait for the database, run migrations, render config files...
php artisan migrate --force
 
exec "$@"
dockerfile
COPY --chmod=755 docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["php-fpm"]

To replace the entrypoint for one run, for example to open a shell, use docker run --entrypoint sh -it myapp. Setting ENTRYPOINT also resets any CMD inherited from the base image, so set CMD again if you need one.

USER

USER sets the user, and optionally the group, for the RUN, CMD and ENTRYPOINT instructions after it and for the running container.

dockerfile
RUN groupadd --system app && useradd --system --gid app --no-create-home app
USER app

Without USER, processes in the container run as root. UIDs are shared between the container and the host kernel, so a process that escapes a root container can be root on the host. Create a dedicated user and switch to it after the steps that need root, such as installing packages. Official images often ship one already, like node in the Node.js images.

STOPSIGNAL

STOPSIGNAL sets the signal docker stop sends to PID 1. The default is SIGTERM. Change it for programs that shut down gracefully on something else; Nginx, for example, finishes open requests on SIGQUIT:

dockerfile
STOPSIGNAL SIGQUIT

Ports, volumes and health checks

These describe how the running container talks to the outside world and how Docker can tell it works.

EXPOSE

EXPOSE documents the ports the application listens on. It doesn't publish anything.

dockerfile
EXPOSE 3000
EXPOSE 53/udp

Ports are published at run time: -p 8080:3000 maps a specific host port, and -P maps every exposed port to a random host port.

VOLUME

VOLUME marks a path as a mount point for data that should outlive the container, such as a database directory.

dockerfile
VOLUME ["/var/lib/postgresql/data"]

If you don't mount anything there, Docker creates an anonymous volume on every docker run, and those pile up unnoticed. A Dockerfile can't bind a host directory; that's done at run time with -v or in Compose. Many images leave VOLUME out and let users mount what they need.

HEALTHCHECK

HEALTHCHECK tells Docker how to test that the application inside still works, not just that the process is running. The container's status becomes healthy or unhealthy, which Swarm, Compose's depends_on: condition: service_healthy and monitoring tools use.

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD curl -fsS http://localhost:3000/health || exit 1

The command must exit with 0 when healthy and 1 when not. Make sure the tool it calls (curl here) exists in the image.

Metadata and base images

The last two instructions don't change what runs: they describe the image and shape the images built from it.

LABEL

LABEL adds key-value metadata to the image. Use the standard OCI keys so registries and scanners can read them:

dockerfile
LABEL org.opencontainers.image.source="https://github.com/acme/myapp" \
      org.opencontainers.image.description="Billing API" \
      org.opencontainers.image.licenses="MIT"

Read them back with docker inspect --format '{{json .Config.Labels}}' myapp.

ONBUILD

ONBUILD stores an instruction that runs later, when another Dockerfile uses this image in its FROM. It suits base images for a team's projects, which always copy and build the code the same way:

dockerfile
FROM node:24-alpine
WORKDIR /app
ONBUILD COPY package*.json ./
ONBUILD RUN npm ci
ONBUILD COPY . .

The triggers run right after the child's FROM and are not passed on to grandchildren. They also hide steps from whoever reads the child Dockerfile, which is why ONBUILD is rarely used today.

Building fast, small images

The instructions decide what goes into an image. How you organize the build decides how fast it runs and how big the result is.

The build context and .dockerignore

The build context is the set of files docker build sends to the builder: the directory you pass, . in the examples above. COPY and ADD can only read from it. A large context (a .git folder, node_modules, build output) slows every build and can leak files into the image.

Exclude what the image doesn't need in a .dockerignore file next to the Dockerfile:

.dockerignore
.git
node_modules
dist
*.log
.env
Dockerfile

The layer cache

Docker reuses a cached layer when the instruction and its inputs haven't changed. For COPY and ADD, the inputs are the files' contents. Once one layer changes, every layer after it is rebuilt. So order instructions from the least to the most frequently changed, and copy dependency manifests before the source code:

dockerfile
COPY package.json package-lock.json ./
RUN npm ci              # cached until the dependencies change
COPY . .                # changes on every commit
RUN npm run build

To ignore the cache entirely, build with docker build --no-cache ..

Multi-stage builds

A multi-stage build compiles in one stage and copies only the result into a clean final stage. Compilers, dev dependencies and source code stay out of the image you ship:

dockerfile
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
 
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

Build both stages from the same base family. node_modules copied from a Debian-based stage into an Alpine one breaks as soon as a package has a native addon, because it was compiled against glibc and Alpine uses musl.

docker build --target build . stops at a named stage, which is handy for running tests in CI.

Tagging images

A tag like latest doesn't tell you which code is inside. Tag each build with the Git commit it was built from, then move latest if you use it:

shell
TAG=$(git rev-parse --short HEAD)
docker build -t myapp:$TAG .
docker tag myapp:$TAG myapp:latest

Other ways to create images

  • docker commit saves a running container's filesystem as a new image. It can save the state of a debugging session, but the result can't be rebuilt or reviewed, so don't use it for images you ship.
  • docker save and docker load write an image, with all its layers and tags, to a tar archive and read it back. Use them to move images to a machine without registry access.
  • docker export and docker import do the same for a container's filesystem, flattened into a single layer and without metadata such as CMD or ENV.
shell
docker save -o myapp.tar myapp:1.4.2
docker load -i myapp.tar

Wrapping up

Most of a good Dockerfile comes down to a few habits: pin the base image, use exec-form CMD and ENTRYPOINT, order instructions for the cache, keep secrets out of ENV and ARG, run as a non-root USER, and use a multi-stage build so the final image carries only what runs in production.

Need this built for your project?

Send a short brief and get an estimate within 24 hours.