Using a multi-Stage Dockerfile
Explore how to optimize your Go command-line programs by using multi-stage Dockerfiles. Understand building with a full Golang image and copying executables to a minimal base image like Alpine to drastically reduce Docker image size. Learn best practices to create efficient, secure containers that require fewer resources.
We'll cover the following...
Using a multi-stage Dockerfile
One of the main benefits of Docker is that it can potentially create very small images, which require less resources and are more secure due to the small surface area. In the previous section, you saw that we can build a 10MB multi-git executable. However, building it requires a lot of foundation. Here is a simple Dockerfile based on the golang:1.14 base image that builds multi-git. I saved it as Dockerfile.big:
Let’s use it to build it a Docker image:
$ docker build . -f Dockerfile.big -t multi-git.big
Sending build context to Docker daemon 22.39MB
Step 1/9 : FROM golang:1.14
---> 25c4671a1478
Step 2/9 : WORKDIR /build
---> Using cache
---> 8b8e998005bc
Step 3/9 : ADD main.go main.go
---> Using cache
---> 69d9863aa86a
Step 4/9 : ADD go.mod go.mod
---> Using cache
---> 1b8a35e84444
Step 5/9 : ADD cmd cmd
---> 6dc9e0482362
Step 6/9 : ADD pkg pkg
...