Skip to content
Visual explainer 4h to learn 5 steps

Deploy the API, worker and database stack

Run the API, worker, Postgres and queue with Docker Compose and map it to one managed deployment with health checks and rollback.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.

Topic 22 of 29

In short

The Q&A service is really four processes: the FastAPI API, the ingestion worker, PostgreSQL and a queue such as Redis. Docker Compose runs all four locally from one file, with health checks, secrets injected at runtime and a one-off migration step before the API starts. The same shape then maps to one managed deployment, where the release plan also says how to roll back.

Think of it like this: The Compose file is the seating plan for a dinner: who sits where, who must arrive first and who brings which key.

Explained simply

Until now you probably ran the API with one command and the database somewhere else. A real deployment has several pieces that must start in the right order: the database, the queue, a step that updates the database tables, the API and the worker. Docker Compose lets you describe all of them in one file and start them with docker compose up.

The API and worker can share one container image. The code is the same; only the start command differs. The API runs Uvicorn and answers HTTP requests. The worker runs a loop that takes ingestion jobs from the queue. Sharing an image means both always run the same version of your code.

Passwords and API keys must not be written into the image or the Compose file. They are handed to the container when it starts, as environment variables or as files mounted into the container. Locally they come from a file that git ignores; in the cloud they come from a secret store.

Each release should be easy to undo. Tag every image with the git commit, update the database in a way the old code still understands, and keep the previous tag ready. If the new version misbehaves, you redeploy the old tag and you are back in minutes.

Press Play on a diagram to walk through it one step at a time.

LayersThe local stack in Docker Compose
  1. 1
    api

    FastAPI behind Uvicorn, port 8000, /healthz and /readyz

  2. 2
    worker

    Same image, different command; pulls ingestion jobs

  3. 3
    migrate

    One-off job: alembic upgrade head, then exits

  4. 4
    redis

    Queue and quota counters

  5. 5
    db

    PostgreSQL with pgvector, data in a named volume

FlowA safe release
  1. 1
    Build image

    Tagged with the git commit, not latest

  2. 2
    Run migrations

    Backward-compatible change only

  3. 3
    Start new version

    Readiness must pass before traffic

  4. 4
    Watch

    Error rate and latency for 15 minutes

  5. 5
    Keep or roll back

    Redeploy the previous tag if needed

MapCompose services and their managed equivalents
Q&A service
  • api
    • Container service with HTTPS ingress
    • Readiness on /readyz
  • worker
    • Container service, no ingress
    • Scale on queue length
  • migrate
    • One-off job in the release pipeline
  • db
    • Managed PostgreSQL with pgvector
    • Automated backups
  • redis
    • Managed Redis
    • Private network only

In depth

Writing the Compose file

Prerequisites: Docker Engine or Docker Desktop with the Compose plugin, and the project's Dockerfile. Define five services. db uses an image with pgvector, such as pgvector/pgvector:pg16, keeps its data in a named volume and has a healthcheck running pg_isready. redis uses the official image with its own healthcheck, redis-cli ping. migrate builds your image and runs alembic upgrade head once. api builds the same image and runs fastapi run or uvicorn on port 8000. worker builds the same image and runs your worker module.

Use depends_on with conditions to set the order: migrate waits for db to be service_healthy, and api and worker wait for migrate to be service_completed_successfully. Expected evidence after docker compose up -d: docker compose ps shows db and redis as healthy, migrate as exited with code 0, and api and worker as running. Cleanup: docker compose down keeps data; docker compose down -v also deletes the volumes.

  • One image, two commands: api and worker
  • Named volume for PostgreSQL data
  • depends_on conditions instead of sleep loops
  • Publish only the API port to the host

Injecting secrets at runtime

Twelve-factor style apps read configuration from the environment, and pydantic-settings makes that typed: a Settings class with DATABASE_URL, REDIS_URL and MODEL_API_KEY fields. Locally, put values in a .env file listed in .gitignore and reference it with env_file in Compose. For anything that should not show up in docker inspect output, use Compose secrets: a top-level secrets entry pointing to a file, and a service-level secrets list. Each secret appears inside the container as a file under /run/secrets/. The official postgres image reads POSTGRES_PASSWORD_FILE for exactly this reason, and pydantic-settings can read a secrets directory too.

