Search code examples
dockercachingdockerfilecontainers

Difference between --cache-to/from and --mount type=cache in docker buildx build


According to the official documentation, in order to leverage a cache backend in docker buildx build, you need to use the --cache-from/to flags.

This makes sense as intuitively it signifies the place where the build result will be cached to (--cache-to) and what cache it will use to speed up the build process (--cache-from).

However, there is another alternative (?) of using cache with the mount option within the RUN directive, as in: (official example)

RUN \
    --mount=type=cache,target=/var/cache/apt \
    apt-get update && apt-get install -y git

In the last example where these (apt packages in our case) will be retrieved from?

Is the cache backend (s3, gha etc) applicable in this case?

Are these two cases complementary or orthogonal?


Solution

  • They are solving two different problems.

    --cache-to/from is used to store the result of a build step and reuse it in future builds, avoiding the need to run the command again. This is stored in a persistent location outside of the builder, like on a registry, so that other builders can skip already completed steps of a build even if the image wasn't built on the local system.

    --mount type=cache creates a mount inside the temporary container that's executed in a RUN step. This mount is reused in later executions of the build when the step itself is not cached. This is useful when a step pulls down a lot of external dependencies that do not need to be in the image and can safely be reused between builds. The storage of the mount cache is local to the builder and is an empty directory on first use.