Multi stage docker build

Multi stage docker build

Step-by-step creating multistage docker file create more efficient and smaller Docker images by using multiple stages in your Dockerfile

First, we can clone the code "python-multistage-docker" from my GiHub account.

Then execute the git clone command to copy the code.

We have removed the docker file and again recreated it for practice purposes.

We can check the code as well so will get all the information like version & ports as well in git hub.

Post this executed the command docker build to build an image and it goes running into the layer.

While executing the docker run command we checked and found that port "5000" had been already allocated for another process. So we can use kill -9 & process id to kill the process

Before moving ahead we can ensure that there is any docker containers running state if yes then we can kill those containers or clear them with the "docker system prune "command

Now run the docker run command:

We can check with docker ps command & docker ps -a command for running containers; if running containers are not showing with docker ps command then try with docker ps -a command.

To check the logs for the container docker logs <container id>

we got an error from the log so we checked on Google and found that "Werkzeug=2.3.7" is not available in the requirement.txt file so we can add into to that.

& then execute docker build command to create an image.

& the image has been successfully created

Post this we can run the command docker run & the container is running.

& now the app is working fine.

We can able to see that the image size so 1.01GB & for one message on the website we cannot spend almost 1GB Size this is not a standard practice.

So with Multi-stage builds in Docker allow you to create more efficient and smaller Docker images by using multiple stages in your Dockerfile. Each stage represents a phase in the build process and can be used to build and compile your application. The final image only includes the artifacts you need, resulting in a smaller image size.

Instead of removing we can do vim Dockerfile & edit in the docker file & we can define it stagewise.

We can take a Python image from Google which has having smaller size

Then we can search in Google Python base image size.

We have taken it from here slim image and put it in the docker file

So from stage 2, the base image size would be less.

Then we can run the docker build -t multi-stage-python .

We have used a different image name over here for the image cause it’s a new image .

It removes intermediate continue means skipping the first image & starting with the new Python slim image

So we can check here the size of the new multi-stage-python image is only 116MB as our previous image was 1.01GB.

Hope you like this article.

Keep Learning !!

Thank You!!