Docker cache mounts deletes downloaded dependencies

Hi guys.
I have a small problem related to docker cache mount.
My application written in golang and i want to speed up my image builds and because i decide to use docker cache mounts to cache the $GOPATH/pkg/mod and $USER/.cache/go-build
for speed up go mod download and go build commands
but cache mount didnt work correctly when i run this command in image building state

RUN --mount=type=cache,target="/go/pkg/mod" go mod download -x

after that i check the size of pkg/mod folder size and it is kilobytes
and when i run the command for building

RUN --mount=type=cache,target="/root/.cache/go-build" go build -o app

it downloades the dependencies again and i am sure that cache mount didnt work correctly if anybody can help me please react to my message.
Thank you.

What is your expectation? You use two different folders as target. That is two different caches, so unless you mount the cache of “/go/pkg/mod” in the second instruction, it will not be mounted again.

The context of your instructions is missing too. I guess you have a multistage build, right? Otherwise you wouldn’t need a cache the filesystem is the only thing that is kept between the instructions and you just save data in the cache which you don’t use in the second instruction.


I got confused as well. What I wrote is true, but something doesn’t seem to work for me either.

Update 2:

This is my cache test and seems working, but I added --no-cache to the build command as usually when I test something, so of course, it didn’t work:

# syntax=docker/dockerfile:1

FROM ubuntu:22.04 as base

RUN --mount=type=cache,target=/cache \
   echo "base" > /cache/t0.txt \
 && mkdir /copy

FROM base as build-client

RUN --mount=type=cache,target=/cache \
    echo "build-client" >> /cache/t1.txt \
 && cp /cache/t1.txt /copy/

FROM base as build-server

RUN --mount=type=cache,target=/cache \
    echo "build-server" >> /cache/t2.txt \
 && cp /cache/t1.txt /copy/t1-2.txt \
 && cp /cache/t2.txt /copy

FROM scratch as client
COPY --from=build-client /copy /

FROM scratch as server
COPY --from=build-server /copy /

Then run

docker build . -t localhost/client --progress plain --target client --output .
docker build . -t localhost/server --progress plain --target server --output .


Dockerfile t1-2.txt  t1.txt  t2.txt

t1-2.txt wouldn’t be there without the cache as it is the copy of t1.txt which was not there i the base image, only in the cache.