Writing better Dockerfiles
A Dockerfile that works is easy; a good one takes a little more thought. Good images are small, rebuild fast, run as an ordinary user, stop cleanly and always build the same way. This chapter builds on the basic Dockerfile from "Working with Docker" and fixes the things that bite in production.
Pick a small base image
Your FROM line decides most of the image's size and how many packages (and therefore possible vulnerabilities) come along. Most official images come in several variants:
| Variant | What it is | Trade-off |
|---|---|---|
node:22 | Full Debian with compilers and common tools | Most compatible, by far the largest |
node:22-slim | Debian with the extras stripped out | Uses glibc like most Linux software, so prebuilt binaries just work. A good default |
node:22-alpine | Alpine Linux, installs packages with apk | Very small, but uses musl libc instead of glibc: some native modules and prebuilt binaries fail or must be compiled from source |
gcr.io/distroless/..., scratch | Only your app and its runtime; no shell, no package manager | Smallest and safest, but harder to debug. Best for the final stage of a multi-stage build |
Rule of thumb: start with -slim; use -alpine when you've tested that everything works on musl.
Keep secrets and junk out: .dockerignore
docker build . sends the whole folder (the build context) to the builder, and COPY . . copies all of it into the image. A .dockerignore file next to the Dockerfile excludes things, just like .gitignore:
# .dockerignore (comments must be on their own line)
.git
# reinstalled inside the image anyway
node_modules
npm-debug.log
# never bake secrets into an image
.env
dist
compose.yaml
This makes builds faster, images smaller, and stops your local node_modules (built for your OS) from overwriting the one installed in the image.
Order layers for the cache
Docker rebuilds from the first changed layer onward, so put what changes least at the top: base image, system packages, dependency files, dependency install, and your source code last. When installing system packages, update and install in the same RUN and clean up in it too, because files deleted in a later layer still take up space in the earlier one:
package*.json and installing before COPY . . means a code change doesn't reinstall every dependency.RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/*
Multi-stage builds
Compilers and build tools are needed to build the app, not to run it. A multi-stage build uses one stage to compile and copies only the result into a clean final stage. Everything else is thrown away. Here's a Go web service:
# ---- stage 1: build ----
FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./ # dependencies first, for the cache
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/server . # static binary, no libc needed
# ---- stage 2: run ----
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
EXPOSE 8080
ENTRYPOINT ["/server"] # the :nonroot image already runs as UID 65532
The final image contains the binary and almost nothing else: no Go toolchain, no shell. CGO_ENABLED=0 matters: without it the binary may be linked against glibc, and in a distroless-static or scratch image it fails with a confusing exec /server: no such file or directory. (If your module has no dependencies there's no go.sum; copy just go.mod.)
Don't run as root
By default the process inside a container runs as root. If the app gets compromised, that makes escaping or doing damage easier. Switch to an unprivileged user with USER. The official Node images already include a user called node:
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev # production dependencies only
COPY . .
RUN mkdir -p /app/uploads && chown node:node /app/uploads # the one place it may write
USER node # everything from here on runs as "node"
EXPOSE 3000
CMD ["node", "server.js"]
The code stays owned by root and read-only for the app; only uploads is writable. On images without a ready-made user, create one: RUN addgroup -S app && adduser -S app -G app (Alpine) or RUN useradd --system --no-create-home app (Debian).
CMD vs ENTRYPOINT, and why exec form matters
CMDis the default command. Anything you type after the image name indocker runreplaces it.ENTRYPOINTis the fixed executable. Arguments fromdocker run(orCMD) are appended to it. Override it only with--entrypoint.
ENTRYPOINT ["python", "app.py"]
CMD ["--port", "8080"]
$ docker run myapp # runs: python app.py --port 8080
$ docker run myapp --port 9000 # runs: python app.py --port 9000
Always use the exec form (JSON array). The shell form, CMD node server.js, runs your app as a child of /bin/sh -c. The shell becomes PID 1 and may not pass SIGTERM on to your app, so docker stop waits its 10-second timeout and then kills it with SIGKILL: no graceful shutdown, no finished requests.
HEALTHCHECK
A running process isn't necessarily a working app. HEALTHCHECK tells Docker how to test it:
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget -qO- http://127.0.0.1:3000/health || exit 1
docker ps then shows (healthy), (unhealthy) or (health: starting), and Compose can wait for it (next chapter). Two catches: the tool must exist in the image (Alpine has BusyBox wget; slim images have neither curl nor wget), and plain Docker only reports unhealthy, it doesn't restart the container. Kubernetes ignores HEALTHCHECK entirely and uses its own probes.
Pin your versions
FROM node:latest means your build can change underneath you any day. Pin at least the major version (node:22-alpine). For fully repeatable builds, pin the digest, the image's content hash, which can never change:
$ docker buildx imagetools inspect node:22-alpine # shows "Digest: sha256:..."
FROM node:22-alpine@sha256:<digest>
The catch: a pinned digest also never gets security fixes, so let a tool such as Dependabot or Renovate open pull requests to bump it.
Check the result
$ docker build -t demee/app:1.1 .
$ docker images demee/app # SIZE column: compare before and after
$ docker history demee/app:1.1 # every layer, its size, the instruction that made it
docker history shows exactly which instruction added the weight: a surprise 300 MB layer usually means a missing .dockerignore entry or an install that didn't clean up after itself.
Common build errors
- COPY fails with "not found": the file is outside the build context or excluded by
.dockerignore. npm cifails: it needs apackage-lock.json; copy it together withpackage.json.exec format errorwhen running: the image was built for another CPU architecture (e.g. arm64 on a Mac, run on an amd64 server). Build with--platform linux/amd64.