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 .. FROMpicks a base image,COPYadds your files,RUNruns a command during the build.CMDruns 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"]Multi-stage builds keep build tools out of the image
- Each
FROMstarts a new stage. Only the last stage becomes the image you ship. COPY --from=buildtakes 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"]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
.indocker build .. - A
.dockerignorefile leaves files out of it, using patterns like.gitignore. - List
node_modules,.gitand.envthere. Builds get faster andCOPY . .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-slimcan 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 --pullchecks for a newer base image.