Ravindra BagaleCourses & study guides मराठी

Chapter 57: Docker Projects Part 1: Websites, Databases, LAMP, LEMP, WordPress, 3-Tier and Every Language with MySQL and MongoDB

DevOps

57.5 Project 5: Python FastAPI with MySQL, MongoDB and PostgreSQL (Alembic as a one-off job)

Friends, today one FastAPI image talks to MySQL, MongoDB or PostgreSQL by changing env vars. We add Alembic as a one-off migrate job, wait with service_completed_successfully, test each database, and clean up. Type every command yourself.

What you will learn in this lesson

  1. Why one API image can talk to three databases.
  2. How pure Python drivers keep the image simple.
  3. How Alembic runs as a one-off Compose job.
  4. How service_completed_successfully makes the API wait for migrations.
  5. How project names keep two stacks apart on one machine.

1. Start from a real problem

Suppose we are at Zomato and a new team builds a small notes API for restaurant partners in Python. Some partners already use MySQL, some use Postgres, and a menu team wants MongoDB documents.

Installing three databases and three Python virtualenvs on every laptop wastes a day. With Docker we write one FastAPI image and point it at each database with environment variables.

We also run database schema changes as a short-lived migrate container so the API never starts on an old schema.

FastAPI imagesame code everywhereDB_ENGINE=mysql|postgres|mongoenv chooses the drivermigrate jobAlembic once, then exitsAPI servicestarts after migrate succeeds
Picture 1: one image, three databases

2. Project folder and app code

Step 1: Folders and dependencies

Why: A small Python API.

What: We keep the app under app/, migrations under alembic/, and Compose files at the root.

Example 1: Make folders

Type this:

mkdir -p notes-api/app notes-api/alembic/versions && cd notes-api && pwd

You will see:

/home/you/notes-api

What it means: Project root ready.

Example 2: Write requirements.txt

Type this:

printf '%s\n' 'fastapi==0.115.0' 'uvicorn[standard]==0.30.6' 'mysql-connector-python==9.0.0' 'psycopg[binary]==3.2.1' 'pymongo==4.8.0' 'sqlalchemy==2.0.35' 'alembic==1.13.2' > requirements.txt && wc -l requirements.txt

You will see:

7 requirements.txt

What it means: Web server, three drivers, SQLAlchemy and Alembic.

Example 3: Ignore junk

Type this:

printf '%s\n' '.env' '__pycache__/' '.venv/' '*.pyc' > .gitignore && cat .gitignore

You will see:

.env
__pycache__/
.venv/
*.pyc

What it means: Local junk stays out of Git.

Step 2: FastAPI app

Why: One code path, env chooses the database.

What: The app reads DB_ENGINE and opens MySQL, Postgres or Mongo. Routes create and list partner notes.

Example 4: Write app/main.py

Type this:

printf '%s\n' 'import os' 'from fastapi import FastAPI' 'from pydantic import BaseModel' '' 'app = FastAPI(title="Partner notes API")' 'ENGINE = os.getenv("DB_ENGINE", "mysql")' '' 'class Note(BaseModel):' '    partner: str' '    text: str' '' 'def store():' '    if ENGINE == "mongo":' '        from pymongo import MongoClient' '        return MongoClient(os.environ["MONGO_URL"])["notes"]["items"]' '    from sqlalchemy import create_engine, text' '    return create_engine(os.environ["DATABASE_URL"])' '' '@app.get("/healthz")' 'def health():' '    s = store()' '    if ENGINE == "mongo":' '        s.database.command("ping"); return {"ok": True, "engine": ENGINE}' '    with s.connect() as c: c.execute(text("SELECT 1")); return {"ok": True, "engine": ENGINE}' '' '@app.post("/notes")' 'def add(note: Note):' '    s = store()' '    if ENGINE == "mongo":' '        s.insert_one(note.model_dump()); return {"saved": True}' '    q = text("INSERT INTO notes (partner, text) VALUES (:p, :t)")' '    with s.begin() as c: c.execute(q, {"p": note.partner, "t": note.text})' '    return {"saved": True}' '' '@app.get("/notes")' 'def list_notes():' '    s = store()' '    if ENGINE == "mongo":' '        return list(s.find({}, {"_id": 0}))' '    with s.connect() as c:' '        rows = c.execute(text("SELECT partner, text FROM notes")).mappings().all()' '        return [dict(r) for r in rows]' > app/main.py && wc -l app/main.py

