Lesson 3 of 9 · 12 min · Building images

Writing a Dockerfile: instructions, caching and multi-stage builds

Covers: Docker Engine 29 with BuildKit; python 3.12-slim, golang 1.22-alpine. Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

What you will learn

  • The Dockerfile instructions you need, and CMD versus ENTRYPOINT
  • How the build cache works and how to order instructions for fast rebuilds
  • Multi-stage builds, with real image sizes
  • .dockerignore
  • A checklist for production Dockerfiles

In simple words

A Dockerfile is a recipe for an image. Each line is one step: start from this base, copy these files, install these packages, run this command. Docker follows the recipe and remembers each finished step, so the next build repeats only what changed. This lesson shows how to write a good one.

Words to know

  • Dockerfile: the text file of instructions that Docker follows to build an image.
  • Build: turning a Dockerfile and your code into an image.
  • Build cache: finished steps that Docker keeps and reuses, so rebuilds are fast.
  • Multi-stage build: building with all the tools in one stage and copying only the result into a small final image.

A Dockerfile is a recipe

A Dockerfile is a text file of instructions that docker build runs to produce an image. A complete example for a small Python web app:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 8000
CMD ["python", "app.py"]

Build and run:

docker build -t pyapp .              # the dot is the build context (the directory sent to the builder)
docker run -d --name py1 -p 18000:8000 pyapp
curl localhost:18000
hello from 1bf929eadf8f as uid 0

(That uid 0 is a hint for the security lesson: the app runs as root inside the container.)

The instructions

Instruction What it does
FROM image:tag the base image to start from (first line; FROM scratch is an empty base)
WORKDIR /app set (and create) the working directory for the following instructions and for the running container
COPY src dest copy files from the build context into the image. Prefer it over ADD
ADD like COPY but also unpacks local tar files and fetches URLs. Use only for the tar feature
RUN command run a command at build time and save the result as a new layer (install packages, compile)
ENV KEY=value set an environment variable for build and runtime. Visible in the image. Not for secrets
ARG NAME=default a build-time variable (--build-arg). Not available at runtime, but recorded in image history
EXPOSE 8000 documentation: the port the app listens on. It does not publish the port
USER app switch to a non-root user for later instructions and for the container
CMD [...] the default command when the container starts
ENTRYPOINT [...] the fixed executable; CMD becomes its default arguments
HEALTHCHECK a command Docker runs periodically to see whether the app is healthy
VOLUME, LABEL, STOPSIGNAL declare a volume mount point, add metadata, change the stop signal

CMD versus ENTRYPOINT

  • CMD ["python", "app.py"] is the default command; the user can replace it entirely with docker run image other-command.
  • ENTRYPOINT ["python"] plus CMD ["app.py"] makes the container behave like the python program, with app.py as a default argument that docker run image other.py replaces.
  • Use the exec form (JSON array) so the program is PID 1 and receives signals (lesson 1).
  • Use ENTRYPOINT for an image meant to behave like one tool, and CMD for services.

RUN: combine, and clean in the same layer

Each RUN creates a layer. Installing packages is the classic case:

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

Doing update, install and the cleanup in one RUN keeps the package index out of the layer and avoids the stale-cache bug where a cached apt-get update layer is reused with a new install line.

The build cache

For each instruction Docker checks whether it has already built a layer from the same instruction on the same parent layer (for COPY/ADD, with the same file contents). If yes it reuses it (CACHED). As soon as one layer changes, every layer after it is rebuilt.

We built our Python image three times. First from scratch (everything runs). Then again without changing anything:

#6 [2/5] WORKDIR /app
#6 CACHED
#7 [3/5] COPY requirements.txt .
#7 CACHED
#8 [4/5] RUN pip install --no-cache-dir -r requirements.txt
#8 CACHED

Then after editing only app.py: the WORKDIR, COPY requirements.txt and pip install steps were still CACHED; only COPY app.py and later steps ran. This is the result of a deliberate ordering: dependencies change rarely, source code changes constantly, so copy the dependency list and install first, and the source last.

Bad order (every code change reinstalls all dependencies):

COPY . .
RUN pip install -r requirements.txt

Good order (dependencies cached until requirements.txt changes):

COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

The same pattern applies to package.json + npm ci, pom.xml, go.mod and so on. Use docker build --no-cache to force a full rebuild (for example to pick up security updates in the base image), and in CI use a cache backend (--cache-from, registry cache) because CI runners start empty.

Multi-stage builds

Building software needs compilers, SDKs and build tools. Running it does not. A multi-stage build uses one stage to build and a clean final stage to run, copying in only the result.

A tiny Go web server built two ways. Single stage:

FROM golang:1.22-alpine
WORKDIR /src
COPY go.mod main.go ./
RUN go build -o /hello .
CMD ["/hello"]

Multi-stage:

