Image for post
Image for post
Docker & Go image by

Go — build a minimal docker image in just three steps

When you build your Go application for docker, you usually start from some image like golang:1.13. However, it’s a waste of resources to actually use that image for runtime. Let’s take a look at how you can build a Go application as an absolute minimal docker image.

1. Choose a Go version

Therefore, always use full specification, including the patch version number and ideally even the base OS that image comes from, e.g. 1.13.0-alpine3.10

2. Keep it minimal

Fast builds

Also, consider using a .dockerignore file which helps keep the build context small — basically, when you run docker build, docker needs to feed everything in the current directory to the build daemon (that Sending build context to Docker daemon message you see at the beginning of a docker build). In short, if your repo contains a lot of data not necessary for building your app (such as tests, markdown for docs generator, etc), .dockerignore will help to speed the build up. At the very least, you can start with the following contents. Dockerfile is there so that if you COPY . . (which you shouldn’t, BTW) doesn’t have to execute and invalidate everything bellow when you change just that Dockerfile.


Small images

How this works is that you use a two-step build inside a single Dockerfile, where you actually build your app on one image, called builder (as an example, it can be actually any name you fancy), then copy the resulting binaries (and all other required files) to a final image based on scratch.

3. Putting it all together

Please leave a comment if you find this useful and/or you would like to share a few tips or tricks of your own.

Written by

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