Course contents · Lesson 6 of 22

Docker Compose Basics: Run Multi-Container Apps

Working with Docker · Lesson 6 of 22 · 12 min Engineer

In lesson 5 you started a web app and its Redis database with four commands, typed in order, with flags that had to match. Add a cache and the list grows, and so do the chances of a typo. Docker Compose replaces that list with one file. This lesson shows how to write it, run the whole app with one command, and where Compose stops being the right tool.

Why Compose: one file instead of many commands

Lesson 5's demo meant building the image, creating a network, then running the database and the web app on it. Forget --network app-net once and the two cannot find each other. The diagram compares that with Compose.

Before and after. Left, typed by hand: docker build -t myapp ., docker network create app-net, docker run for db with --network app-net, -v db-data:/data, redis:7.4-alpine and redis-server --appendonly yes, and docker run for web with --network app-net, -p 127.0.0.1:8080:8000 and myapp. Warning: four commands in the right order and three more to clean up. Right, one file: compose.yaml holds every flag; docker compose up -d starts or updates everything; docker compose down stops and removes it while the data stays. Ticks: the same result every time, and the file can live in Git next to your code
The flags move into a file, so starting the whole app shrinks to one command.

Docker Compose is a tool for defining and running multi-container apps. You describe the app in a YAML file, a plain-text format that nests settings by indentation. The file is declarative: it says what should exist, and Compose works out the steps to create those containers, networks and volumes.

Today Compose is the docker compose command, with a space, a plugin of the Docker command line that Docker Desktop includes. Older tutorials write docker-compose with a hyphen: that is Compose v1, which is no longer updated.

Anatomy of a compose.yaml

Compose looks for compose.yaml in the current folder (the older name docker-compose.yml also works). Work in lesson 5's myapp folder; if its old containers still exist, remove them with docker rm -f web db.

First, let the app read the database's address from an environment variable, a named setting handed to a process when it starts. In app.py, add import os as the first line, then change the Redis line to:

db = redis.Redis(host=os.environ.get("REDIS_HOST", "localhost"), port=6379)

The app now connects to the host REDIS_HOST names, or localhost when it is unset. Save this beside the Dockerfile as compose.yaml, indenting with spaces, never tabs, because indentation carries meaning:

services:
  web:
    build: .
    ports:
      - "127.0.0.1:8080:8000"
    environment:
      REDIS_HOST: db
    depends_on:
      db:
        condition: service_healthy
  db:
    image: redis:7.4-alpine
    command: redis-server --appendonly yes
    volumes:
      - db-data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

volumes:
  db-data:

Under services, each key is a service: one part of your app, run as one or more containers with the same settings. build: . builds web's image from this folder's Dockerfile; image: makes Compose pull db's ready-made image.

Most other keys mirror docker run flags: ports is -p, environment is -e, and command replaces the start command, here with lesson 5's Redis options. A service's volumes mounts like -v; the top-level volumes section declares the named volume, and Compose rejects a mount of an undeclared name.

depends_on makes Compose start db before web; the condition and healthcheck lines, explained in the last section, make it wait until Redis answers. Notice in the diagram that the file never mentions a network.

Left, the compose.yaml, trimmed: under services, a web block with build ., ports 127.0.0.1:8080:8000, environment REDIS_HOST: db and depends_on, and a db block with image redis:7.4-alpine, the volume db-data at /data and a healthcheck; then a top-level volumes block declaring db-data. Arrows lead right: web becomes the container myapp-web-1, built from your Dockerfile and published on 127.0.0.1:8080 to port 8000; db becomes myapp-db-1 from redis:7.4-alpine, which others reach by the name db. Both sit on the network myapp_default, added by Compose and not in the file. A dashed box shows that a cache would be one more block. The volumes block becomes the volume myapp_db-data, mounted by db at /data, which survives docker compose down
Every block under services becomes a container, and Compose adds the network itself.

Skip the version: "3.8" line that old guides start with: current Compose ignores it and warns that it is obsolete.

Run it: up, ps, logs and down

docker compose up creates and starts everything in the file; -d (detached) runs it in the background. In myapp, run:

docker compose up -d

The first run builds the web image and pulls Redis if needed. You should then see something like this (trimmed: the build output comes first, and wording varies by version):

 ✔ Network myapp_default    Created
 ✔ Volume "myapp_db-data"   Created
 ✔ Container myapp-db-1     Healthy
 ✔ Container myapp-web-1    Started

