I'm having trouble getting the cache to work for my repeated Dockerfile builds using Go. Here's what my Dockerfile looks like:
```dockerfile
FROM golang:1.24 AS builder
WORKDIR /workspace
COPY go.mod go.mod
COPY go.sum go.sum
RUN go mod download
# Copy the Go source (relies on .dockerignore to filter)
COPY . .
ENV GOCACHE=/root/.cache/go-build
RUN --mount=type=cache,target=/root/.cache/go-build
CGO_ENABLED=0 go build -a -o manager cmd/main.go
FROM gcr.io/distroless/static:nonroot
WORKDIR /
COPY --from=builder /workspace/manager .
ENTRYPOINT ["/manager"]
```
When I build the Docker image with `docker build .`, the `RUN go mod download` layer is cached, which is great:
```
=> CACHED [builder 5/7] RUN go mod download
```
But the go build step always takes more than 2 minutes, even though I expected it to cache the builds:
```
=> [builder 7/7] RUN --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 go build -a -o manager cmd/main.go 135.7s
```
It seems like the cache mount isn't being reused as it's supposed to, and I'm not sure what I'm doing wrong. How can I fix this to cache my Go builds correctly?
3 Answers
Make sure to include the syntax line as the very first line of your Dockerfile to enable BuildKit features, like this:
`# syntax=docker/dockerfile:1`
Removing the quotes may help with caching but do note, it's crucial to be on a recent version of Docker.
This sounds off. Check your GOCACHE before and after the build to ensure it's getting populated correctly. That could shed some light on why the cache isn’t working as expected.
You might want to try using multistage Dockerfiles for better cache layer handling instead of relying solely on the host mount. It can simplify your builds and make caching more effective.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically