How to Containerize a Python Application: A Step-by-Step Guide
Containerizing a Python application with Docker ensures consistent environments, easy deployment, and scalability. This tutorial walks you through the core steps—from writing a Dockerfile to building and running your container. No prior Docker experience needed, just a basic Python app and Docker installed.
1. Prepare Your Python Application
Start with a simple Python project. For example, a app.py that runs a Flask server or a script. Include a requirements.txt file listing all dependencies (e.g., flask). Your project folder should look like this:
- app.py
- requirements.txt
2. Write a Dockerfile
Create a file named Dockerfile (no extension) in the root. Use a slim Python base image to keep the container small. Here’s a typical example:
FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["python", "app.py"]
For a Flask app, change CMD to CMD ["python", "-m", "flask", "run", "--host=0.0.0.0"].
Key Dockerfile Instructions Explained
- FROM – Sets the base image (Python 3.11 slim).
- WORKDIR – Defines the working directory inside the container.
- COPY �� Copies files from your host to the container.
- RUN – Installs Python dependencies.
- CMD – Specifies the command to run when the container starts.
3. Build and Run the Container
Open a terminal in your project folder. Build the image with:
docker build -t my-python-app .
Then run a container from that image:
docker run -d -p 5000:5000 --name my-app my-python-app
The -p flag maps host port 5000 to container port 5000 (adjust if your app uses a different port). Your Python app is now running inside a Docker container.
4. Verify and Manage
Check running containers: docker ps. View logs: docker logs my-app. Stop the container: docker stop my-app. To rebuild after code changes, run docker build again (Docker caches layers for speed).
For more advanced setups, consider using docker-compose to orchestrate multi‑service apps (e.g., Python + Redis).
Conclusion
Containerization simplifies Python app deployment by packaging code, dependencies, and runtime into a single portable unit. With just a few lines in a Dockerfile, you can achieve reproducible builds and seamless scaling across environments. Start with the steps above and explore Docker’s ecosystem to optimize your workflow.