Every name starts with the project, Compose's name for the whole app, taken from the folder. The -1 is a copy number, since a service can run several identical containers. The flowchart shows the order behind those lines. If Docker reports port is already allocated, an old container holds port 8080: remove it with docker rm -f web.

Flowchart of docker compose up in six steps. 1, read the file compose.yaml; the project name, myapp, comes from the folder. 2, get the images: pull redis:7.4-alpine and build myapp-web from the folder. 3, create the network myapp_default, reused if it already exists. 4, create the volume myapp_db-data, reused if it already exists. 5, start db and wait until it is healthy, which means redis-cli ping must pass; if not yet healthy, check again in 5 seconds. 6, start web, myapp-web-1, only after db is healthy. Footer: run up again and anything unchanged is left running
Images first, then network and volume, then containers in dependency order.

Run curl http://localhost:8080 twice. The count starts at 1, because Compose made its own volume, myapp_db-data, rather than reusing lesson 5's db-data:

Hello from my container, visit 1
Hello from my container, visit 2

An Internal Server Error with a ConnectionError for localhost:6379 in the logs means REDIS_HOST never reached the app: check the environment indentation. Next, docker compose ps lists the project's containers; note (healthy) and that only web publishes a port (times will differ):

NAME          IMAGE              COMMAND                  SERVICE   CREATED          STATUS                    PORTS
myapp-db-1    redis:7.4-alpine   "docker-entrypoint.s…"   db        30 seconds ago   Up 29 seconds (healthy)   6379/tcp
myapp-web-1   myapp-web          "python app.py"          web       24 seconds ago   Up 23 seconds             127.0.0.1:8080->8000/tcp

docker compose logs prints every service's output, each line prefixed with its container; name a service to see one, and add -f to follow new lines until Ctrl+C. docker compose logs web ends with your two requests (trimmed; addresses and times are illustrative):

web-1  | 172.18.0.1 - - [28/Nov/2026 10:15:02] "GET / HTTP/1.1" 200 -
web-1  | 172.18.0.1 - - [28/Nov/2026 10:15:04] "GET / HTTP/1.1" 200 -

One trap: up builds an image only if it does not exist yet, so after editing app.py, run docker compose up -d --build. To stop, docker compose down removes the containers, web first, and the network, but keeps the named volume:

 ✔ Container myapp-web-1  Removed
 ✔ Container myapp-db-1   Removed
 ✔ Network myapp_default  Removed

Run up -d and curl again: the count carries on at visit 3, because the data lived in the volume. When you finish, docker compose down -v also removes the declared volumes, deleting the data for good.

Networking for free: services find each other by name

Compose creates one network per project, named after the project plus _default, and joins every service to it. It is a user-defined bridge network, so Docker's built-in DNS works as in lesson 5: each service is reachable by its service name. Another folder's project gets a separate network, so two projects can each have a db.

That is why REDIS_HOST: db works without any docker network create or --network. And db needs no ports entry, because containers on one network reach each other's ports directly; publish only what you open from your own machine.

Limits: start order is not readiness, and one machine only

A plain depends_on: [db] only sets the order: Compose starts web as soon as the db container is running. Running is not ready: a database can take seconds to open its files, and an app that connects once at start-up then crashes on "connection refused". Ours would cope, since redis-py connects at the first request, but many apps do not.

The fix is a health check: a command Docker runs inside the container at intervals, where exit code 0 means healthy. Ours runs redis-cli ping every 5 seconds (interval), allows 3 seconds per try (timeout) and marks the container unhealthy after 5 failures in a row (retries). With condition: service_healthy, Compose starts web only once db is healthy: the Healthy line above.

The second limit: Compose drives one Docker Engine on one machine. If that machine fails, every container stops, and Compose cannot spread copies across servers. It suits development, tests and small single-server setups; running containers across many machines is the job of Kubernetes, which What Is Kubernetes? introduces next.

Check yourself

You change the greeting in app.py and run docker compose up -d, but curl shows the old text. Why?

Compose reused the existing myapp-web image, because it builds only when the image is missing. up -d --build rebuilds it and recreates web.

An API crashes at start-up with "connection refused", although its service has depends_on: [db]. What is missing?

A readiness check: plain depends_on waits only until the db container runs, not until it accepts connections. Add a healthcheck to db and condition: service_healthy.

After down and up -d, the visit count carries on; after down -v, it restarts at 1. Why?

down keeps named volumes, where Redis stores its data; -v removes them too, so Redis starts empty.