← All Exercises

Keep the Dependency Layer Cacheable

basicjavascript~20min

Background

Layer order decides rebuild time. Copying the whole source tree before installing dependencies forces a reinstall whenever a comment changes.

Problem

Inspect a Dockerfile instruction list and flag any instruction that copies application sources before the dependency install layer, which invalidates the cache on every code change.

Input

JSON object: { instructions: [{ cmd, args }] }

Output

JSON object: { cacheSafe: boolean, offending: number[], suggestion: string }

Sample tests

Sample 1

Input: {"instructions":[{"cmd":"FROM","args":"node:22"},{"cmd":"COPY","args":"package*.json ./"},{"cmd":"RUN","args":"npm ci"},{"cmd":"COPY","args":". ."}]}
Expected: {"cacheSafe":true,"offending":[],"suggestion":"layer order keeps dependency cache intact"}

Sample 2

Input: {"instructions":[{"cmd":"FROM","args":"node:22"},{"cmd":"COPY","args":". ."},{"cmd":"RUN","args":"npm ci"}]}
Expected: {"cacheSafe":false,"offending":[1],"suggestion":"move COPY of sources after the dependency install layer"}

Your solution

Learning objective

Review Dockerfiles for cache-invalidating instruction order.