You will see:

40 app/main.py

What it means: Health, create and list for all three engines.

Example 5: Show engine switch

Type this:

grep ENGINE app/main.py | head -2

You will see:

ENGINE = os.getenv("DB_ENGINE", "mysql")

What it means: Default engine is mysql.

Example 6: Show health route

Type this:

grep -A2 'healthz' app/main.py | head -3

You will see:

@app.get("/healthz")
def health():

What it means: Health pings the chosen database.

3. Dockerfile and Alembic

Step 3: API Dockerfile

Why: Same image for every engine.

What: Install requirements once. Pure Python drivers mean no OS database client packages. The migrate job reuses this image with a different command.

Example 7: Write Dockerfile

Type this:

printf '%s\n' 'FROM python:3.12-slim' 'WORKDIR /app' 'ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1' 'COPY requirements.txt .' 'RUN pip install --no-cache-dir -r requirements.txt' 'COPY app/ ./app/' 'COPY alembic.ini .' 'COPY alembic/ ./alembic/' 'EXPOSE 8000' 'CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]' > Dockerfile && wc -l Dockerfile

You will see:

10 Dockerfile

What it means: Slim Python image with uvicorn as the default command.

Example 8: Write .dockerignore

Type this:

printf '%s\n' '.venv' '__pycache__' '.env' '*.pyc' > .dockerignore && cat .dockerignore

You will see:

.venv
__pycache__
.env
*.pyc

What it means: Local venv never enters the build.

Example 9: Show default CMD

Type this:

grep '^CMD' Dockerfile

You will see:

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

What it means: Migrate job will override this command.

Step 4: Alembic migration

Why: Schema change as code.

What: For MySQL and Postgres we create a notes table with Alembic. Mongo needs no relational migration.

Example 10: Write alembic.ini stub

Type this:

printf '%s\n' '[alembic]' 'script_location = alembic' 'sqlalchemy.url = driver://user:pass@localhost/dbname' > alembic.ini && printf '%s\n' 'from alembic import op' 'import sqlalchemy as sa' 'revision = "0001"' 'down_revision = None' 'def upgrade():' '    op.create_table("notes", sa.Column("id", sa.Integer, primary_key=True),' '        sa.Column("partner", sa.String(120), nullable=False),' '        sa.Column("text", sa.Text, nullable=False))' 'def downgrade():' '    op.drop_table("notes")' > alembic/versions/0001_notes.py && wc -l alembic/versions/0001_notes.py

You will see:

9 alembic/versions/0001_notes.py

What it means: First revision creates the notes table.

Example 11: Show revision id

Type this:

grep revision alembic/versions/0001_notes.py

You will see:

revision = "0001"

What it means: Compose migrate job will run alembic upgrade head.

Example 12: List migration files

Type this:

find alembic -type f | sort

You will see:

alembic/versions/0001_notes.py

What it means: One revision for this project.

4. Compose for MySQL with migrate job

db healthyMySQL accepts connectionsmigrate containeralembic upgrade head, then exits 0api startscondition: service_completed_successfully
Picture 2: migrate then API

Step 5: MySQL Compose file

Why: Migrate runs once.

What: depends_on with condition service_completed_successfully waits until the migrate container exits zero. Then the API starts on the new schema.

Example 13: Write compose.mysql.yaml

Type this:

