Build your own containers | Dockerfile
Dockerfile is basically a configuration file that is use to create docker image. It contains list of commands that will run in order to assemble the image.
💠Understand by an example:
Suppose you have a application and you want to containerize it(installing it in docker container) and then use it.
So what is the actual requirement? Basically you need a container which has the dependent libraries. Then you can copy the source code into the container. Install the application if required. And then run the application. All of these steps can be done via a dockerfile. And in the end you will get a docker image. And when you run this image your application will be started.
Let’s try it out:
If I take an example of python application. Here is my simple python application which is creating a server to show the list of files in the directory:
Now if I check the dependencies for this application. I can say it is mainly dependent on python. So to containerize the application I need to create a docker image that contains python and my application.
So instead of creating the image from scratch, I can just use the existing Docker image of python. It is available in docker hub and I can built on top of it. So here is the example dockerfile.
In the above file, firstly, I am using the python:3.10-alpine as my base image. And now since my major dependency is fullfilled, I just copied the source code ( all the files present in the current directory ) and exposed the port where the application is listening to. This allows my application to take requests from the host machine where the docker daemon is running.
Next, I am setting the working directory. So any command I will run will be executed in that directory.
Then I am running the command to start the application. Save the file with the name Dockerfile.
All these statements are adding layers to the initial python image. The more layers you have, the bigger is the size of the image that it will create.
Now to build the image use the command:
-t flag is to tag the image with name:version -f flag is used to refer your dockerfile. ‘.’ is to set the context of the docker build to the current folder
And you can run the image to create a container:
-p flag to map host port to the container port
Now we have containerize the application. You can watch the video below for the demo:
Conclusion:
Dockerfile is an essential part of Docker. This helps us to understand how docker images are built and how we can create our own images. Try out the demo showed above and always try to follow the best practices mentioned in the documentation.
Important links