Lab: an app and its database with Compose, health checks and a live-reload loop
Describe the notes API and its Postgres database in one Compose file with two networks, a named volume and health checks that gate start-up; watch health change when the database goes away; then set up a development loop that reloads the code on save.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Point the app at Postgres
- Step 2: Describe both services in compose.yaml
- Step 3: Start the stack and wait for health
- Step 4: Use the API, the database and the logs
- Step 5: Check names and network boundaries
- Step 6: Watch health change when the database goes away
- Step 7: Recreate everything and keep the data
- Step 8: A live-reload loop for development
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of Containerization
- A container is a process with boundaries Concept · 15 min
- Images, overlay layers, the build cache and what not to bake in Concept · 20 min
- Lab: from a naive Dockerfile to a slim, non-root multi-stage image Lab · 30 min
- Running containers deliberately: ports, volumes, bind mounts, devices and GPUs, environment and logs Worked example · 25 min
- Lab: an app and its database with Compose, health checks and a live-reload loop Lab · 30 min
- Check: debug three broken containers Knowledge check · 8 questions
What you will learn
- Describe a multi-service application with Docker Compose, including networks, volumes, health checks and startup dependencies.
01. Goal and setup
Real services rarely run alone. In this lab the notes API from lesson 3 stores its notes in Postgres, and one Compose file describes both: how to build or pull each image, how they find each other, where the database keeps its data, how each one reports that it is ready, and in what order they start. You finish with a development loop in which saving a Python file reloads the server inside its container.
You need Docker Engine 25 or later with the Compose plugin (or a current Docker Desktop) and the notes-api folder from lesson 3, with its Dockerfile, .dockerignore and app/healthcheck.py. The lab was run with Docker Engine 29.8, Docker Compose 5.5, postgres:18-alpine (PostgreSQL 18.6) and psycopg 3.3. IDs, timings and private IP addresses vary. When you are done, the folder looks like this:
notes-api/
├── app/
│ ├── __init__.py
│ ├── healthcheck.py (from lesson 3)
│ └── main.py (rewritten in step 1)
├── .dockerignore (from lesson 3)
├── .env (replaced in step 2)
├── compose.dev.yaml
├── compose.yaml
├── Dockerfile (from lesson 3)
└── requirements.txt (one line added)02. Step 1: Point the app at Postgres
Add the Postgres driver, psycopg 3, with its prebuilt binary package so the slim image needs no compiler:
fastapi==0.146.0
uvicorn[standard]==0.54.0
psycopg[binary]==3.3.6Replace app/main.py. The app reads its connection string from DATABASE_URL, creates its table at start-up, and its /health route now answers 503 when the database cannot be reached, so the container's health check reflects the whole service. Opening a connection per request keeps the lab short; a real service would use a pool (psycopg_pool).
"""Notes API backed by Postgres."""
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
import psycopg
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
DATABASE_URL = os.environ['DATABASE_URL']
class Note(BaseModel):
title: str
body: str = ''
def connect() -> psycopg.Connection:
return psycopg.connect(DATABASE_URL, connect_timeout=3)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
with connect() as conn:
conn.execute(
'CREATE TABLE IF NOT EXISTS notes ('
'id serial PRIMARY KEY, title text NOT NULL, body text NOT NULL)'
)
yield
app = FastAPI(title='Notes API', lifespan=lifespan)
@app.get('/health')
def health() -> dict[str, str]:
try:
with connect() as conn:
conn.execute('SELECT 1')
except psycopg.OperationalError:
raise HTTPException(status_code=503, detail='database unavailable')
return {'status': 'ok', 'env': os.environ.get('APP_ENV', 'dev')}
@app.post('/notes', status_code=201)
def add_note(note: Note) -> Note:
with connect() as conn:
conn.execute(
'INSERT INTO notes (title, body) VALUES (%s, %s)', (note.title, note.body)
)
return note
@app.get('/notes')
def list_notes() -> list[Note]:
with connect() as conn:
rows = conn.execute('SELECT title, body FROM notes ORDER BY id').fetchall()
return [Note(title=title, body=body) for title, body in rows]Build the image once on its own to check that the driver installs, and see what the app does when nobody gives it a database:
docker build -q -t notes-api:compose . >/dev/null
docker run --rm notes-api:compose python -c "import psycopg; print(psycopg.__version__)"
docker run --rm notes-api:compose 2>&1 | tail -n 13.3.6
KeyError: 'DATABASE_URL'The app refuses to start without its connection string, and the container exits with code 1. Supplying that setting, and a database to point it at, is the Compose file's job.
03. Step 2: Describe both services in compose.yaml
name: notes
services:
api:
build: .
image: notes-api:compose
ports:
- "127.0.0.1:8000:8000"
environment:
APP_ENV: local
DATABASE_URL: postgresql://notes:${POSTGRES_PASSWORD:?set in .env}@db:5432/notes
depends_on:
db:
condition: service_healthy
restart: true
networks: [frontend, backend]
restart: unless-stopped
develop:
watch:
- action: sync+restart
path: ./app
target: /app/app
- action: rebuild
path: requirements.txt
db:
image: postgres:18-alpine
environment:
POSTGRES_USER: notes
POSTGRES_DB: notes
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set in .env}
volumes:
- db-data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U notes -d notes"]
interval: 5s
timeout: 3s
retries: 5
start_period: 20s
start_interval: 1s
networks: [backend]
restart: unless-stopped
volumes:
db-data:
networks:
frontend:
backend:
internal: trueRead it service by service:
name: notesfixes the project name, which prefixes every container, network and volume (notes-db-1,notes_db-data).- api is built from the Dockerfile in this folder and tagged
notes-api:compose. Its port is published on127.0.0.1only.DATABASE_URLuses the host namedb: Compose registers each service name in the DNS of the networks it joins. depends_onwithcondition: service_healthymakes Compose startapionly afterdbreports healthy, not merely after its container started.restart: truerestartsapiwhen Compose restartsdb, for example withdocker compose restart db.- db uses the official image unchanged; its environment variables create the user and database on first start. PostgreSQL 18 images keep their data under
/var/lib/postgresql/18/dockerand declare/var/lib/postgresqlas the volume, so mount the named volume there (images up to 17 used/var/lib/postgresql/data). - The healthcheck runs
pg_isreadyinside the container.start_periodis a grace period in which failures do not count, andstart_intervalprobes every second during it, so a fast start is noticed quickly. - Networks split traffic:
apijoinsfrontendandbackend,dbonlybackend, which isinternal, sodbhas no route out of the host at all.dbpublishes no ports. ${POSTGRES_PASSWORD:?...}is interpolated from your shell or from a.envfile next tocompose.yaml;:?makes Compose refuse to start when it is missing.- The
developsection is only used bydocker compose watchin step 8.
Replace the .env file from lesson 3 with the database password (a local development value; .dockerignore already keeps .env out of the image), then validate the file, with and without the variable:
printf 'POSTGRES_PASSWORD=local-dev-only\n' > .env
docker compose config --quiet && echo valid
POSTGRES_PASSWORD= docker compose --env-file /dev/null config --quietvalid
error while interpolating services.api.environment.DATABASE_URL: required variable
POSTGRES_PASSWORD is missing a value: set in .env
error while interpolating services.db.environment.POSTGRES_PASSWORD: required
variable POSTGRES_PASSWORD is missing a value: set in .env04. Step 3: Start the stack and wait for health
docker compose up -d --build --wait
docker compose ps --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'SERVICE STATUS PORTS
api Up 6 seconds (healthy) 127.0.0.1:8000->8000/tcp
db Up 10 seconds (healthy) 5432/tcpup printed its progress first: networks, volume, db started, db healthy, only then api started. --wait returns once every service is running and healthy, which makes the command safe to use in scripts and CI. 5432/tcp without an arrow means the database port exists on the network but is not published to the host.
05. Step 4: Use the API, the database and the logs
curl -s -X POST localhost:8000/notes -H 'Content-Type: application/json' \
-d '{"title": "Stored in Postgres"}'; echo
curl -s localhost:8000/notes; echo
docker compose exec db psql -U notes -c 'SELECT id, title FROM notes'
docker compose logs api --no-log-prefix --tail 2{"title":"Stored in Postgres","body":""}
[{"title":"Stored in Postgres","body":""}]
id | title
----+--------------------
1 | Stored in Postgres
(1 row)
INFO: 172.22.0.1:57656 - "POST /notes HTTP/1.1" 201 Created
INFO: 172.22.0.1:57662 - "GET /notes HTTP/1.1" 200 OKdocker compose exec runs a command in a service's container by service name, so you never need container IDs. docker compose logs merges the logs of all services, or of the ones you name; add -f to follow them while you work.
06. Step 5: Check names and network boundaries
docker compose exec api python -c "import socket; print(socket.gethostbyname('db'))"
docker compose exec db sh -c \
'wget -q -T 3 -O /dev/null https://pypi.org && echo online || echo "no route out"'
docker network ls --filter name=notes_ --format '{{.Name}} internal={{.Internal}}'172.24.0.2
wget: bad address 'pypi.org'
no route out
notes_backend internal=true
notes_frontend internal=falseThe API resolves db through Docker's embedded DNS server. The IP address can change whenever the container is recreated, which is why services refer to each other by name. The database cannot even resolve an outside name: an internal network has no gateway to the outside world. In production you would keep it that way, and reach it for maintenance with docker compose exec.
07. Step 6: Watch health change when the database goes away
docker compose stop db
curl -s -i localhost:8000/health | sed -n '1p;$p'; echo
sleep 40
docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'
docker compose start db
sleep 15
docker compose ps --format 'table {{.Service}}\t{{.Status}}'HTTP/1.1 503 Service Unavailable
{"detail":"database unavailable"}
SERVICE STATUS
api Up About a minute (unhealthy)
db Exited (0) 40 seconds ago
SERVICE STATUS
api Up About a minute (healthy)
db Up 15 seconds (healthy)Three failed probes in a row turned api unhealthy, and then nothing else happened: Docker Engine records health but does not act on it. The container kept running and recovered by itself once db was back, because each request opens a new connection. Acting on health is the job of whatever runs your containers: Compose uses it to order start-up, Docker Swarm replaces unhealthy tasks; Kubernetes ignores HEALTHCHECK and uses its own liveness and readiness probes. Your app's retries cover the rest.
08. Step 7: Recreate everything and keep the data
docker compose down
docker volume ls --filter label=com.docker.compose.project=notes --format '{{.Name}}'
docker compose up -d --wait
curl -s localhost:8000/notes; echonotes_db-data
[{"title":"Stored in Postgres","body":""}]down removed the containers and networks but kept the named volume, so the new db container found its data. docker compose down -v would delete the volume too; use it only when you want an empty database.
09. Step 8: A live-reload loop for development
Rebuilding the image after every edit is too slow for development. Add a second Compose file that changes only what development needs: it bind-mounts your app folder over the copy in the image (read-only, so the container cannot change your files) and runs uvicorn with --reload, which restarts the server when a file changes. Uvicorn listens on port 8000 by default, so the flag can be left out.
services:
api:
command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--reload"]
environment:
APP_ENV: dev
volumes:
- ./app:/app/app:rodocker compose -f compose.yaml -f compose.dev.yaml up -d --wait
curl -s localhost:8000/health; echo{"status":"ok","env":"dev"}Compose merges the files in order: maps such as environment are merged key by key, command is replaced, and volumes entries are merged by their target path. Now open app/main.py in your editor, change 'status': 'ok' in the health route to 'status': 'reloaded', save, and ask again:
curl -s localhost:8000/health; echo
docker compose logs api --no-log-prefix | grep -E 'WatchFiles|Started server'{"status":"reloaded","env":"dev"}
INFO: Started reloader process [1] using WatchFiles
INFO: Started server process [8]
WARNING: WatchFiles detected changes in 'app/main.py'. Reloading...
INFO: Started server process [17]The edit reached the running container through the bind mount within a second, with no rebuild. Change the value back to 'ok' before you continue.
Compose also has its own mechanism, Compose Watch, which needs no bind mount and works well where bind mounts are slow, such as Docker Desktop on macOS. The develop section in compose.yaml tells it to copy changes under ./app into the container and restart it, and to rebuild the image when requirements.txt changes. Go back to the plain file and start watching in a second terminal:
docker compose up -d --wait
docker compose watchWatch enabled
Syncing service "api" after 2 changes were detected
Container notes-api-1 Restarting
Container notes-api-1 Started
service(s) ["api"] restartedOne caveat: Compose Watch expects the container user to be able to write to the target. Our /app is root-owned, so deletes and renames under ./app can fail to sync. For watch, build a development target with COPY --chown=app:app app/ ./app/.
Stop watching with Ctrl+C. Choose one mechanism per project: the bind mount with --reload is simplest on Linux, and Compose Watch gives the same loop without mounting your source. Either way the production compose.yaml stays free of development settings. When you have finished, remove everything, including the volume: docker compose down -v.
10. Troubleshooting
11. Check your understanding
12. Apply it: stretch task
Finish this skill's practice project: run your service and its database through a Compose file whose health checks gate start-up, plus a development setup that bind-mounts the source and reloads on save. Then stretch it:
- Add Redis as a cache:
image: redis:8-alpine, a healthcheck withredis-cli ping, no published port, on thebackendnetwork only, andcondition: service_healthyfor it inapi. Make the app work, more slowly, when Redis is down. - Put the development settings behind a Compose profile, or keep the override file and set
COMPOSE_FILE=compose.yaml:compose.dev.yamlin your shell, so teammates use the same loop with plaindocker compose up. - Move the database password out of the environment: declare it under a top-level
secrets:key, mount it intodband setPOSTGRES_PASSWORD_FILE, which the official image reads. - In CI, run
docker compose up -d --build --wait, your tests againstlocalhost:8000, anddocker compose down -v, so every pipeline starts from an empty database.
13. Review prompt
Without looking back, write the db service of this lab's compose.yaml: image, environment, volume (with the correct mount path for PostgreSQL 18), healthcheck and network. Then write the depends_on entry that makes api wait for it, and explain in two sentences the difference between a container that is running, one that is healthy and one that is ready to serve your users.
References
- Docker Compose documentation
- Compose file reference: services
- Docker Docs: Control startup and shutdown order in Compose
- Docker Docs: Networking in Compose
- Compose file reference: interpolation
- Docker Docs: Merge Compose files
- Docker Docs: Use Compose Watch
- Docker Docs: Using profiles with Compose
- Docker Hub: postgres official image
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.