In a managed platform, the same settings come from its secret store, such as Azure Key Vault, AWS Secrets Manager or Google Secret Manager, referenced by the service definition. The code does not change: it still reads environment variables or files. Never copy a .env file into the image with COPY.

CompareWhere configuration comes from
Local Compose
  • .env file ignored by git
  • Compose secrets as files in /run/secrets
  • Placeholder values only
  • Recreated with docker compose up
Managed platform
  • Platform secret store
  • Referenced by the service definition
  • Rotated without rebuilding the image
  • Access controlled per service identity

Liveness and readiness probes

Give the API two endpoints. GET /healthz returns 200 as long as the process can answer; it checks nothing else. A platform uses it as a liveness probe and restarts the container if it stops answering. GET /readyz checks the things a request needs, such as a quick SELECT 1 on the database pool and a Redis PING, each with a short timeout, and returns 503 if one fails. A platform uses it as a readiness probe and stops sending traffic until it passes.

Keeping them separate matters. If liveness checked the database, a short database outage would restart every API container, which fixes nothing and adds a burst of reconnects when the database comes back. Workers usually have no HTTP port; a common pattern is a heartbeat timestamp the worker updates every few seconds, checked by a small command or by queue lag alerts.

Migrations before release, and the rollback plan

Run migrations once per release as their own step, before new code starts: the migrate service locally, or a one-off job or release command on a managed platform. Never let every API replica run them at startup, because replicas will race.

Use expand and contract. Release 1 adds a new nullable column and code that writes both old and new. A backfill fills old rows. Release 2 switches reads to the new column. Release 3 drops the old one. At every step, the previous image still works with the current schema, so rollback is just redeploying the previous tag. Write the rollback plan before you release: the previous tag, the command to redeploy it, the signal that triggers it (for example error rate above 2 percent for 5 minutes) and who decides. Alembic downgrade exists, but avoid relying on it in production when data has already been written in the new shape.

  • Migrations are a separate one-off step
  • Every migration must suit the old and new code
  • Rollback = redeploy previous image tag
  • Write the trigger and the command before release
FlowRenaming a column with expand and contract
  1. Step 1
    Expand

    Add new column, write to both

  2. Step 2
    Backfill

    Copy old values in batches

  3. Step 3
    Switch reads

    Code reads the new column

  4. Step 4
    Contract

    Later release drops the old column

Mapping the stack to one managed deployment

Each Compose service maps to a managed building block. The API becomes a container service with HTTPS ingress and autoscaling, such as Azure Container Apps, Google Cloud Run or AWS App Runner or ECS. The worker becomes a second service from the same image with no public ingress, scaled by queue length where the platform supports it. PostgreSQL becomes a managed database with pgvector enabled, such as Azure Database for PostgreSQL flexible server, Cloud SQL or Amazon RDS. Redis becomes a managed cache, such as Azure Managed Redis or Memorystore. The migrate service becomes a one-off job run by the release pipeline.

These services cost money. A free trial or credits often cover a short test, but you can complete this topic design-only: write the mapping table, the secret names and the probe paths, and keep running everything locally with Compose.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Write the Compose file~50m
  2. 2
    Inject secrets at runtime~50m
  3. 3
    Add liveness and readiness probes~50m
  4. 4
    Run migrations before release~50m
  5. 5
    Plan the rollback~50m

Key points

  • Build one image for the API and worker and choose the role with the start command.
  • Secrets come from the environment or mounted files at runtime; they are never baked into the image.
  • Liveness asks whether the process is alive; readiness asks whether it can serve requests right now.
  • Run migrations as a separate step before the new code, and keep them compatible with the old code.
  • Rollback means redeploying the previous image tag, which only works if the schema still suits it.

Key terms

Tap a card to flip it. 0/6 known

Examples

yaml
services:
  db:
    image: pgvector/pgvector:pg16
    environment: { POSTGRES_PASSWORD_FILE: /run/secrets/db_password }
    secrets: [db_password]
    healthcheck: { test: ["CMD-SHELL", "pg_isready -U postgres"], interval: 5s }
  migrate:
    build: .
    command: alembic upgrade head
    depends_on: { db: { condition: service_healthy } }
  api:
    build: .
    depends_on: { migrate: { condition: service_completed_successfully } }
