Skip to content
Engineering Bible
Docker

Docker on Dockerfiles and builds

A Dockerfile is the recipe for an image

  • It's a text file of instructions, run top to bottom by docker build -t todo-app ..
  • FROM picks a base image, COPY adds your files, RUN runs a command during the build.
  • CMD runs nothing at build time. It sets the command a container starts with.
  • Each instruction that changes files adds one layer to the image.

Order instructions so the cache does the work

  • Docker reuses a layer when its instruction and the files it uses haven't changed.
  • One change rebuilds that step and every step after it, so put slow steps early.
  • Copy the dependency list and install first. Copy the code after, since it changes most.
  • A cache mount keeps the package manager's downloads between builds, outside the image.
FROM node:24-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
CMD ["node", "server.js"]
Editing code only reruns the last COPY. Dependencies reinstall only when package*.json changes.

Multi-stage builds keep build tools out of the image

  • Each FROM starts a new stage. Only the last stage becomes the image you ship.
  • COPY --from=build takes the finished files from an earlier stage and nothing else.
  • Compilers, test tools and source code stay behind, so the image is smaller.
FROM node:24-slim AS build
WORKDIR /app
COPY . .
RUN npm ci && npm run build

FROM node:24-slim
WORKDIR /app
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
Assumes npm run build bundles the app into dist. The second stage ships only that folder.

BuildKit is the builder behind docker build

  • BuildKit is the default builder in Docker Desktop and Docker Engine.
  • It builds stages that don't depend on each other at the same time.
  • It skips stages the final image doesn't use, and sends only the files that changed.

Send the builder only what it needs

  • The build context is the set of files a build can read: the . in docker build ..
  • A .dockerignore file leaves files out of it, using patterns like .gitignore.
  • List node_modules, .git and .env there. Builds get faster and COPY . . copies less.

Pin the base image and rebuild often

  • Pick a small base image from a trusted source. Less inside means less to patch.
  • A tag like node:24-slim can be moved, so the same Dockerfile can build a new image.
  • Add the digest, FROM node:24-slim@sha256:..., to get the exact same base every time.
  • Rebuild regularly to pick up fixes. docker build --pull checks for a newer base image.
Docker in four pages2 / 4