WHAT THE FAQ

Dockerizing a Python Project: Step-by-Step Guide

 

Dockerizing a Python Project: Step-by-Step Guide

In this blog post, we will learn how to Dockerize a Python project. Docker is a tool that allows you to package and run an application in a lightweight container, ensuring that it works consistently across different environments.

Folder Structure

Let’s start by setting up a folder structure for our Python project. It will look like this:

/my_python_project
├── /app
│ ├── actions.py
│ ├── config.py
│ ├── login.py
│ ├── main.py
│ ├── merged_script.py
│ ├── navigate.py
│ └── setup.py
│
├── Dockerfile
├── requirements.txt
└── README.md

Step 1: Create Project Directory

Start by creating a directory for your project and moving your Python files into a subfolder named app:

mkdir my_python_project
cd my_python_project
mkdir app
mv /path/to/your/files/* ./app/

Step 2: Create requirements.txt

In the root directory, create a requirements.txt file that lists all the dependencies required for the project. Below is an example:

# requirements.txt
selenium==4.1.0
pandas==1.4.0
requests==2.26.0

Step 3: Create a Dockerfile

Now, let’s create the Dockerfile. This file tells Docker how to build your application image. Add the following content:

# Dockerfile
# Use Python official image
FROM python:3.8-slim

# Set the working directory in the container
WORKDIR /app

# Copy requirements.txt into the container
COPY requirements.txt .

# Install the dependencies
RUN pip install --upgrade pip
RUN pip install -r requirements.txt

# Copy the rest of your application code into the container
COPY ./app /app

# Command to run the application
CMD ["python", "main.py"]

Step 4: Build and Run the Docker Container

With the Dockerfile in place, you can now build and run the Docker container. Use the following commands:

# Build the Docker image
docker build -t my_python_app .

# Run the Docker container
docker run -it --rm my_python_app

Step 5: README File

It’s always a good practice to include a README.md file that provides instructions on how to set up and run your application. Here’s an example of what you can add to your README:

# My Python Project

## Prerequisites
- Docker
- Python 3.8+

## Running the Project with Docker

1. Build the Docker image:

```bash
docker build -t my_python_app .
```

2. Run the Docker container:

```bash
docker run -it --rm my_python_app
```

## Running Locally

1. Set up a virtual environment:

```bash
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
```

2. Install the required dependencies:

```bash
pip install -r requirements.txt
```

3. Run the app:

```bash
python app/main.py
```

Conclusion

With Docker, you can easily package your Python application and ensure it runs consistently across various environments. By following the steps outlined in this post, you should now be able to build and run your Python project inside a Docker container.

Exit mobile version