Day 20 : Multi Stage Docker Builds

#90daysofdevops #devops

ยท

2 min read

Today we are going to take the example of a model application that we will execute as a docker container. If it is a Go-based application, the Dockerfile steps will be as follows:

Though we have written here a good Dockerfile, we need to find if there is a scope for improvement.

If you look at the above Dockerfile, it has many dependencies. For example, it has Ubuntu as a base image which inherently includes some basic binaries and libraries like wget, curl etc. The application doesn't require all those bin, libs to run and this will increase the image size.

At the end of the day, you just want to run the model application. That application requires only the runtime.

To solve this problem Docker came up with Multistage-builds.

Docker multistage builds:

A multistage Docker build is a process to create a Docker image through a series of steps. You will split your Dockerfile into multiple parts.

If I write the same example with a multistage Docker build, it looks as follows:

With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. The final stage will have the ENTRYPOINT or CMD and it will use the stages above that as inputs for the build.

One excellent benefit of a multistage Docker build is that it reduces the number of dependencies and unnecessary packages in the image, reducing the attack surface and improving security. In addition, it keeps the build clean and lean by having only the things required to run your application in production.

Here are some other advantages of using multistage builds:

  • Optimizes the overall size of the Docker image

  • Removes the burden of creating multiple Dockerfiles for different stages

  • Easy to debug a particular build stage

  • Ability to use the previous stage as a new stage in the new environment

  • Ability to use the cached image to make the overall process quicker

  • Reduces the risk of vulnerabilities found as the image size becomes smaller with multi-stage builds

Note: You can create n number of stages in a multistage Dockerfile. But there will be only one final stage which will be a minimalistic image.

Tomorrow's blog will be on a live project of multistage docker build and Distroless Container Images.

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

_ Thank you for reading!

_Sudipa

ย