Conceptualizing the Blueprint
I'm focused on the fundamental building blocks now. I've pinpointed the core elements: Docker, Flask, and Gunicorn. Next, I need to articulate the interactions between these three pieces, outlining how they connect to deliver a functional application.
Detailing the Implementation
I'm presently building out the details for each component. Flask's core logic will reside in app/main.py. The Dockerfile setup is underway, with a Python base image, installation of dependencies, and application code copying. Also, entrypoint.sh script is being defined for startup, plus an optional gunicorn_config.py to simplify command arguments.
Refining the Dockerfile
The Dockerfile is now coming together. I'm focusing on optimization, making it lean and efficient. I am making use of a multi-stage build to reduce the final image size, and setting up a non-root user. I'm also ensuring the application code is only copied after dependencies are installed to leverage Docker's caching.
Constructing the Output
I'm presently building the output, focusing on a clear, step-by-step presentation. I'm starting with the directory structure and then moving onto the specific file contents. I'm also including the essential components like Flask app, requirements, Gunicorn config, and Dockerfile. Security is key, hence implementing a non-root user. The wsgi.py entry point and application factory pattern are also being implemented for scalability.
Defining the Structure
I'm now mapping out the components and the directory structure. I'm focusing on a standard layout with app/main.py, a Dockerfile, and optional but recommended files like .env and docker-compose.yml. I'm also thinking of including a wsgi entry point for more robust applications.
Here is a production-ready boilerplate for a Dockerized Flask application using Gunicorn as the WSGI HTTP Server.
This setup focuses on security (running as a non-root user), modularity, and ease of use.
1. Project Structure
Create a folder for your project and set up the following file structure:
my-flask-app/
├── app/
│ ├── __init__.py
│ └── routes.py
├── .dockerignore
├── docker-compose.yml
├── Dockerfile
├── gunicorn_config.py
├── requirements.txt
└── wsgi.py
2. The Files
requirements.txt
Define your dependencies.
flask
gunicorn
app/__init__.py
Using the "Application Factory" pattern is best practice for Flask.
from flask import Flask
def create_app():
app = Flask(__name__)
# Import and register blueprints/routes
from app.routes import main
app.register_blueprint(main)
return app
app/routes.py
A simple route definition.
from flask import Blueprint, jsonify
main = Blueprint('main', __name__)
@main.route('/')
def home():
return jsonify({
"message": "Hello from Dockerized Flask!",
"status": "success"
})
wsgi.py
The entry point for Gunicorn to hook into.
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run()
gunicorn_config.py
Configuring Gunicorn via a python file is cleaner than long command-line arguments.
import os
workers = int(os.environ.get('GUNICORN_PROCESSES', '2'))
threads = int(os.environ.get('GUNICORN_THREADS', '4'))
# timeout = int(os.environ.get('GUNICORN_TIMEOUT', '120'))
bind = os.environ.get('GUNICORN_BIND', '0.0.0.0:8000')
forwarded_allow_ips = '*'
secure_scheme_headers = { 'X-Forwarded-Proto': 'https' }
Dockerfile
This Dockerfile sets up a secure environment, installs dependencies, and creates a non-root user.
# Use an official Python runtime as a parent image
FROM python:3.11-slim
# Set environment variables
# PYTHONDONTWRITEBYTECODE: Prevents Python from writing .pyc files to disc
# PYTHONUNBUFFERED: Ensures console output is not buffered by Docker
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install dependencies
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
# Copy the current directory contents into the container at /app
COPY . /app/
# Create a non-root user and switch to it (Security Best Practice)
RUN useradd -m appuser && chown -R appuser /app
USER appuser
# Expose the port the app runs on
EXPOSE 8000
# Run the application
CMD ["gunicorn", "--config", "gunicorn_config.py", "wsgi:app"]
.dockerignore
Prevent unnecessary files from being copied into the image to keep it small and secure.
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.git
.gitignore
docker-compose.yml
Dockerfile
docker-compose.yml
To simplify building and running the container.
services:
web:
build: .
container_name: flask_app
restart: always
ports:
- "8000:8000"
environment:
- GUNICORN_PROCESSES=3
- GUNICORN_THREADS=4
# Optional: Mount volume for local development (updates code without rebuilding)
# volumes:
# - .:/app
3. How to Run
1. Build and Run
Run the following command in the root directory:
docker-compose up --build
2. Test
Open your browser or use curl to interact with the API:
curl http://localhost:8000
Expected Output:
{"message":"Hello from Dockerized Flask!","status":"success"}
4. Key Features of this Boilerplate
- Production Ready: Uses Gunicorn instead of the built-in Flask development server.
- Security: The Dockerfile creates a specific user (
appuser) so the application does not run as root.
- Optimized: The
slim Python image is used to keep the image size small, and flags prevent Python from generating unnecessary cache files.
- Configurable: Gunicorn settings (workers, threads, port) can be adjusted easily via environment variables in the
docker-compose.yml file.