tezvyn:

Optimizing Dockerfile layer caching

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

how layer caching invalidation works.

OUTLINE

order instructions least-to-most volatile, copy dependency manifests and install before copying source, and understand any changed layer busts all later layers.

WHAT THIS TESTS This checks whether you understand Docker's layered build cache: every instruction produces a layer, and changing one instruction invalidates its cache and all subsequent layers.

A GOOD ANSWER COVERS The fix is ordering instructions from least to most frequently changing. Copy the dependency manifest first, for example package.json and lockfile or requirements.txt, run the install step, and only then COPY the rest of the source. Because the manifest rarely changes, the expensive install layer stays cached across code edits, and only the cheap final COPY and build layers rerun. Add a dockerignore to keep noisy files out of the build context so they do not bust the cache. For modern builds, BuildKit cache mounts persist package-manager caches across builds even when a layer rebuilds. Multi-stage builds keep build tooling out of the final image.

COMMON WRONG ANSWERS Putting COPY . . before the install command, so any code change invalidates the install layer and forces a full reinstall. Pinning nothing and assuming the cache helps anyway. Forgetting dockerignore, so changing a log file invalidates the build context.

LIKELY FOLLOW-UPS What exactly invalidates a COPY layer? How do cache mounts differ from layers? How does cache behave in CI with ephemeral runners? What is the effect of ARG on caching?

ONE CONCRETE EXAMPLE A Node service originally did COPY . . then RUN npm install, so editing one line in app.js triggered a fresh npm install of hundreds of packages. Reorder to COPY package.json package-lock.json ./, then RUN npm ci, then COPY . ., then RUN npm run build. Now an app.js edit only invalidates the final COPY and build layers; npm ci is served from cache and the rebuild drops from minutes to seconds.

Read the original → docs.docker.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.