Containerize a Python Application using Docker
This article aims to outline the basics of docker and learn how to build an image that runs a Python application in a container.
What is Docker?
It is a platform for developing, shipping, and running applications. In simple terms, you can build your application, package them along with their dependencies into a container, and then these containers can be shipped to run on other machines.
Key Terminologies
- Dockerfile- A text file that consists of instructions and arguments. It informs Docker how the image should get built.
- Image- It is a read-only template with instructions for creating a container. Each instruction in a Dockerfile creates a layer in the image.
- Container- It is a running instance of an image. It is well defined by its image as well as any configuration options provided to it create or start.
The above diagram shows multiple running instances (container) of the same image (template) which was created or built using a Dockerfile.
Dockerfile Instruction
A Dockerfile consists of a set of instructions and arguments. The general syntax is
INSTRUCTION arguments
The most commonly used Dockerfile instructions are :
Docker Commands
The most commonly used docker commands are :
Getting Started
We will create a simple project to containerize a Python application by following the steps mentioned below :
- Create a simple static web application using flask
- Create a Dockerfile
- Build image out of Dockerfile
- Run the image in the container
1. Installation
2. Code
- app.py
- home.html
- requirements.txt
- Dockerfile
3. Run
Open terminal and navigate to the project .
- Build an image out of Dockerfile by running the following command below. Pass in the
-t
parameter to name the image .
docker build -t sample .
- To verify the image built use the following command
docker images
- Run the docker container . The
-p
flag maps a port running inside the container to your host. The — — name is used to give name to the container and sample is image name which was built earlier .
docker run --name flask_app -p 8000:5000 sample
- Open the browser and type
http:://127.0.0.1:8000/
Conclusion
In this story, we have seen the basics of docker and learnt how to containerize a Python application using docker in simple steps. Hope you have understood the basics of docker.
Thanks for reading!