Containerize a Flask web application and connect it to a PostgreSQL database using Docker. Deploy the application with Docker Compose for easy development, testing, and deployment.
flask_postgres_docker/ │ ├── app/ │ ├── app.py # Flask application code │ ├── Dockerfile # Dockerfile to containerize Flask │ └── requirements.txt # Python dependencies (optional, for Dockerfile) │ ├── postgres/ # Optional directory for PostgreSQL data │ └── (empty, Docker volumes will handle data persistence) │ ├── docker-compose.yml # Docker Compose configuration for Flask and PostgreSQL ├── README.md # Optional, project documentation
Create a project directory:
mkdir flask_postgres_docker
cd flask_postgres_docker
Inside the directory, create an app
folder for the Flask app:
mkdir app
Create a Python virtual environment (venv
) for local development and testing:
python3 -m venv venv
source venv/bin/activate # For Linux/Mac
venv\\Scripts\\activate # For Windows
Inside the app
folder, create app.py
:
from flask import Flask, jsonify
import psycopg2
app = Flask(__name__)
def get_db_connection():
conn = psycopg2.connect(
host="db", # Docker Compose service name
database="flaskdb",
user="flaskuser",
password="flaskpassword"
)
return conn
@app.route('/')
def index():
conn = get_db_connection()
cur = conn.cursor()
cur.execute('SELECT version();')
db_version = cur.fetchone()
cur.close()
conn.close()
return jsonify({'db_version': db_version[0]})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Install Flask and psycopg2 in the virtual environment:
pip install flask psycopg2-binary
<aside> 💡
psycopg2-binary
is a PostgreSQL adapter for Python. It allows Python code to interact with a PostgreSQL database.
</aside>
Freeze the dependencies into a requirements.txt
file:
pip freeze > requirements.txt
<aside> 💡
The command pip freeze > requirements.txt
is used to generate a requirements.txt
file that lists all the installed Python packages in your current environment along with their versions.
</aside>
Inside the app
folder, create a Dockerfile
:
# Use an official Python runtime as a base image
FROM python:3.9-slim
# Set the working directory
WORKDIR /app
# Copy the application code
COPY . /app
# Install dependencies
RUN pip install -r requirements.txt
# Expose port 5000
EXPOSE 5000
# Run the Flask app
CMD ["python", "app.py"]
Create a folder named postgres
to store the database configuration.
Inside the project folder, create a docker-compose.yml
file:
version: '3.8'
services:
web:
build:
context: ./app
ports:
- "5000:5000"
depends_on:
- db
environment:
- FLASK_ENV=development
db:
image: postgres:13
environment:
POSTGRES_USER: flaskuser
POSTGRES_PASSWORD: flaskpassword
POSTGRES_DB: flaskdb
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data: