Manually fetch dependencies from go.mod?

Alex Guerra picture Alex Guerra · Sep 11, 2018 · Viewed 28.3k times · Source

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?

Answer

rustyx picture rustyx · Jun 20, 2019

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:

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

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

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

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