Containerize a Python Application using Docker

Ashish MJ
Dev Genius
Published in
3 min readOct 8, 2022

--

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.
Multiple running instances (container) of the same image (template)

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 :

Commonly used Dockerfile instructions
Sample Dockerfile

Docker Commands

The most commonly used docker commands are :

Commonly used docker commands

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
Project structure

1. Installation

2. Code

  • app.py
app.py
  • home.html
home.html
  • requirements.txt
requirements.txt
  • Dockerfile
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 .
docker build
Successfully built
  • To verify the image built use the following command
docker images
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
docker run
  • Open the browser and type
http:://127.0.0.1:8000/
Flask application

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!

Github Website Linkedin

--

--

A Software Engineer with a demonstrated history of working in the IT .A keen learner, who always strives to feed curiosity and learn about new technologies.