Project: Add a Database with Compose
This project adds a Postgres database to the Flask app with Compose. One file starts both services, the app reads the database, and the data lives in a named volume.
The compose file
Two services: the app and its database, on one network.
services:
web:
build: .
ports:
- "8113:5000"
environment:
DATABASE_URL: postgresql://postgres:secret@db:5432/appdb
depends_on:
db:
condition: service_healthy
db:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
volumes:
pgdata:The requirements
Two lines name Flask and the Postgres driver to install.
Flask==3.1.0
psycopg2-binary==2.9.10The app reads the database
The app counts the rows in a table and prints the count.
from flask import Flask
import os, psycopg2
app = Flask(__name__)
@app.route("/")
def home():
conn = psycopg2.connect(os.environ["DATABASE_URL"])
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS visits (id SERIAL PRIMARY KEY)")
cur.execute("SELECT COUNT(*) FROM visits")
n = cur.fetchone()[0]
cur.execute("INSERT INTO visits DEFAULT VALUES")
conn.commit()
return f"Visit number {n + 1}"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)Example
docker compose -p g6proj up -d --build >/dev/null
sleep 5
curl -s http://localhost:8113/
curl -s http://localhost:8113/
docker compose -p g6proj downKey points
- The compose file has two services: the Flask app and Postgres.
- depends_on starts the app after the database is healthy.
- The app reads the database address from an environment variable.
- The database stores its data in a named volume.
- One docker compose up starts the whole app.
In this example, Compose builds the app image and starts the app with its database. The first curl prints visit number 1, and the second prints visit number 2. The rising count proves the app writes to the database and the data persists across requests.
Note
The app connects by the service name db, not by an IP address.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
How does the Flask app reach the database in Compose?