Framing the Boilerplate
I'm now zeroing in on the user's objective: a Dockerized Flask application boilerplate, powered by Gunicorn. The core idea is to furnish a readily usable starting point. I'm focusing on simplicity, emphasizing ease of use for the user.
Outlining the Structure
Currently, I'm constructing a modular and extensible project structure for the boilerplate. I'm prioritizing clear separation of concerns, with distinct directories for the application code, configuration files, and Docker-related components. The docker-compose.yml file is taking shape to streamline deployment, and I'm ensuring all necessary configuration files are included.
Constructing the Pieces
I'm presently building the requirements.txt file, including Flask, Gunicorn, and considering python-dotenv. Moving to the Gunicorn configuration file, I'll explore parameters for optimal performance. I'm focusing on defining the entry point for Gunicorn through the wsgi.py file, enabling flexibility for different run environments. I will also incorporate sensible defaults.
Developing the Blueprint
I've decided to prioritize ease of use, even over scalability, for this boilerplate. Consequently, I opted for a single main.py file to simplify the Flask app. I've also completed the wsgi.py file, linking the Flask app to Gunicorn. The Gunicorn configuration will be critical, so I'm researching parameters.
Defining the App's Core
I'm presently focusing on the app/ directory and its contents. I've designed the main.py file with a simple "Hello World" route and built the wsgi.py file to handle Gunicorn's entry point. I am now finalizing the structure, including .env handling.
This consists of a production-ready boilerplate. It includes the file structure, the Flask code, a hardened Dockerfile (using a non-root user), Gunicorn configuration, and a docker-compose file for easy orchestration.
Project Structure
Create a folder and set up the following file structure:
my-flask-app/
├── app/
│ ├── __init__.py
│ └── main.py
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
├── gunicorn_config.py
├── .dockerignore
└── .gitignore
1. Application Code
app/main.py
A simple Flask application entry point.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return {
"message": "Hello from Dockerized Flask & Gunicorn!",
"status": "success"
}
if __name__ == "__main__":
# For local development only
app.run(host="0.0.0.0", port=5000)
app/__init__.py
(Leave empty, makes the directory a Python package).
2. Dependency Management
requirements.txt
Flask==3.0.0
gunicorn==21.2.0
3. Gunicorn Configuration
gunicorn_config.py
Using a config file allows for cleaner Docker commands and easier tuning.
import os
import multiprocessing
# Check for available CPUs, use 2 * CPU + 1 workers formula
workers = multiprocessing.cpu_count() * 2 + 1
# Bind to port 8000 (exposed in Dockerfile)
bind = "0.0.0.0:8000"
# Basic logging
loglevel = "info"
accesslog = "-" # Print to stdout
errorlog = "-" # Print to stderr
# Worker class (use 'gevent' if you need async capabilities, requires installing gevent)
worker_class = "sync"
# Time out to prevent hanging workers
timeout = 120
4. Dockerfile
Dockerfile
This uses a slim Python image and creates a non-root user for security best practices.
# Use official lightweight Python image
FROM python:3.11-slim
# Set environment variables
# Prevents Python from writing pyc files to disc
ENV PYTHONDONTWRITEBYTECODE=1
# Prevents Python from buffering stdout and stderr
ENV PYTHONUNBUFFERED=1
# Set working directory
WORKDIR /app
# Install dependencies
# Copy only requirements first to leverage Docker cache
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Create a non-root user and group
RUN groupadd -r appuser && useradd -r -g appuser appuser
# Copy project files
COPY . .
# Change ownership of the app directory to the non-root user
RUN chown -R appuser:appuser /app
# Switch to non-root user
USER appuser
# Expose the port Gunicorn will run on
EXPOSE 8000
# Command to run the application
# Pointing to 'app.main:app' means: look in folder 'app', file 'main.py', variable 'app'
CMD ["gunicorn", "-c", "gunicorn_config.py", "app.main:app"]
5. Docker Compose
docker-compose.yml
version: '3.8'
services:
web:
build: .
container_name: flask_gunicorn_app
ports:
- "8000:8000"
volumes:
# Mount current directory to /app for hot-reloading code changes
# (Note: Gunicorn needs --reload flag config to see these changes, see below)
- ./:/app
environment:
- FLASK_ENV=production
restart: unless-stopped
6. Ignore Files
.dockerignore
Prevents unnecessary files from bloating the Docker image.
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.git/
.gitignore
docker-compose.yml
README.md
.gitignore
__pycache__/
venv/
.env
*.pyc
How to Run
- Build and Run:
docker-compose up --build
- Access the App:
Open your browser or Postman and go to
http://localhost:8000.
Development vs. Production
The boilerplate above is set for Production.
If you want to use this for Development (with hot-reloading), modify the CMD in the Dockerfile (or override it in docker-compose.yml) to add the --reload flag:
In docker-compose.yml:
services:
web:
# ... existing config ...
command: gunicorn -c gunicorn_config.py --reload app.main:app
Note: Do not usage --reload in production as it consumes significant resources.