printf '%s\n' 'name: notes-mysql' 'services:' '  db:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: notes' '      MYSQL_USER: notes' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' '    volumes: [mysql-data:/var/lib/mysql]' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${DB_ROOT_PASSWORD}"]' '      interval: 5s' '      retries: 20' '' '  migrate:' '    build: .' '    command: ["alembic", "upgrade", "head"]' '    environment:' '      DATABASE_URL: mysql+mysqlconnector://notes:${DB_PASSWORD}@db:3306/notes' '    depends_on:' '      db:' '        condition: service_healthy' '' '  api:' '    build: .' '    ports: ["8000:8000"]' '    environment:' '      DB_ENGINE: mysql' '      DATABASE_URL: mysql+mysqlconnector://notes:${DB_PASSWORD}@db:3306/notes' '    depends_on:' '      migrate:' '        condition: service_completed_successfully' '' 'volumes:' '  mysql-data:' > compose.mysql.yaml && wc -l compose.mysql.yaml

You will see:

35 compose.mysql.yaml

What it means: name: notes-mysql keeps this stack apart from others.

Example 14: Write .env

Type this:

printf '%s\n' 'DB_PASSWORD=notes-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && cat .env

You will see:

DB_PASSWORD=notes-pass
DB_ROOT_PASSWORD=root-pass

What it means: Passwords for local practice.

Example 15: Show the wait condition

Type this:

grep -A2 'migrate:' compose.mysql.yaml | tail -2

You will see:

migrate:
  condition: service_completed_successfully

What it means: API waits for migrate exit code 0.

Step 6: Start MySQL stack and test

Why: Prove migrations and API.

What: Build, migrate, start API, then create a note.

Example 16: Up the MySQL stack

Type this:

docker compose -f compose.mysql.yaml up -d --build

You will see:

[+] Running 4/4
 ✔ Container notes-mysql-db-1       Healthy
 ✔ Container notes-mysql-migrate-1  Exited
 ✔ Container notes-mysql-api-1      Started

What it means: Migrate exited. API started.

Example 17: Health and create note

Type this:

curl -s http://localhost:8000/healthz
curl -s -X POST http://localhost:8000/notes -H 'Content-Type: application/json' -d '{"partner":"Vaishali","text":"Need more dosa batter"}'

You will see:

{"ok":true,"engine":"mysql"}
{"saved":true}

What it means: MySQL engine healthy. Note saved.

Example 18: List notes

Type this:

curl -s http://localhost:8000/notes

You will see:

[{"partner":"Vaishali","text":"Need more dosa batter"}]

What it means: Round trip through MySQL works.

5. Same image on Postgres and Mongo

Step 7: Postgres Compose

Why: Only env and image change.

What: Reuse the same Dockerfile. Point DATABASE_URL at Postgres. Alembic still creates the notes table.

Example 19: Write compose.postgres.yaml

Type this:

printf '%s\n' 'name: notes-pg' 'services:' '  db:' '    image: postgres:16-alpine' '    environment:' '      POSTGRES_DB: notes' '      POSTGRES_USER: notes' '      POSTGRES_PASSWORD: ${DB_PASSWORD}' '    volumes: [pg-data:/var/lib/postgresql/data]' '    healthcheck:' '      test: ["CMD-SHELL", "pg_isready -U notes -d notes"]' '      interval: 5s' '      retries: 20' '' '  migrate:' '    build: .' '    command: ["alembic", "upgrade", "head"]' '    environment:' '      DATABASE_URL: postgresql+psycopg://notes:${DB_PASSWORD}@db:5432/notes' '    depends_on:' '      db: {condition: service_healthy}' '' '  api:' '    build: .' '    ports: ["8001:8000"]' '    environment:' '      DB_ENGINE: postgres' '      DATABASE_URL: postgresql+psycopg://notes:${DB_PASSWORD}@db:5432/notes' '    depends_on:' '      migrate: {condition: service_completed_successfully}' '' 'volumes: {pg-data:}' > compose.postgres.yaml && docker compose -f compose.postgres.yaml up -d --build

