Short answer
Each instruction is a cached layer keyed by its content and the previous layers; a change invalidates that layer and everything after it.
Explanation
So you copy and resolve dependencies before copying source — for Maven, COPY pom.xml then mvn dependency:go-offline, then COPY src — so editing code only busts the cheap source/compile layers while the expensive dependency layer stays cached. Putting COPY . . too early is the classic mistake: any file change re-downloads all dependencies, making every build slow.
Common mistakes
- Copying the whole project before dependencies, which invalidates the cache on every change.
- Not separating dependency download from source copy.