Docker Compose: Run a FastAPI App and Postgres From One File
A notes API in FastAPI plus Postgres, described in one compose.yaml: the service name as the database host, a named volume, a pg_isready healthcheck with depends_on, and a real run showing notes surviving docker compose down but not down -v.
What you will learn
- Explain why two hand-typed docker run commands break, and what compose.yaml replaces
- Write services for a built API image and a pulled Postgres image
- Connect them by service name, keep data in a named volume, and order startup with a healthcheck and depends_on
- Run, inspect and tear down the stack with up, ps, logs, down and down -v
Before you start
- Docker images, containers and volumes
- A Dockerfile for a FastAPI app
One container is easy: build an image, run it. But a real app usually needs more than one. Our example is a small notes API written with FastAPI that stores every note in Postgres. That is two containers, and they have to find each other, share a password and start in the right order.
Docker Compose describes all of that in one file, compose.yaml, and starts everything with one command. Every output below comes from a real run of the lecture's project.
Two long commands, and everything must match
Without Compose you create a network, then run Postgres with a name, a user, a password, a database name and a volume. Then you build the app image and run it with a name, the same network, a port, and the address of the database. The network name must match in both commands. The container name db must match the host the app uses. The password must be the same on both sides. Type one letter wrong and the link is broken, and with three or four containers it only gets worse.
Think of a container as a lunchbox: one thing inside, and you carry each box yourself. A bento box packs several boxes together so they travel and open at the same table. compose.yaml is the list on the lid: which boxes you need and how they connect.
The notes API
import os
import psycopg
from fastapi import FastAPI
from pydantic import BaseModel
DATABASE_URL = os.environ["DATABASE_URL"]
app = FastAPI(title="Notes API")
class NoteIn(BaseModel):
text: str
def connect():
return psycopg.connect(DATABASE_URL)
@app.on_event("startup")
def create_table():
with connect() as con:
con.execute(
"CREATE TABLE IF NOT EXISTS notes ("
"id SERIAL PRIMARY KEY, text TEXT NOT NULL)"
)
@app.post("/notes")
def add_note(note: NoteIn):
with connect() as con:
row = con.execute(
"INSERT INTO notes (text) VALUES (%s) RETURNING id", (note.text,)
).fetchone()
return {"id": row[0], "text": note.text}
@app.get("/notes")
def list_notes():
with connect() as con:
rows = con.execute("SELECT id, text FROM notes ORDER BY id").fetchall()
return [{"id": r[0], "text": r[1]} for r in rows]
Line 7 reads the database address from the environment variable DATABASE_URL, so the code stays the same on a laptop or a server, and Compose supplies the value. On startup the app creates its own notes table if it is missing. POST /notes inserts a note and returns its id; GET /notes reads them all back by id. The %s placeholder passes the text to Postgres as a value, so it is never pasted into the SQL.
The Dockerfile is the familiar recipe from containerising a model API. With no port given, uvicorn uses its default, 8000:
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0"]
compose.yaml
services:
api:
build: ./app
ports:
- "${PORT:-8000}:8000"
environment:
DATABASE_URL: postgresql://notes_user:${DB_PASSWORD:-notes_pass}@db:5432/notes
depends_on:
db:
condition: service_healthy
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: notes_user
POSTGRES_PASSWORD: ${DB_PASSWORD:-notes_pass}
POSTGRES_DB: notes
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U notes_user -d notes"]
interval: 3s
timeout: 3s
retries: 10
volumes:
pgdata:
Services: build one, pull the other
A service is one box in the bento. api has build: ./app, so Compose builds it from the app folder's Dockerfile. db has image: postgres:17-alpine, a ready-made image that Compose just pulls.
Ports and the service name
"${PORT:-8000}:8000" maps a port on your computer to port 8000 in the container. The number comes from a PORT variable and defaults to 8000, which helps when 8000 is busy. In DATABASE_URL, the host is db: Compose puts both services on one private network where each service is reachable by its name. You don't need any network commands. The password comes from DB_PASSWORD (defaulting to notes_pass) and is used on both sides, so it can't drift. The project ships a .env.example to copy to .env and change.
Volume, healthcheck and depends_on
Postgres keeps its files in the named volume pgdata. Containers can be removed and recreated; the volume stays. Every 3 seconds Compose runs pg_isready, and when it answers yes the database is marked healthy. The api's depends_on with condition: service_healthy makes it wait until Postgres is ready to take connections. That solves the classic problem of the app starting before its database.
One command, both services
docker compose up -d --build
docker compose ps
SERVICE STATUS PORTS
api Up Less than a second 0.0.0.0:51942->8000/tcp, [::]:51942->8000/tcp
db Up 3 seconds (healthy) 5432/tcp
For this recorded run the lecture set PORT to a free port (51942), which shows up in the ports column. The db is healthy, so the api was allowed to start. The database shows only 5432/tcp, with no mapping to your computer, because only the app talks to it over the private network.
Calling the API
Two POSTs, then a GET (requests and answers summarised from the run log, one per line):
POST /notes {"text": "Buy milk"} -> 200 {"id":1,"text":"Buy milk"}
POST /notes {"text": "Call mum"} -> 200 {"id":2,"text":"Call mum"}
GET /notes -> 200 [{"id":1,"text":"Buy milk"},{"id":2,"text":"Call mum"}]
docker compose logs api shows the api service's own log:
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: 172.18.0.1:51276 - "GET /notes HTTP/1.1" 200 OK
INFO: 172.18.0.1:51286 - "POST /notes HTTP/1.1" 200 OK
INFO: 172.18.0.1:51290 - "POST /notes HTTP/1.1" 200 OK
INFO: 172.18.0.1:51302 - "GET /notes HTTP/1.1" 200 OK
Each note went through the api container into the db container. To follow the log live, use docker compose logs -f api and press Ctrl+C to stop following.
Data survives down; down -v wipes it
docker compose down
docker volume ls
s01l04_pgdata
down stops and removes both containers, but the volume is still there. Start again with docker compose up -d and ask for the notes:
GET /notes -> 200 [{"id":1,"text":"Buy milk"},{"id":2,"text":"Call mum"}]
New containers, same data. Now with -v:
docker compose down -v
docker volume ls
docker compose up -d
docker volume ls -> (empty list)
GET /notes -> 200 []
down keeps your data. down -v deletes the volume with it, which is what you want for a clean start and nothing else.
Common mistakes
- Using
localhostas the database host inside the app container. Inside the network, the host is the service name,db. - Starting the api without a healthcheck-based
depends_on, so it tries to connect before Postgres is ready. - Running
down -vout of habit and losing the data. - Publishing the database port to your computer when only the app needs it.
Recap
| Command or key | What it does |
|---|---|
services | One entry per container: build or image |
| Service name | The hostname on the private network (@db:5432) |
volumes: pgdata | Keeps the database files when containers are removed |
healthcheck + depends_on | The api waits for a healthy database |
up -d --build | Build, pull and start everything in the background |
ps / logs -f api | Who is up and healthy / follow one service |
down / down -v | Stop and keep data / stop and wipe data |
Try it yourself: add Adminer as a third service (image adminer, ports 8080:8080), open it in the browser, and log in to the db host to see the notes table. Then change the api port with PORT=8010. The next step, health checks, networks and limits, makes the stack sturdier.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