secrets:
  db_password: { file: ./secrets/db_password.txt }

Excerpt: the API waits for migrations, which wait for a healthy database.

Readiness and liveness endpoints

Step 1: add /healthz that simply returns status ok and checks nothing. Step 2: add /readyz, shown below, that runs SELECT 1 and a Redis PING within a two-second overall timeout. Step 3: return 503 with the type of the error that failed the check. Drill: run docker compose stop db and call /readyz; expect 503 with db failing, while /healthz still returns 200. Then docker compose start db and watch /readyz return to 200. Cleanup: nothing to remove.

python
import asyncio
from fastapi import Request
from fastapi.responses import JSONResponse
from sqlalchemy import text
@app.get("/readyz")
async def readyz(request: Request):
    st = request.app.state  # engine and redis are set in the lifespan
    try:
        async with asyncio.timeout(2):
            async with st.engine.connect() as c:
                await c.execute(text("SELECT 1"))
            await st.redis.ping()
    except Exception as exc:
        return JSONResponse({"status": "unavailable", "error": type(exc).__name__}, status_code=503)
    return {"status": "ready"}

A release and a rollback, step by step

Prerequisites: the stack runs locally and images are tagged with the commit. Step 1: build qa-api:abc123 and run docker compose run --rm migrate; it adds a nullable column only. Step 2: set the image tag to abc123 and run docker compose up -d api worker. Step 3: check /readyz and send a test question. Step 4: a smoke test fails, so set the tag back to the previous one, def456, and run docker compose up -d api worker again. Expected evidence: docker compose ps shows the old tag and the smoke test passes. The added column is harmless to def456, so no database rollback is needed.

bash
export TAG=abc123
docker compose build
docker compose run --rm migrate
docker compose up -d api worker
curl -fsS localhost:8000/readyz
# rollback
export TAG=def456
docker compose up -d api worker

Quick reference

  • docker compose up -d starts the stack; docker compose ps shows health and exit codes.
  • depends_on condition: service_healthy or service_completed_successfully sets start order.
  • Compose secrets appear as files in the container, under /run/secrets/ with the secret name.
  • /healthz = process alive; /readyz = dependencies reachable. Never restart on readiness.
  • Run alembic upgrade head once per release as its own step, not in every replica.
  • Tag images with the git commit; rollback = redeploy the previous tag.
  • docker compose down -v deletes volumes and all local data; use it only to reset.

Common mistakes

  • Using the same endpoint for liveness and readiness, so a database blip restarts every API container.
  • Running alembic upgrade head inside every API replica at startup, so replicas race each other.
  • Dropping a column in the same release that stops using it, which makes rollback impossible.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where should the model API key come from in a deployed container?

Question 2

2The database is down for 30 seconds. What should happen to API containers?

Question 3

3Which migration keeps a rollback to the previous image safe?

Question 4

4Why run migrations as a separate one-off step?

Question 5

5What does docker compose down -v do that docker compose down does not?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add a healthcheck to a redis service in Compose so other services can wait for it with service_healthy.

  2. Exercise 2medium

    Give the api and worker services one shared build and different commands, and make both wait for the migrate service to finish successfully.

  3. Exercise 3hard

    Write a one-page rollback plan for a release that adds a summary column to documents and starts filling it in the worker.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should the worker run in the same container as the API?
No. Separate containers from the same image let you scale, restart and limit each one on its own, and a crash in one does not take down the other.
Is depends_on enough to make the API wait for the database?
Only with condition: service_healthy and a real healthcheck on the database. Plain depends_on just waits for the container to start, not for PostgreSQL to accept connections.
Do I need Kubernetes for this?
No. A managed container service plus a managed database covers this stack. Kubernetes becomes useful when you run many services and need its extra control.
Can I run this without paying for cloud services?
Yes. Everything runs locally with Docker Compose and a fake model. Treat the managed mapping as a design exercise unless you have a free trial or credits.

Go deeper

ShareXLinkedInWhatsApp