Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

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

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:

Folder layout
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:

requirements.txt
fastapi==0.146.0
uvicorn[standard]==0.54.0
psycopg[binary]==3.3.6

Replace 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).

app/main.py
"""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:

Terminal, in notes-api/
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 1
Expected output
3.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

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: true

Read it service by service:

  • name: notes fixes 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 on 127.0.0.1 only. DATABASE_URL uses the host name db: Compose registers each service name in the DNS of the networks it joins.
  • depends_on with condition: service_healthy makes Compose start api only after db reports healthy, not merely after its container started. restart: true restarts api when Compose restarts db, for example with docker 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/docker and declare /var/lib/postgresql as the volume, so mount the named volume there (images up to 17 used /var/lib/postgresql/data).
  • The healthcheck runs pg_isready inside the container. start_period is a grace period in which failures do not count, and start_interval probes every second during it, so a fast start is noticed quickly.
  • Networks split traffic: api joins frontend and backend, db only backend, which is internal, so db has no route out of the host at all. db publishes no ports.
  • ${POSTGRES_PASSWORD:?...} is interpolated from your shell or from a .env file next to compose.yaml; :? makes Compose refuse to start when it is missing.
  • The develop section is only used by docker compose watch in 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:

Terminal, in notes-api/
printf 'POSTGRES_PASSWORD=local-dev-only\n' > .env
docker compose config --quiet && echo valid
POSTGRES_PASSWORD= docker compose --env-file /dev/null config --quiet
Expected output (each error is one line, wrapped here to fit)
valid
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 .env

04. Step 3: Start the stack and wait for health

Terminal
docker compose up -d --build --wait
docker compose ps --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
Illustrative output of docker compose ps, after the build and progress lines (times vary)
SERVICE   STATUS                    PORTS
api       Up 6 seconds (healthy)    127.0.0.1:8000->8000/tcp
db        Up 10 seconds (healthy)   5432/tcp

up 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

Terminal
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
Illustrative output (addresses and ports vary)
{"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 OK

docker 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

Terminal
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}}'
Illustrative output (the IP address varies)
172.24.0.2
wget: bad address 'pypi.org'
no route out
notes_backend internal=true
notes_frontend internal=false

The 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

Terminal
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}}'
Illustrative output, without the progress lines of stop and start (times vary)
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

Terminal
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; echo
Illustrative output, without the progress lines of down and up
notes_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.

compose.dev.yaml
services:
  api:
    command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--reload"]
    environment:
      APP_ENV: dev
    volumes:
      - ./app:/app/app:ro
Terminal
docker compose -f compose.yaml -f compose.dev.yaml up -d --wait
curl -s localhost:8000/health; echo
Illustrative output, after the progress lines
{"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:

Terminal
curl -s localhost:8000/health; echo
docker compose logs api --no-log-prefix | grep -E 'WatchFiles|Started server'
Illustrative output (process numbers vary)
{"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:

Terminal 1, then terminal 2
docker compose up -d --wait
docker compose watch
Illustrative output in terminal 2 after you save app/main.py (after the build log; the count depends on your editor)
Watch enabled
Syncing service "api" after 2 changes were detected
 Container notes-api-1 Restarting
 Container notes-api-1 Started
service(s) ["api"] restarted

One 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

Practice check · 3 questions

Check your Compose file

Questions about the stack you have just run.

Q1. In this lab, db is attached only to the backend network, which has internal: true. What does that give you?
Q2. POSTGRES_PASSWORD is not set anywhere, and compose.yaml uses ${POSTGRES_PASSWORD:?set in .env}. What does docker compose up do?
Q3. The api container's health check starts failing because Postgres was stopped. What does Docker Engine do to the api container?
Practice only: not graded, not saved, not evidence.

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:

  1. Add Redis as a cache: image: redis:8-alpine, a healthcheck with redis-cli ping, no published port, on the backend network only, and condition: service_healthy for it in api. Make the app work, more slowly, when Redis is down.
  2. Put the development settings behind a Compose profile, or keep the override file and set COMPOSE_FILE=compose.yaml:compose.dev.yaml in your shell, so teammates use the same loop with plain docker compose up.
  3. Move the database password out of the environment: declare it under a top-level secrets: key, mount it into db and set POSTGRES_PASSWORD_FILE, which the official image reads.
  4. In CI, run docker compose up -d --build --wait, your tests against localhost:8000, and docker 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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check