Day 21 : Docker Multistage build Projects

ยท

2 min read

Let's build a project with a multistage Dockerfile and try to get the hang of its benefits.

We have created a calculator application using Golang. The main purpose of choosing a golang based application to demonstrate this example is Golang is a statically-typed programming language that does not require runtime in the traditional sense. Unlike dynamically-typed languages like Python, Ruby, and JavaScript, which rely on a runtime environment to execute their code, Go compiles directly to machine code, which can be executed directly by the operating system. So the real advantage of multi-stage docker build and distroless images can be understood with a drastic decrease in the Image size.

Firstly, let's clone the repository and go inside the "golang-multi-stage-docker-build" folder.

Github link: https://github.com/SudipaDas/Docker.git

you can run this calculator application by using "go run calculator.go" like below:

Now, let's containerize the application using Dockerfile. To begin, we will try without a multistage docker build and check what the image size is. Let's go inside the folder called "dockerfile-without-multistage".

In the above image, we can see the basic Dockerfile where we have used ubuntu as a base image and installed some dependencies related to Golang and at last, executed the application.

Now let's build the application using the "docker build" command.

In the above image, you can see the calculator image size is 860MB.

Can you guess if a basic calculator application's image size is around 800 MB how big will an application like Amazon, or Flipkart be?

Now let's try a docker multistage build.

In this multistage docker build Dockerfile we have two stages.

Stage one doesn't have CMD or ENTRYPOINT, it is only dedicated to the build stage. In the second stage, we used a minimalistic distroless image called scratch. And, in the next line, we are copying the binary from the first stage. Finally, we are executing it as part of the ENTRYPOINT.

As you can see in the above image, the size of the image got reduced.

It is now just 1.83MB. It got reduced by 800% !! I appreciate it :-)

By moving towards multistage docker build and distroless images we not only reduce the size of the image but also make sure the containers are running securely. These are very less vulnerable to threats.

Note: you can find all the distroless images for Python, Java in the below github link:

https://github.com/GoogleContainerTools/distroless

If this post was helpful, please follow and click the ๐Ÿ’š button below to show your support.

_ Thank you for reading!

_Sudipa

ย