Deploying Flask Applications with Docker and Nginx
"It works on my machine" is the developer's famous last words. To ensure my applications run consistently everywhere, I've fully embraced Docker.
Containerization
I wrap my Flask application in a Docker container. My Dockerfile starts with a lightweight Python image (python:3.11-slim), installs dependencies from requirements.txt, and uses Gunicorn as the production WSGI server.
dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:create_app()"]
Reverse Proxy
I don't expose Gunicorn directly to the internet. Instead, I use Nginx as a reverse proxy. Nginx handles SSL termination (using Let's Encrypt), serves static files efficiently, and forwards API requests to the Flask container.
Docker Compose
I use docker-compose to orchestrate the services (Flask, Nginx, and sometimes a separate DB container). This allows me to spin up the entire production stack locally with a single command: docker-compose up.
Deployment is no longer a headache; it's a repeatable, automated process.