Skip to content

Guides

How to fix Docker cache invalidation

Docker layers rebuild even when the relevant files did not change.

5 min read

Docker layers rebuild even when the relevant files did not change.

Why it happens

A COPY earlier in the Dockerfile than it needs to be invalidates everything after it.

How to fix it

  1. Copy the lockfile and install dependencies before copying application source
  2. Use .dockerignore so unrelated files do not bust the cache
  3. Pin the base image by digest so an upstream rebuild does not invalidate everything
  4. Use cache mounts for package manager directories

Your next build could be twice as fast, at half the price

Start free. Migrating away is the same one line, and we publish that diff too.