Technical Guide: Setting Up A Flask Web Application With Docker, PostgreSQL, and Nginx
Technical Guide: Setting Up A Flask Web Application With Docker, PostgreSQL, and Nginx
Nginx
Introduction
In this guide, we will walk through the process of setting up a basic Flask web
application in a Dockerized environment with PostgreSQL as the database and Nginx
as the reverse proxy server. This setup is ideal for scalable production-ready
environments.
Prerequisites
Docker
Docker Compose
Basic understanding of Python, Flask, and Docker
bash
my_flask_app/
├── app/
│ ├── __init__.py
│ ├── routes.py
├── Dockerfile
├── requirements.txt
└── docker-compose.yml
Create app/__init__.py:
python
def create_app():
"""Initialize the core application"""
app = Flask(__name__)
with app.app_context():
from . import routes
return app
Create app/routes.py:
python
@app.route('/')
def home():
"""Route to return a simple JSON response."""
return jsonify({"message": "Welcome to the Flask App!"})
1.2 Requirements
Create requirements.txt to specify the Python packages needed for the Flask app:
txt
Flask==1.1.2
psycopg2-binary==2.8.6
gunicorn==20.0.4
2. Docker Setup
2.1 Dockerfile
Dockerfile
2.2 docker-compose.yml
yaml
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
depends_on:
- db
environment:
- DATABASE_URL=postgresql://postgres:password@db/postgres
networks:
- app-network
db:
image: postgres:12.0
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- app-network
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- web
networks:
- app-network
volumes:
postgres_data:
networks:
app-network:
3. Configuring Nginx
nginx
server {
listen 80;
location / {
proxy_pass http://web:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
To build and run the containers, navigate to the root project directory
(my_flask_app/) and run:
bash
docker-compose up --build
To connect Flask to PostgreSQL, modify the database URI inside your Flask
configuration.
python
import os
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
db.init_app(app)
with app.app_context():
from . import routes
db.create_all()
return app
Conclusion
You now have a working Flask application with PostgreSQL and Nginx, all managed
through Docker. This setup can be expanded and adapted for larger-scale production
applications, with additional security and optimization practices for performance.