Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
Make a FastAPI plus Postgres Compose stack ready for a server: config from the environment, logs to stdout, a /health route behind HEALTHCHECK that turns the API unhealthy when the database stops, an internal network that hides the database, and a 256 MB limit that kills a 400 MB allocation with exit code 137.
What you will learn
- Read settings from environment variables and log to stdout so Docker collects the logs
- Write a /health route that checks the database, and wire it to a Dockerfile HEALTHCHECK
- Keep the database on an internal network that only the API can reach
- Set memory and CPU limits in Compose and watch a limit stop a hungry process
Before you start
- Docker Compose with an app and a database
- Docker volumes
A container that says Up can still be broken. Stop the database under a running API and the API container keeps saying Up, because Docker only knows the process is running. This article takes the notes API from Docker Compose: app plus database and closes that gap, one question at a time:
- Does the data survive when containers are removed? (volumes)
- Who can reach the database? (networks)
- Is the app really working? (the health check)
- What if one container eats all the memory? (limits)
Picture a shared canteen. Lockers keep your things overnight. An intercom lets a table call another table by name, but only inside the same hall. A nurse walks past every table asking "are you okay?" and marks a table that doesn't answer three times. And fixed portions stop one hungry table from emptying the kitchen. Every output below comes from a real run of the lecture's project (Compose project name s01l05).
Settings from the environment
import os
APP_NAME = os.environ.get("APP_NAME", "notes")
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
DB_HOST = os.environ.get("DB_HOST", "localhost")
DB_USER = os.environ["DB_USER"]
DB_PASSWORD = os.environ["DB_PASSWORD"]
DB_NAME = os.environ.get("DB_NAME", "notes")
DATABASE_URL = (
f"postgresql://{DB_USER}:{DB_PASSWORD}"
f"@{DB_HOST}:5432/{DB_NAME}"
)
APP_NAME and LOG_LEVEL have defaults. DB_HOST defaults to localhost for your laptop; Compose sets it to db, so the same code talks to the database container. The user and password have no default on purpose: if one is missing, the app stops at once with a KeyError instead of starting with a wrong password. The password is never written into the image. The image stays the same, only the environment changes.
Logs to stdout and a real /health route
import logging
import sys
import psycopg
from fastapi import FastAPI, Response
from pydantic import BaseModel
import settings
logging.basicConfig(
stream=sys.stdout,
level=settings.LOG_LEVEL,
format="%(levelname)s %(name)s %(message)s",
)
log = logging.getLogger(settings.APP_NAME)
app = FastAPI(title="Notes API")
class NoteIn(BaseModel):
text: str
def connect():
return psycopg.connect(
settings.DATABASE_URL, connect_timeout=2
)
@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)"
)
log.info("table ready on %s", settings.DB_HOST)
@app.get("/health")
def health(response: Response):
try:
with connect() as con:
con.execute("SELECT 1")
except psycopg.OperationalError:
log.warning("health check: database down")
response.status_code = 503
return {"status": "down", "db": "down"}
return {"status": "ok", "db": "up"}
Lines 10 to 14 send log lines to standard output, not to a file inside the container, so Docker can collect them. The /health route asks the database the smallest possible question, SELECT 1. If Postgres can't be reached, psycopg raises OperationalError, the route logs a warning and answers 503 Service Unavailable. Health means the app can do its job, not just answer.
Wire it to Docker with HEALTHCHECK
FROM python:3.13-slim
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY *.py ./
HEALTHCHECK --interval=5s --timeout=3s --retries=3 \
CMD python healthcheck.py
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", \
"--no-access-log"]
import sys
import urllib.request
URL = "http://localhost:8000/health"
try:
urllib.request.urlopen(URL, timeout=2)
except Exception:
sys.exit(1)
PYTHONUNBUFFERED=1 stops Python from holding log lines in a buffer. The HEALTHCHECK runs python healthcheck.py inside the container every 5 seconds, waits at most 3 seconds, and after 3 failures in a row marks the container unhealthy. A 200 lets the script end normally (healthy). A 503 makes urlopen raise, and sys.exit(1) tells Docker the check failed. Why not curl? The slim Python image doesn't have it, and Python is already there.
compose.yaml: networks and limits
services:
api:
build: ./app
ports:
- "${PORT:-8000}:8000"
environment:
APP_NAME: notes
LOG_LEVEL: INFO
DB_HOST: db
DB_USER: notes_user
DB_PASSWORD: ${DB_PASSWORD:-notes_pass}
networks: [front, back]
mem_limit: 256m
memswap_limit: 256m
cpus: 0.5
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
networks: [back]
mem_limit: 512m
healthcheck:
test: ["CMD-SHELL", "pg_isready -U notes_user"]
interval: 3s
timeout: 3s
retries: 10
networks:
front:
back:
internal: true
volumes:
pgdata:
back can find the database. internal: true means nothing on it is reachable from outside.The api joins two networks, front and back; the database joins back only, and back is internal. The api gets 256 MB of memory and half a CPU. memswap_limit is set to the same 256m, which means no extra swap on top. Without that line Docker gives the container swap as well, and the limit is softer than it looks. Who talks to whom, and how much each may use, sit together in one file.
Up, healthy, and two notes
In the blocks below, each curl answer is shown on one line as its HTTP status plus the body.
$ docker compose up -d --build
Container s01l05-db-1 Started
Container s01l05-db-1 Waiting
Container s01l05-db-1 Healthy
Container s01l05-api-1 Starting
Container s01l05-api-1 Started
$ docker compose ps --format 'table {{.Service}}\t{{.Status}}'
SERVICE STATUS
api Up 9 seconds (healthy)
db Up 16 seconds (healthy)
$ curl -X GET localhost:8000/health
HTTP 200 {"status":"ok","db":"up"}
$ curl -X POST localhost:8000/notes -d '{"text":"Buy milk"}' -H 'content-type: application/json'
HTTP 200 {"id":1,"text":"Buy milk"}
$ curl -X POST localhost:8000/notes -d '{"text":"Call mum"}' -H 'content-type: application/json'
HTTP 200 {"id":2,"text":"Call mum"}
Now healthy on the api comes from our own check, not just from the process starting.
Volumes: the locker stays
$ docker volume ls -q --filter name=s01l05
s01l05_pgdata
$ docker volume inspect s01l05_pgdata --format '{{.Mountpoint}}'
/var/lib/docker/volumes/s01l05_pgdata/_data
$ curl -X GET localhost:8000/notes
HTTP 200 [{"id":1,"text":"Buy milk"},{"id":2,"text":"Call mum"}]
$ curl -X POST localhost:8000/notes -d '{"text":"Pay rent"}' -H 'content-type: application/json'
HTTP 200 {"id":3,"text":"Pay rent"}
After docker compose down removed both containers and both networks, the s01l05_pgdata volume was still listed. It lives under /var/lib/docker/volumes and belongs to Docker, not to any container. After up -d, both notes are back and the next one gets id 3. Containers are thrown away; the volume isn't. (Images, containers and volumes from the ground up are in Docker essentials.)
Networks: found by name
import socket
import sys
name = sys.argv[1]
try:
print(name, "->", socket.gethostbyname(name))
except socket.gaierror:
print(name, "-> not found")
$ docker network ls --filter name=s01l05 --format '{{.Name}}'
s01l05_back
s01l05_front
$ docker compose exec api python lookup.py db
db -> 172.18.0.2
$ docker run --rm --network s01l05_front s01l05-api python lookup.py db
db -> not found
Inside the api container, db resolves to an address because both sit on back. A new container on front only can't even see that a database exists. That is how you keep the database away from everything that doesn't need it.
Health check: break it
$ docker compose stop db
Container s01l05-db-1 Stopping
Container s01l05-db-1 Stopped
$ curl -X GET localhost:8000/health
HTTP 503 {"status":"down","db":"down"}
$ docker compose ps -a --format 'table {{.Service}}\t{{.Status}}'
SERVICE STATUS
api Up 31 seconds (unhealthy)
db Exited (0) 15 seconds ago
With the database stopped, /health answers 503 straight away, and in this run the api was marked unhealthy 12.7 seconds later, after three failed checks 5 seconds apart. Start the database again:
$ docker compose start db
Container s01l05-db-1 Starting
Container s01l05-db-1 Started
$ docker compose ps --format 'table {{.Service}}\t{{.Status}}'
SERVICE STATUS
api Up 45 seconds (healthy)
db Up 12 seconds (healthy)
$ curl -X GET localhost:8000/health
HTTP 200 {"status":"ok","db":"up"}
Notice what Docker did not do: it marked the api unhealthy but never restarted it. Unhealthy is a signal. Something has to act on it, such as a load balancer or an orchestrator that watches that status.
Logs go to stdout
$ docker compose logs api --no-log-prefix
INFO: Started server process [1]
INFO: Waiting for application startup.
INFO notes table ready on db
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO notes note 3 saved
WARNING notes health check: database down
WARNING notes health check: database down
WARNING notes health check: database down
WARNING notes health check: database down
WARNING notes health check: database down
Uvicorn's startup lines, our own notes table ready on db, note 3 saved, and the warnings from while the database was down. Notes 1 and 2 aren't here because that container was removed, and its logs went with it. Nobody opened a log file: we wrote to stdout and Docker collected it.
Limits: break it
$ docker inspect s01l05-api-1 -f '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}'
268435456 500000000
$ docker stats --no-stream --format '{{.Name}} {{.MemUsage}} {{.CPUPerc}}' s01l05-api-1 s01l05-db-1
s01l05-api-1 36.99MiB / 256MiB 0.51%
s01l05-db-1 18.45MiB / 512MiB 2.33%
268435456 bytes is exactly 256 MB, and 500000000 nano CPUs is half a CPU. The api uses about 37 MiB of its 256. Now ask for 400 MB inside the api container:
$ docker compose exec api python -c "b = bytearray(400 * 1024 * 1024)"
(exit code 137)
The process hit the limit and was killed with exit code 137, which is 128 + 9, the kill signal. And the api itself?
$ docker compose ps --format 'table {{.Service}}\t{{.Status}}'
SERVICE STATUS
api Up 59 seconds (healthy)
db Up 25 seconds (healthy)
$ curl -X GET localhost:8000/health
HTTP 200 {"status":"ok","db":"up"}
$ docker inspect s01l05-api-1 -f '{{.State.Status}} {{.RestartCount}}'
running 0
Still running, still healthy, zero restarts. Only the hungry process was stopped, and the database never noticed. A limit protects the neighbours.
The same stack is what a CI pipeline builds and tests on every push; see CI with GitHub Actions.
Recap
| Piece | Canteen picture | What it gives you |
|---|---|---|
| Named volume | Locker | Data survives containers coming and going |
Networks, internal: true | Intercom in one hall | Only containers on a shared network find each other by name |
/health + HEALTHCHECK | Nurse | Healthy means the app can really do its job; unhealthy is a signal, not a restart |
| stdout logging | Docker collects the logs; no log files in the container | |
mem_limit, memswap_limit, cpus | Fixed portions | One process can't starve the others; exit 137 when it tries |
Try it yourself: lower the api's mem_limit to 128m, rebuild, and check with docker stats whether the API still starts comfortably. Then put a new container on back and confirm it can find db.
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.
