CodeBlanks Logo Icon CodeBlanks

Putting it together - compose

Combine all services and run with compose up.

Putting it together: the full stack

Putting the parts together, the stack of API, PostgreSQL and Redis lives in a single file. The API takes the connection information from environment variables using the service names:

services:
  api:
    build: .
    ports: ["8000:8000"]
    environment:
      DATABASE_URL: postgresql://app:gizli@db:5432/app
      REDIS_URL: redis://cache:6379
    depends_on:
      db: {condition: service_healthy}
      cache: {condition: service_started}
  db:
    image: postgres:16
    ...
  cache:
    image: redis:7

Everyday commands

docker compose up -d              # start (create/update what's needed)
docker compose ps                 # status
docker compose logs -f api        # follow the api logs
docker compose exec db psql -U app   # a command in the service container
docker compose restart api        # restart
docker compose down               # remove (volumes stay)

The commands are run in the folder containing the compose file; from elsewhere -f path/compose.yaml is given.

Practice The full stack

Write a compose.yaml: the api service has build: ., port "8000:8000", REDIS_URL: redis://cache:6379 under environment, and cache under depends_on; the cache service uses the redis:7 image.

Starter code

terminal
# compose.yaml
# buraya yaz

Sample solution

terminal
# compose.yaml
services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      REDIS_URL: redis://cache:6379
    depends_on:
      - cache
  cache:
    image: redis:7

Expected output

[+] Running 3/3
 ✔ Network proje_default  Created
 ✔ Container proje-cache-1  Started
 ✔ Container proje-api-1  Started

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which rebuilds only the api image and updates the stack after a code change?

  • docker build compose.yaml
  • docker compose ps --build
  • docker compose up -d --build api Correct answer
  • docker compose down -v

Explanation: The unchanged db and cache containers aren't touched.

2 Run a command in a service container.

Question
docker compose ____ db psql -U app
Answer
docker compose exec db psql -U app

Explanation: compose exec runs in the running service container.

3 Match.

Term Meaning
up -d --build Rebuild and start
logs -f api Follow api logs
exec db Command in db
down Remove, volumes stay

All lessons in Beginner