You will see:

... Started

What it means: Postgres stack on host port 8001. Project name notes-pg.

Example 20: Test Postgres API

Type this:

curl -s http://localhost:8001/healthz
curl -s -X POST http://localhost:8001/notes -H 'Content-Type: application/json' -d '{"partner":"Goodluck","text":"Bun maska order"}'

You will see:

{"ok":true,"engine":"postgres"}
{"saved":true}

What it means: Same image, Postgres engine.

Example 21: List on 8001

Type this:

curl -s http://localhost:8001/notes

You will see:

[{"partner":"Goodluck","text":"Bun maska order"}]

What it means: Postgres path works.

Step 8: Mongo Compose

Why: No Alembic job.

What: Mongo stores documents. Skip migrate. Set DB_ENGINE=mongo and MONGO_URL.

Example 22: Write compose.mongo.yaml

Type this:

printf '%s\n' 'name: notes-mongo' 'services:' '  db:' '    image: mongo:7' '    environment:' '      MONGO_INITDB_ROOT_USERNAME: root' '      MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD}' '    volumes: [mongo-data:/data/db]' '    healthcheck:' '      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' '      interval: 5s' '      retries: 20' '' '  api:' '    build: .' '    ports: ["8002:8000"]' '    environment:' '      DB_ENGINE: mongo' '      MONGO_URL: mongodb://root:${DB_PASSWORD}@db:27017/' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mongo-data:}' > compose.mongo.yaml && docker compose -f compose.mongo.yaml up -d --build

You will see:

... Started

What it means: Mongo stack on port 8002.

Example 23: Test Mongo API

Type this:

curl -s http://localhost:8002/healthz
curl -s -X POST http://localhost:8002/notes -H 'Content-Type: application/json' -d '{"partner":"Cafe Goodluck","text":"Extra chai"}'

You will see:

{"ok":true,"engine":"mongo"}
{"saved":true}

What it means: Mongo engine healthy and writing.

Example 24: List on 8002

Type this:

curl -s http://localhost:8002/notes

You will see:

[{"partner":"Cafe Goodluck","text":"Extra chai"}]

What it means: Document round trip works.

6. Isolation, mistakes and clean up

Step 9: Project names keep stacks apart

Why: Three APIs on one laptop.

What: The name: field prefixes containers and volumes. notes-mysql, notes-pg and notes-mongo can run together without clashing.

Example 25: List all three APIs

Type this:

docker ps --format 'table {{.Names}}\t{{.Ports}}' | grep notes

You will see:

notes-mysql-api-1   0.0.0.0:8000->8000/tcp
notes-pg-api-1      0.0.0.0:8001->8000/tcp
notes-mongo-api-1   0.0.0.0:8002->8000/tcp

What it means: Three projects, three host ports.

Example 26: List volumes by project

Type this:

docker volume ls | grep notes

You will see:

local  notes-mysql_mysql-data
local  notes-pg_pg-data
local  notes-mongo_mongo-data

What it means: Volumes are namespaced by project.

Example 27: Show migrate exit

Type this:

docker inspect -f '{{.State.ExitCode}}' notes-mysql-migrate-1

You will see:

0

What it means: Successful migrate left exit code 0.

Step 10: Common mistakes

Why: Fix them fast.

What: Starting the API before migrate, hard-coding one driver, and reusing the default Compose project name are common.

Example 28: Failed migrate blocks API

Type this:

echo 'If alembic fails, api never starts because of service_completed_successfully'

You will see:

If alembic fails, api never starts because of service_completed_successfully

What it means: That is the feature, not a bug.

Example 29: Wrong engine symptom

Type this:

curl -s http://localhost:8000/healthz | grep mysql

You will see:

{"ok":true,"engine":"mysql"}

