🐳 Fix a Build Cache Ignoring a Changed ARG Value
Docker’s layer cache keys a layer by the instruction text in the Dockerfile and the build context it consumes, not by the runtime value you pass with –build-arg – so an ARG that’s declared but not actually referenced inside the specific RUN or COPY instruction whose output should change leaves that layer’s cache key untouched even when you change the ARG’s value between builds. The build finishes fast, reports no errors, and tags a new image that’s quietly still running the previous version’s artifact underneath.
🐳 The Problem
ARG VERSION=2.0
FROM base-image:latest
# VERSION is declared above but never actually used inside this RUN line,
# so changing --build-arg VERSION=2.1 does not change this instruction's
# text or its cache key - the layer below is reused from the old build.
RUN curl -O https://example.com/releases/app-latest.tar.gz && \
tar -xzf app-latest.tar.gz
✅ Fix: Make the ARG Actually Participate in the Cached Instruction
- Interpolate the ARG directly inside the RUN or COPY instruction whose output needs to change (for example RUN curl -O https://example.com/releases/app-$VERSION.tar.gz), since Docker only busts a layer’s cache when that layer’s instruction text or consumed context actually differs.
- When you need to force a rebuild of one specific layer without discarding the entire cache, build with –no-cache targeted at that stage, or restructure the Dockerfile so the ARG-dependent instruction runs as late as possible, after the other reliably cacheable steps.
- Add a development-only RUN echo “$VERSION” step right before the layer in question so a stale cache hit shows the wrong value directly in the build log instead of baking in silently.
🚨 Why This Is Dangerous
- An image tagged and shipped as a new release can still be running the previous version’s binary underneath, with nothing in the build log or the final image’s own metadata pointing at the mismatch.
Docker doesn’t cache what you told it to build – it caches the exact instructions you wrote, and an unused ARG never changes those.
