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
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:
docker build -t cowsay .
docker run --rm cowsay # prints "Hello from Docker"
docker run --rm cowsay "Moo" # arguments replace CMDEach 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
| Instruction | What it does |
|---|---|
FROM | Starts a build stage from a base image |
RUN | Runs a command at build time and saves the result as a layer |
WORKDIR | Sets the working directory for the instructions after it |
SHELL | Changes the shell used by shell-form commands |
COPY | Copies files from the build context or another stage |
ADD | Like COPY, plus remote URLs, Git repos and auto-extracting archives |
ENV | Sets environment variables for the build and the running container |
ARG | Declares a build-time variable |
CMD | Default command, or default arguments for ENTRYPOINT |
ENTRYPOINT | The executable the container always runs |
USER | Sets the user for the instructions after it and for the container |
STOPSIGNAL | Sets the signal sent to stop the container |
EXPOSE | Documents the ports the container listens on |
VOLUME | Declares a mount point for persistent data |
HEALTHCHECK | Tells Docker how to check that the container still works |
LABEL | Adds metadata to the image |
ONBUILD | Registers 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.
FROM node:24-alpineAlways 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 andapk. Small, but some prebuilt binaries expect glibc.debian:trixie-slim: glibc andaptat a fraction of the size ofubuntu.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:
docker build --pull -t myapp .RUN
RUN executes a command in a new layer on top of the current image and commits the result.
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:
RUN --mount=type=cache,target=/root/.npm npm ciWORKDIR
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.
WORKDIR /app
COPY . .
RUN npm ciUse 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:
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN curl -fsSL https://example.com/install.sh | bashAdding 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.
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/filedoesn'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.
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 filePrefer 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.
ENV NODE_ENV=production \
PORT=3000Use 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:
ARG NODE_VERSION=24
FROM node:${NODE_VERSION}-alpine
ARG APP_VERSION=dev
LABEL org.opencontainers.image.version=$APP_VERSIONdocker 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.
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 receivesSIGTERMfromdocker stopand 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 forwardSIGTERM, 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:
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:
#!/bin/sh
set -e
# Wait for the database, run migrations, render config files...
php artisan migrate --force
exec "$@"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.
RUN groupadd --system app && useradd --system --gid app --no-create-home app
USER appWithout 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:
STOPSIGNAL SIGQUITPorts, 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.
EXPOSE 3000
EXPOSE 53/udpPorts 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.
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.
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD curl -fsS http://localhost:3000/health || exit 1The 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:
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:
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:
.git
node_modules
dist
*.log
.env
DockerfileThe 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:
COPY package.json package-lock.json ./
RUN npm ci # cached until the dependencies change
COPY . . # changes on every commit
RUN npm run buildTo 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:
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:
TAG=$(git rev-parse --short HEAD)
docker build -t myapp:$TAG .
docker tag myapp:$TAG myapp:latestOther ways to create images
docker commitsaves 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 saveanddocker loadwrite 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 exportanddocker importdo the same for a container's filesystem, flattened into a single layer and without metadata such asCMDorENV.
docker save -o myapp.tar myapp:1.4.2
docker load -i myapp.tarWrapping 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.