What it means: If DB_ENGINE does not match DATABASE_URL, health fails. Keep them paired.

Example 30: Default project name clash

Type this:

grep '^name:' compose.*.yaml

You will see:

name: notes-mysql
name: notes-pg
name: notes-mongo

What it means: Named projects avoid the folder-name default clash.

Step 11: Clean up all three

Why: Leave the machine tidy.

What: Down each file with -v. Remove the built image if you want the disk space.

Example 31: Stop MySQL stack

Type this:

docker compose -f compose.mysql.yaml down -v

You will see:

... Volume notes-mysql_mysql-data Removed

What it means: MySQL project gone.

Example 32: Stop Postgres and Mongo

Type this:

docker compose -f compose.postgres.yaml down -v
docker compose -f compose.mongo.yaml down -v

You will see:

... Removed

What it means: Other two projects gone.

Example 33: Confirm no notes containers

Type this:

docker ps -a --filter name=notes- --format '{{.Names}}' | wc -l

You will see:

0

What it means: Clean.

Step 12: Retry in the app as well as health checks

Why: Networks flap. Apps must retry.

What: Compose health checks start the API at the right time. The app should still retry short DB blips so one dropped packet does not fail a request.

Example 34: Show health does SELECT 1 or ping

Type this:

grep -E 'SELECT 1|ping' app/main.py | head -2

You will see:

s.database.command("ping"); return {"ok": True, "engine": ENGINE}
    with s.connect() as c: c.execute(text("SELECT 1")); return {"ok": True, "engine": ENGINE}

What it means: Health proves the database answers right now.

Example 35: Add a tiny retry note in code comments

Type this:

grep -c 'store()' app/main.py

You will see:

3

What it means: Each request opens work through store(). In production wrap store() with 3 retries and sleep.

Example 36: Why both layers

Type this:

echo 'health = when to start; retry = when a live request hits a blip'

You will see:

health = when to start; retry = when a live request hits a blip

What it means: Teams at Amazon and Shopify use both.

Ravindra Bagale's Tip

Run migrations as a one-off job, not inside the API process. At Netflix and Uber style teams, the API pods start only after migrate succeeds. Compose service_completed_successfully teaches the same idea on a laptop.

Check yourself

Q1. How does one FastAPI image talk to three databases?

Environment variables choose the driver and connection URL.

Q2. What does service_completed_successfully wait for?

The migrate container must exit with code 0 before the API starts.

Q3. Why use pure Python database drivers here?

They keep the image small and avoid OS packages for each database client.

Q4. Why set name: notes-mysql in Compose?

So containers and volumes do not clash with the Postgres and Mongo stacks.

Q5. Does Mongo need Alembic in this project?

No. Mongo stores documents. Only MySQL and Postgres use the migrate job.

Q6. Which host ports did we use for the three APIs?

8000 for MySQL, 8001 for Postgres, 8002 for Mongo.

Friends, you ran one FastAPI image against MySQL, Postgres and Mongo, with Alembic as a one-off job and project names that keep stacks apart. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and repeat the MySQL migrate-then-API path. Next project: Node.js with MySQL, MongoDB and a Redis cache.

Lab: try at home

  1. Create notes-api with app and alembic folders.
  2. Write requirements, main.py, Dockerfile and the first Alembic revision.
  3. Write compose.mysql.yaml with migrate and API.
  4. Start MySQL stack and create a note.
  5. Start Postgres on 8001 and Mongo on 8002 with the same image.
  6. Prove all three /notes lists work.
  7. Clean up all three projects with down -v.

Recap

  • One API image can target many databases by env.
  • Alembic belongs in a one-off migrate job.
  • service_completed_successfully gates the API on migrate success.
  • Project names isolate stacks on one machine.
  • Mongo skips relational migrations.
  • Always clean each Compose project when practice ends.

Ravi Sir's Cards for this lesson

मराठी cards