How to Containerize a Python Flask App with Docker: Beginner Tutorial
Containerizing a Python Flask app with Docker means packaging your Flask application, its dependencies, and runtime into a lightweight, portable container. This ensures your app runs consistently across any environment—from your laptop to a production server. In this beginner tutorial, you’ll learn to create a `Dockerfile`, build an image, and run your Flask app in a container. By the end, you’ll have a fully containerized Flask app ready for deployment.

Photo by Wolfgang Weiser on Pexels
## Why Containerize a Flask App with Docker?
Docker simplifies development and deployment. Here’s why you should use it:
- Consistency: No more “it works on my machine” issues.
- Isolation: Your app runs in a clean environment with its own dependencies.
- Portability: Deploy to any platform (AWS, Azure, DigitalOcean) without changes.
- Scalability: Easily scale your app with Docker Compose or orchestration tools.
## Prerequisites
Before starting, ensure you have:
- Python 3.8+ installed locally
- Docker Desktop installed (get it from docker.com)
- Basic knowledge of Flask and command line
## Step 1: Build a Simple Flask App
First, create a minimal Flask application. In a new folder named `flask-docker-app`, create these files:
### `app.py`
“`python
from flask import Flask
app = Flask(__name__)
@app.route(‘/’)
def home():
return “Hello, Dockerized Flask!”
if __name__ == ‘__main__’:
app.run(host=’0.0.0.0′, port=5000)
“`
### `requirements.txt`
“`
flask==2.3.3
“`
Tip: Always pin exact versions for reproducibility.
## Step 2: Create the Dockerfile
A `Dockerfile` is a blueprint for your container image. Here’s the one for our Flask app:
“`dockerfile
# Use official Python runtime as base image
FROM python:3.9-slim
# Set working directory inside container
WORKDIR /app
# Copy requirements first for better caching
COPY requirements.txt .
# Install dependencies
RUN pip install –no-cache-dir -r requirements.txt
# Copy the rest of the application code
COPY . .
# Expose port 5000
EXPOSE 5000
# Command to run the app
CMD [“python”, “app.py”]
“`
Key points:
- `FROM python:3.9-slim` uses a lightweight Python image (~120MB).
- `WORKDIR /app` sets the working directory.
- Copying `requirements.txt` first leverages Docker’s layer caching.

Photo by anshul kumar on Pexels
## Step 3: Build the Docker Image
Open a terminal in your project folder and run:
“`bash
docker build -t flask-app:latest .
“`
- `-t flask-app:latest` tags the image with a name and version.
- The `.` tells Docker to use the current directory.
Expected output: A success message with the image ID.
## Step 4: Run the Container
Now run your containerized Flask app:
“`bash
docker run -d -p 5000:5000 flask-app:latest
“`
- `-d` runs the container in detached mode (background).
- `-p 5000:5000` maps port 5000 on your host to port 5000 in the container.
Verify: Open `http://localhost:5000` in your browser. You should see “Hello, Dockerized Flask!”
### Common Commands Reference
| Command | Purpose |
|---|---|
| `docker ps` | List running containers |
| `docker stop |
Stop a container |
| `docker rm |
Remove a container |
| `docker images` | List all images |
| `docker rmi flask-app:latest` | Delete the image |
## Step 5: Use Docker Compose (Optional)
For multi-container apps (e.g., Flask + Redis), use `docker-compose.yml`. Here’s a simple version:
“`yaml
version: ‘3.8’
services:
web:
build: .
ports:
- “5000:5000”
“`
Run with: `docker-compose up -d`
## Step 6: Optimize Your Dockerfile
Make your image smaller and builds faster with these tips:
- Use multi-stage builds for production.
- Use `.dockerignore` to exclude unnecessary files (like `__pycache__`).
### Example `.dockerignore`
“`
__pycache__
*.pyc
.git
.env
“`
### Optimized Dockerfile (Production)
“`dockerfile
FROM python:3.9-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install –user –no-cache-dir -r requirements.txt
FROM python:3.9-slim
WORKDIR /app
COPY –from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
EXPOSE 5000
CMD [“python”, “app.py”]
“`

Photo by Gordon Plant on Pexels
## Troubleshooting Common Issues
- Port already in use: Change the host port: `docker run -p 5001:5000 flask-app:latest`
- Module not found: Ensure `requirements.txt` is correct and copied before `pip install`.
- Permission denied: On Linux, add your user to the `docker` group: `sudo usermod -aG docker $USER`
## Real-World Tips
- Use environment variables for configuration (e.g., `os.getenv(‘FLASK_ENV’, ‘production’)`).
- Log to stdout so Docker can capture logs: `app.logger.info(‘App started’)`.
- Health checks in Dockerfile: `HEALTHCHECK CMD curl –fail http://localhost:5000/ || exit 1`
## Conclusion
You’ve successfully containerized a Python Flask app with Docker! You now have a portable, consistent, and scalable application ready for deployment. This workflow works for any Flask project—just update your `requirements.txt` and code.
Next steps: Deploy your container to a cloud platform like AWS ECS, or use Docker Compose for a full stack with a database.
Ready to explore more? Visit freeresource.store for free AI tools, Docker deployment templates, and open-source resources to supercharge your projects. Sign up today and get instant access to our premium membership library!