Skip to main content

Dockerizing Python Applications: A Practical Guide

Introduction: Docker and Its Importance in Software Development

Docker is a powerful platform for building, developing, and running applications that addresses common challenges in software development and deployment. By creating isolated and portable environments, it enables consistent application execution across different environments.

Key Benefits of Using Docker:

  1. Portability: Applications can be easily transferred between different systems.
  2. Isolated Environments: Each Docker container creates an independent environment from other applications.
  3. Dependency Management: Using Dockerfile application dependencies are easily managed.
  4. Integration with CI/CD: Dockerized applications integrate seamlessly into CI/CD processes.
  5. Enhanced Security: Docker allows applications to run in secure and isolated environments.

Creating a Dockerfile for Python Applications

To dockerize a Python application, the first step is to create a Dockerfile. This file contains instructions for building a Docker image. Below are examples of Dockerfile for various Python frameworks.

tip

If your application requires the installation of additional programs (such as mysql-client), write the installation commands in the run.sh file. This file will be executed before installing Python dependencies:

COPY ./run.sh /app/run.sh
RUN chmod +x /app/run.sh
RUN /app/run.sh
FROM python:3.10-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /app

COPY ./requirements.txt /app/requirements.txt

RUN apt-get update && apt-get install -y --no-install-recommends build-essential gcc

COPY ./run.sh /app/run.sh
RUN chmod +x /app/run.sh
RUN /app/run.sh

RUN pip install --upgrade pip
RUN pip install -r requirements.txt --no-cache-dir

COPY . /app

CMD ["python", "./app.py"]

Building and Running the Dockerfile

To build the Dockerfile and create an image, use the command:

docker build -t [ProjectName] .
  • -t: Assigns a tag and name to the project.

Then, to run it:

docker run -p outport:inport[5000] --name=container-name -d [ProjectName]
  • -p: Specifies the port for running the project.
  • outport: The external port.
  • inport: The internal port of the project defined in the Dockerfile.
  • --name: Assigns a name to the container.
  • -d: Runs the container in detached mode.
caution

Before deploying in a production environment, be sure to test your Docker image in a production-like environment.