The Go 1.11 web service Dockerfile

Build with Modules, Ship from Scratch

If you use dep, check out my previous post instead.

Goals:

  • The application executable is compiled inside a container, in order to boost reproducibility

It is a multistage Dockerfile: the first throwaway stage is used for building, while the final image will only contain the compiled binary executable.

The dependencies are fetched at build time using the go.mod and go.sum files; an alternative Dockerfile for vendored dependencies is available at the bottom of this post.

  • Line 3: the ARG keyword fetches an optional command line argument. For example: docker build --build-arg GO_VERSION=1.11.2. If not provided, the default value 1.11 is used.

Alternative Dockerfile for vendored dependencies

Locking the dependencies using the go.sum integrity checks will make sure that the code downloaded for a production build will match the dependencies you’ve set up locally… provided that they are still available on the remote origin.

Since I’m not paying per MB in my repository hosting, I often vendor dependencies to ensure both integrity and availability. Go 1.11 with enabled modules will only build using vendored dependencies when passed the flag -mod=vendor.

If you are using a .dockerignore exclusion file, remember to remove vendor/ from it and run go mod vendor from your host machine, as this Dockerfile will expect all the dependencies already vendored.

This post originally appeared here.

Written by

Test-driven backend engineer. Cryptography consumer. Berlin, Europe.

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