Why isn’t my Docker cache working for Go builds?

0
1
Asked By CuriousCoder87 On

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

Answered By CacheMaster99 On

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.

Answered By TechieTom On

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.

Answered By DockerDude101 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.