Using go mod download to speed up Golang Docker builds

The build time of Golang Docker images always frustrated me as there was always a need to do the go get ./... before we started building the binary. This resulted in fetching the dependencies every time we wanted to build the image. The Dockerfile then looked like this:

FROM golang:alpine AS build-envCOPY . $GOPATH/src/mypackage/myapp/
WORKDIR
$GOPATH/src/mypackage/myapp/
# go get and build <-- THIS IS THE IMPORTANT PART
RUN go get -d -v
RUN go build -o /go/bin/hello
FROM scratch # <- Second step to build minimal image
COPY --from=build-env /go/bin/hello /go/bin/hello
ENTRYPOINT ["/go/bin/hello"]

Go mod download

Go 1.11 introduces the go mod downloadcommand, which takesgo.modand go.sumfiles and downloads the dependencies from them instead of using the source code. As these files don’t change frequently (unless you are updating the dependencies), they can be simply cached by the COPYcommand from Dockerfile.

FROM golang:1.11.1-alpine3.8 as build-env# All these steps will be cached
RUN mkdir /hello
WORKDIR /hello
COPY go.mod . # <- COPY go.mod and go.sum files to the workspace
COPY go.sum .

# Get dependancies - will also be cached if we won't change mod/sum
RUN go mod download
# COPY the source code as the last step
COPY . .

# Build the binary
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o /go/bin/hello
FROM scratch # <- Second step to build minimal image
COPY --from=build-env /go/bin/hello /go/bin/hello
ENTRYPOINT ["/go/bin/hello"]
RUN apk add --update --no-cache ca-certificates git

I like lasagnas

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store