FROM golang:1.22-alpine AS build
WORKDIR /src
COPY go.mod main.go ./
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /hello .

FROM scratch
COPY --from=build /hello /hello
USER 65534:65534
EXPOSE 8080
ENTRYPOINT ["/hello"]

Measured image sizes:

go-single  445MB
go-multi   6.87MB

The final image holds only the binary (scratch is an empty image): 65 times smaller, nothing to patch except the binary, no shell or package manager for an attacker to use. We confirmed: docker run --entrypoint sh go-multi fails because there is no shell. The same idea applies to every language:

  • Java: build with Maven in a JDK stage, run the jar on a JRE (or distroless) image.
  • Node: npm ci and build in one stage; copy dist/ and production node_modules to a slim image.
  • Python: build wheels in a stage with compilers, copy them to a slim runtime stage.
  • Frontend: build the static files in Node, serve them from nginx:alpine.

Name stages with AS and copy with --from=name. Build only a stage with --target build (handy for a test stage in CI).

.dockerignore

docker build . sends the whole directory (the build context) to the builder, and COPY . . copies everything. A .dockerignore file excludes paths, like .gitignore:

.git
.env
node_modules
__pycache__
*.log

Test with a .env file in the directory and COPY . /ctx, then list /ctx in the image. Without .dockerignore:

. .. .env Dockerfile a.txt

With .env in .dockerignore:

. .. .dockerignore Dockerfile a.txt

The secret file no longer ends up in the image. This also makes the context smaller (faster builds) and avoids invalidating the cache with irrelevant file changes.

A production Dockerfile checklist

  1. Pinned, small base image (specific version tag; slim, alpine or distroless where suitable).
  2. Multi-stage if you compile anything.
  3. Instructions ordered from least to most frequently changing.
  4. .dockerignore present.
  5. RUN steps combined and cleaned; --no-install-recommends and --no-cache-dir flags.
  6. A non-root USER.
  7. Exec-form CMD/ENTRYPOINT; the app logs to stdout.
  8. No secrets in ENV, ARG, COPY or layers.
  9. HEALTHCHECK or an equivalent probe in the orchestrator.
  10. Lint it with hadolint, and scan the built image (security lessons).

Common mistakes

  • COPY . . before installing dependencies, busting the cache on every edit.
  • Separate apt-get update and install layers.
  • Using latest base images.
  • Shell-form CMD.
  • Running as root, with a full build toolchain in the final image.
  • Believing EXPOSE publishes a port.
  • Putting secrets in build args (they show in docker history).

Try it yourself

  1. Containerise a small web app of your own. Build it three times: cold, with no change, and after editing one source file. Identify the CACHED steps.
  2. Reorder the Dockerfile badly (COPY . . first) and see how the rebuild time changes.
  3. Convert a single-stage Dockerfile for a compiled language to a multi-stage one and compare docker images sizes.
  4. Add a .dockerignore, prove with a RUN ls -a that the ignored files are gone.

Check yourself

Why copy requirements.txt and install dependencies before copying the rest of the code?

Docker caches each layer and invalidates later ones when a layer changes. Dependencies change rarely and code often, so installing dependencies first lets rebuilds after code edits reuse the cached dependency layer.

What is the difference between CMD and ENTRYPOINT?

ENTRYPOINT sets the executable that always runs, CMD sets default arguments or the default command, which docker run arguments replace. Together: ENTRYPOINT ["tool"] and CMD ["--help"].

What does EXPOSE 8000 do?

It only documents that the container listens on that port. Publishing to the host needs -p (or -P) at run time.

Why does a multi-stage build make images smaller and safer?

The final image contains only runtime artefacts, not compilers, source code or build tools, so there is less to download and less for an attacker to use or for scanners to flag.

Interview questions

A Docker build that used to take 10 seconds now takes 4 minutes on every code change. What happened?

The cache is being invalidated early: probably COPY . . precedes the dependency install, or a changing file (or ARG) comes before it. Reorder the Dockerfile so slow, stable steps come first.

How do you reduce a 1 GB image?

Smaller base image, multi-stage build, remove build tools and caches in the same layer, .dockerignore, install only runtime dependencies, and inspect docker history to see which layers are large.

Why combine apt-get update and apt-get install in one RUN?

If update is its own cached layer, a later change to the install line reuses the stale package index and can fail or install old versions. One RUN keeps them together and lets you delete the lists in the same layer.

Summary

  • A Dockerfile is a list of instructions; each RUN/COPY makes a layer; the cache reuses layers until one changes.
  • Order instructions from stable to volatile; combine and clean RUN steps; use .dockerignore.
  • Multi-stage builds ship only runtime artefacts: our example shrank from 445 MB to 6.9 MB.
  • Use pinned bases, exec-form CMD, a non-root user, and no secrets in layers.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Docker and containers for DevOps Engineer and scores every answer, with what to fix.