To be more precise than the accepted response, not all lines are cache invalidated after an ARG declaration. Only those that use ARG values and RUNs. The docker documentation the details:
Impact on build caching
ARGvariables are not persisted into the built image asENVvariables are. However,ARGvariables do impact the build cache in similar ways. If a Dockerfile defines an ARG variable whose value is different from a previous build, then a “cache miss” occurs upon its first usage, not its definition. In particular, allRUNinstructions following anARGinstruction use theARGvariable implicitly (as an environment variable), thus can cause a cache miss. All predefinedARGvariables are exempt from caching unless there is a matchingARGstatement in the Dockerfile.
- https://docs.docker.com/engine/reference/builder/#impact-on-build-caching
You’ll have to move your ARGs under the RUNs that would not need the argument in order to keep layer cache optimized.
For more info:
- https://github.com/moby/moby/issues/18017
- https://github.com/moby/moby/pull/18161
- RUN explanation here: https://github.com/moby/moby/pull/21885