Search code examples
gogo-modules

Manually fetch dependencies from go.mod?


I'm using go 1.11 with module support. I understand that the go tool now installs dependencies automatically on build/install. I also understand the reasoning.

I'm using docker to build my binaries. In many other ecosystems its common to copy over your dependency manifest (package.json, requirements.txt, etc) and install dependencies as a separate stage from build. This takes advantage of docker's layer caching, and makes rebuilds much faster since generally code changes vastly outnumber dependency changes.

I was wondering if vgo has any way to do this?


Solution

  • 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.