I know this is quite late answer, but it does tell how to build the slimmiest image for Golang programs. It is based on the question Deployment using image from scratch fails to start
The trick is to build statically linked executable and place it into the empty image called scratch
. The image contains just a single file, that exact executable. It is the smallest image possible.
Docker file:
FROM golang:latest as builder
# The Dockerfile expects the source code of the application
# to reside in ./src/ directory
COPY src /src
WORKDIR /src
# Build statically linked file and strip debug information
# The Dockerfile expects the `main` package to be at the root of the module
RUN CGO_ENABLED=0 go build -ldflags="-extldflags=-static -s -w" -o executable
# scratch is an empty image
FROM scratch
# If you need /bin/sh and a few utilities, uncomment
# the following line. It increases the image by 5.5 MB
# FROM alpine:latest
COPY --from=builder /src/executable /executable
# copy other files if needed
ENTRYPOINT ["/executable"]
The Dockerfile expects the source code to be in src
directory
<project_root>
|_ Dockerfile
|_ src/
|_ go.mod
|_ package_main.go # file with `package main` and `func main()`
|_ other source files
The command docker build ./ -t my-minimal-go
produces the image named my-minimal-go:latest
To prove that it is the minimal image, save it to TAR and study the contents:
docker image save my-minimal-go:latest > my-minimal-go.tar
tar tf my-minimal-go.tar
The contents is something like
84ebda22f9b32043fdcb7bb70c559f0ee91cac60b4b92f1ce424662afec6d4b9.json
e622775ad65d50bc0b9f30e6ce58ee7670f752c63c3ca70caba4f9165efdca80/
e622775ad65d50bc0b9f30e6ce58ee7670f752c63c3ca70caba4f9165efdca80/VERSION
e622775ad65d50bc0b9f30e6ce58ee7670f752c63c3ca70caba4f9165efdca80/json
e622775ad65d50bc0b9f30e6ce58ee7670f752c63c3ca70caba4f9165efdca80/layer.tar
manifest.json
repositories
And to see the list of files in the image:
docker image save my-minimal-go:latest | tar x --wildcards '*layer.tar' -O | tar t
Output:
executable
Just a single file, the minimal image.