Manually fetch dependencies from go.mod?

It was an issue #26610, which is fixed now.

So now you can just use:

go mod download

For this to work you need just the go.mod / go.sum files.

For example, here’s how to have a cached multistage Docker build: (source)

FROM golang:1.17-alpine as builder
RUN apk --no-cache add ca-certificates git
WORKDIR /build

# Fetch dependencies
COPY go.mod go.sum ./
RUN go mod download

# Build
COPY . ./
RUN CGO_ENABLED=0 go build

# Create final image
FROM alpine
WORKDIR /
COPY --from=builder /build/myapp .
EXPOSE 8080
CMD ["./myapp"]

Also see the article Containerize Your Go Developer Environment – Part 2, which describes how to leverage the Go compiler cache to speed up builds even further.

Leave a Comment