The user wants a boilerplate for a Dockerized Flask application using Gunicorn.
Key Components Required:
- Application Code (
app.py): A simple "Hello World" Flask app.
- Dependencies (
requirements.txt): Needs Flask and gunicorn.
- Docker Configuration (
Dockerfile): Needs to set up the Python environment, copy files, install dependencies, expose the port, and define the run command with Gunicorn.
- Docker Compose (
docker-compose.yml - Optional but recommended): Makes building and running easier.
- Docker Ignore (
.dockerignore): To keep the image lean.
Structure:
my-app/
app/
__init__.py (or just main.py) -> Let's stick to a single app.py for simplicity, or a structured app/__init__.py for best practice. I'll use a standard app.py for the boilerplate as it's easier to grasp, but maybe mention structure.
requirements.txt
Dockerfile
.dockerignore
Drafting the Content:
Refining the Boilerplate:
To make it a good boilerplate, I should organize the files properly. A project folder structure is better than flat files.
Proposed Structure:
project/
├── app/
│ └── main.py
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
└── .dockerignore
Step-by-Step Implementation Details:
requirements.txt: Pin versions? No, generic is fine for boilerplate, but I'll leave placeholders.
app/main.py: Standard Flask setup.
Dockerfile:
- Use
python:3.11-slim (newer stable).
- Create a non-root user (security best practice). This adds a bit of complexity but is worth it for a "production-ready" boilerplate hint.
- Wait, keep it simple first. Standard root user is fine for a basic boilerplate, but I'll add a comment about non-root. Actually, let's stick to the most standard, simple approach that works out of the box.
- Run Command:
gunicorn -w 4 -b 0.0.0.0:5000 app.main:app (since it's in a subfolder).
Let's re-evaluate the structure.
If I put the app in an app directory, the import in the gunicorn command changes.
Command: gunicorn -b 0.0.0.0:5000 "app.main:create_app()" or just app.main:app.
Let's stick to a flat structure for the absolute simplest boilerplate, or a slightly structured one.
Decision: I will use a slightly structured one because it feels more "real world".
Folder: src or app.
Let's go with:
app.py (in root) for simplicity, or app/main.py.
I will provide the flat file structure as it is the most requested "boilerplate" format.
Files:
requirements.txt
Dockerfile
app.py
docker-compose.yml (Highly recommended for ease of use).
Code content:
-
Dockerfile:
FROM python:3.11-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"]
-
docker-compose.yml:
version: '3.8'
services:
web:
build: .
ports:
- "5000:5000"
Additional Polish:
- Add
.dockerignore.
- Add comments explaining the Gunicorn command arguments (workers, bind, timeout).
Final Review:
Does this meet the prompt? "Dockerized Flask application with Gunicorn". Yes.
Is it copy-pasteable? Yes.
Let's construct the final response. I will present the directory structure, then the code for each file, then instructions on how to run it.
Self-Correction during drafting:
Should I include an entrypoint script? No, over-engineering for a boilerplate.
Should I use alpine? slim is generally preferred over alpine for Python due to wheel compatibility issues, though alpine is smaller. I'll stick to slim for reliability.
Let's write it out.
Here is a complete, production-ready boilerplate for a Dockerized Flask application served by Gunicorn.
Project Structure
Create a folder for your project and set up the following structure:
my-flask-app/
├── app/
│ ├── __init__.py # The Flask application
│ └── main.py # Entry point
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── .dockerignore # Files to ignore in Docker build
└── docker-compose.yml # (Optional) Easy orchestration
1. The Application Code
requirements.txt
We include gunicorn here so it is installed inside the Docker image.
Flask==3.0.0
gunicorn==21.2.0
app/__init__.py
A simple Hello World Flask app.
from flask import Flask
def create_app():
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World! Running on Gunicorn inside Docker.</p>"
return app
app/main.py
This is the entry point that Gunicorn will look for.
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
2. The Docker Configuration
.dockerignore
This prevents copying unnecessary files (like your local virtual environment or git files) into the Docker image, speeding up builds.
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.git
.gitignore
.dockerignore
Dockerfile
docker-compose.yml
Dockerfile
This uses a lightweight Python image (slim), creates a non-root user for security, and configures Gunicorn.
# Use an official lightweight Python image
# "slim" variants are smaller and more secure than "alpine" for Python
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Set environment variables
# Prevents Python from writing .pyc files to disc
ENV PYTHONDONTWRITEBYTECODE 1
# Prevents Python from buffering stdout and stderr
ENV PYTHONUNBUFFERED 1
# Install system dependencies (optional, but good practice if you add DB drivers later)
RUN apt-get update && apt-get install -y --no-install-recommends gcc
# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code
COPY . .
# Create a non-root user and switch to it for security
RUN adduser --disabled-password --gecos '' myuser
USER myuser
# Expose the port the app runs on
EXPOSE 5000
# Run the application with Gunicorn
# -w 4: Use 4 worker processes
# -b 0.0.0.0:5000: Bind to all network interfaces on port 5000
# "app.main:app": Points to the 'app' variable inside 'app/main.py'
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app.main:app"]
3. Orchestration (Optional)
docker-compose.yml
This makes building and running the container easier with a single command.
version: '3.8'
services:
web:
build: .
ports:
- "5000:5000"
# Override the default command for development if needed (e.g., enable auto-reload)
# command: gunicorn -w 4 -b 0.0.0.0:5000 app.main:app --reload
How to Run
Option A: Using Docker Compose (Recommended)
- Run the build and start command:
docker-compose up --build
- Open your browser to
http://localhost:5000.
Option B: Using Docker Commands directly
- Build the image:
docker build -t my-flask-app .
- Run the container:
docker run -p 5000:5000 my-flask-app
Explanation of Gunicorn Flags
-w 4: This tells Gunicorn to spawn 4 worker processes. A general rule of thumb is (2 x CPU_cores) + 1.
-b 0.0.0.0:5000: This binds the server to all available network interfaces (inside the container) on port 5000.
app.main:app: This syntax means "Look in the folder app, find the file main.py, and load the object named app."