Sub topic 3
Layer Ordering and the Build Cache
Assume you know basic command-line use, can run Docker commands, and understand that an image is a packaged application while a container is a running instance of it.
Layer ordering and the build cache
Docker builds an image in layers. Most Dockerfile instructions create a layer. Docker reuses a layer when the instruction and its required files have not changed. A cache miss invalidates that layer and later layers.
Copy dependency manifests before application source. Source changes then do not force dependency installation again.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
USER node
EXPOSE 3000
CMD ["node", "server.js"]Put stable instructions early and frequently changing instructions late. A cache speeds builds but does not replace reproducible dependency versions.
Keeping the context small with .dockerignore
The build context is the set of files sent to the Docker builder. Exclude unnecessary files before the build starts:
node_modules
.git
*.log
.env
Dockerfile
.dockerignoreDo not send secrets, local dependencies, or large test artifacts. .dockerignore improves speed and reduces accidental exposure.
> Callout note > A file in .dockerignore cannot be copied by COPY. Keep required production files outside the excluded patterns.
Multi-stage builds for smaller images
A multi-stage build uses one image to compile and another to run. The final image receives only the runtime files.
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]This reduces image size and removes compilers and source code from production.
Running as a non-root user
Use USER after files are prepared. A process running as a non-root user has fewer permissions if the application is compromised. Ensure the selected user can read the application and write only to intended directories.
Documenting ports and checking health
EXPOSE 3000 documents the container port. It does not publish that port. Use docker run -p 3000:3000 image to publish it. Add HEALTHCHECK when the application provides a reliable health endpoint.
BuildKit cache and secret mounts
BuildKit can cache package-manager data without storing it in an image layer. Secret mounts expose credentials only during one build step.
# syntax=docker/dockerfile:1
RUN --mount=type=cache,target=/root/.npm npm ci \
&& --mount=type=secret,id=npmrc,target=/root/.npmrc npm run buildUse docker build --secret id=npmrc,src=$HOME/.npmrc .. Never copy a secret into the image.
Exercise
Why should COPY package*.json ./ appear before COPY . .?
Show answer
Application source changes then leave the dependency-installation layer cached, so Docker can reuse it.