Building Minimal Docker Image for Go Applications

Learn how to build tiny docker image for Go from scratch

ta-ching chen

2 minute read

 Table of Contents

Hello World 

Lets create a simple small application that keeps printing out Hello World!

// main.go
package main

import (

func main() {
    for {
        fmt.Println("Hello World!")
        time.Sleep(1 * time.Second)


Cross Compilation 

CGO_ENABLED let the Go binaries link the libraries on the system. To reduce the binary size, CGO_ENABLED is enabled by default for native build. This time we use scratch as our base image, which is a special Docker image with nothing in it (even the libraries), we need to disable the cgo parameter let compiler packages all the libraries application need into the binary.

If you want to do cross compilation, dont forget to add GOOS and GOARCH.

$ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main

Build Image 

Here is all we need in the Dockerfile

FROM scratch
ADD main /
CMD ["/main"]
$ docker build -t minimal_go_docker_img .
$ docker images
REPOSITORY                        TAG                 IMAGE ID            CREATED             SIZE
minimal_go_docker_img             1.0                 8f836c8b219a        17 minutes ago      1.638 MB

Launch it 

$ docker run --rm minimal_go_docker_img

Add SSL Certificates 

If your application need to access https service, dont forget to add the ca.crt.

Normally you can find ca-certificates.crt under the /etc/ssl/certs/ at any linux distribution.

FROM scratch
ADD ca-certificates.crt /etc/ssl/certs/
ADD main /
CMD ["/main"]

Further reading 


comments powered by Disqus