Go Ways

How to Build a Minimal Golang Docker Image

Make Docker image less than 10MB

Pavel Fokin
3 min readAug 7, 2022
Minimal Golang Docker Image

Having an image container that keeps precisely what you need is always considered a best practice. We want to have only our application and dependencies that are required for its runtime.

Why we would do this?

  • Small size image reduces the risk of vulnerabilities.
  • It will improve the deployment process improve perfomance and reduce size

Minimal Project

I’ll be using a simple HelloWorld webservice to build a Docker image.

HelloWorld webservice

Using alpine image

01. Dockerfile

Let’s write a Dockerfile with using an alpine distro as an image.

Docker.large

02. Docker build

After building this Dockerfile we will get a 350MB image.

➜  minimal-docker git:(main) ✗ docker build -t helloworld-large -f Dockerfile.large .
[+] Building 7.1s (12/12) FINISHED
...
...
...
➜ minimal-docker git:(main) ✗ docker image ls helloworld-large
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld-large latest 678f9303af18 10 seconds ago 350MB
➜ minimal-docker git:(main) ✗ docker run -ti -p 8000:8000 helloworld-large:latest
Server listen 8000...

Can we do better? Yes, we can!

Using distroless image

01. Dockerfile

For the next Dockerfile we will use multistage approach and distroless image by Google.

Docker.small

02. Docker build

Voila! After building we get only 8.6MB image size.

➜  minimal-docker git:(main) ✗ docker build -t helloworld-small -f Dockerfile.small .
[+] Building 8.0s (14/14) FINISHED
...
...
...
➜ minimal-docker git:(main) ✗ docker image ls helloworld-small
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld-small latest 3b035dc2c7e4 5 seconds ago 8.6MB
➜ minimal-docker git:(main) ✗ docker run -ti -p 8000:8000 helloworld-small:latest
Server listen 8000...

Can we do better? Yes, we can!

Using scratch image

01. Dockerfile

We even can go smaller, for this we can use scratch image. But as this is a super slim image we will need to add some extra things as timezones or ssl certificates.

Docker.xsmall

02. Docker build

And we get 7.59MB image.

➜  minimal-docker git:(main) ✗ docker build -t helloworld-xsmall -f Dockerfile.xsmall .
...
...
➜ minimal-docker git:(main) ✗ docker image ls helloworld-xsmall
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld-xsmall latest b7b554ac46c9 21 minutes ago 7.59MB

Full code you can find in my GitHub repo pave-fokin/go-patterns/minimal-docker.

Happy coding!

Thank you for reading! Share you thoughts with me on LinkedIn or Twitter.

Further readings

If you like this article you can be interested in the following.

--

--