Lesson 3 of 9 · 12 min · Building images
Writing a Dockerfile: instructions, caching and multi-stage builds
What you will learn
- The Dockerfile instructions you need, and
CMDversusENTRYPOINT - 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 withdocker run image other-command.ENTRYPOINT ["python"]plusCMD ["app.py"]makes the container behave like thepythonprogram, withapp.pyas a default argument thatdocker run image other.pyreplaces.- Use the exec form (JSON array) so the program is PID 1 and receives signals (lesson 1).
- Use
ENTRYPOINTfor an image meant to behave like one tool, andCMDfor 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 ciand build in one stage; copydist/and productionnode_modulesto 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
- Pinned, small base image (specific version tag; slim, alpine or distroless where suitable).
- Multi-stage if you compile anything.
- Instructions ordered from least to most frequently changing.
.dockerignorepresent.RUNsteps combined and cleaned;--no-install-recommendsand--no-cache-dirflags.- A non-root
USER. - Exec-form
CMD/ENTRYPOINT; the app logs to stdout. - No secrets in
ENV,ARG,COPYor layers. HEALTHCHECKor an equivalent probe in the orchestrator.- 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 updateandinstalllayers. - Using
latestbase images. - Shell-form
CMD. - Running as root, with a full build toolchain in the final image.
- Believing
EXPOSEpublishes a port. - Putting secrets in build args (they show in
docker history).
Try it yourself
- Containerise a small web app of your own. Build it three times: cold, with no change, and after editing one source file. Identify the
CACHEDsteps. - Reorder the Dockerfile badly (
COPY . .first) and see how the rebuild time changes. - Convert a single-stage Dockerfile for a compiled language to a multi-stage one and compare
docker imagessizes. - Add a
.dockerignore, prove with aRUN ls -athat 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/COPYmakes a layer; the cache reuses layers until one changes. - Order instructions from stable to volatile; combine and clean
RUNsteps; 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
- Dockerfile reference: every instruction and option.
- Building best practices: official guidance on caching, layers and base images.
- Multi-stage builds: patterns and
--target. - Build cache: how invalidation works and cache backends for CI.
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.