Building and Containerizing a Python Application Using Docker


Containerizing Python applications with Docker simplifies dependencies management, ensures consistency across multiple environments, and enhances deployment processes. This guide will walk you through the process of creating a Dockerfile for a simple Python application, building the Docker image, and running it as a container.


  • Python: Basic knowledge of Python programming.

  • Docker: Docker must be installed on your system. You can download it from Docker Hub.

Step-by-Step Guide to Containerizing a Python Application

1. Creating a Python Application

First, create a simple Python application. Here's a basic example of a Python app that runs a simple HTTP server:

from http.server import BaseHTTPRequestHandler, HTTPServer

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.wfile.write(b'Hello, Docker!')

def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    print('Server starting on port 8000...')

if __name__ == '__main__':

Save this script as in your project directory.

2. Writing the Dockerfile

Next, create a Dockerfile to specify how the Docker image should be built:


# Use an official Python runtime as a parent image
FROM python:3.8-slim

# Set the working directory to /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir http.server

# Make port 8000 available to the world outside this container

# Define environment variable

# Run when the container launches
CMD ["python", ""]

This Dockerfile uses the official Python 3.8 slim image, copies the application into the image, installs dependencies, and specifies how to run the application.

3. Building the Docker Image

Build your Docker image using the following command:

Example Command:

docker build -t python-app .

Expected Output:

Sending build context to Docker daemon  4.096kB
Step 1/6 : FROM python:3.8-slim
 ---> 3d8f801fc3db
Step 2/6 : WORKDIR /app
 ---> Using cache
 ---> d4d1b5213eef
Step 3/6 : COPY . /app
 ---> a2c10c4072fa
Step 4/6 : RUN pip install --no-cache-dir http.server
 ---> Running in 7d26cd4f620e
Collecting http.server
Successfully built af3c33f0dc25
Successfully tagged python-app:latest

4. Running the Docker Container

Run your Docker container using the command:

Example Command:

docker run -p 8000:8000 python-app

Expected Output:

Server starting on port 8000...

You can now access your application at http://localhost:8000 to see "Hello, Docker!".


Containerizing a Python application with Docker not only simplifies deployment but also ensures that the application runs consistently across different environments. This setup is ideal for development, testing, and production phases.

Additional Resources