TExcelTAD
Home › Docker Compose › Your First Compose App

Your First Compose App

Time to build something. In this lesson you will write a small two-service application, a Python web API that counts visits and a Redis server that stores the counter, and run it with Compose. Along the way you will see the full life cycle: write the file, check it, start it, look at it, change it and tear it down.

text
   browser / curl                     project "counter"
        │                ┌──────────────────────────────────────────┐
        │ :8000          │  network counter_default                 │
        └──────────────▶ │  ┌──────────────┐  redis:6379  ┌───────┐ │
                         │  │ counter-api-1 │ ───────────▶ │ redis │ │
                         │  └──────────────┘              └───────┘ │
                         └──────────────────────────────────────────┘

The project folder

text
counter/
├── compose.yaml
└── api/
    ├── Dockerfile
    ├── requirements.txt
    └── app.py

The API is a few lines of Flask. It reads the Redis host from an environment variable, so the same code works inside and outside Compose:

python
# api/app.py
import os
from flask import Flask
from redis import Redis

app = Flask(__name__)
store = Redis(host=os.environ.get("REDIS_HOST", "localhost"), port=6379)

@app.get("/")
def hello():
    visits = store.incr("visits")
    return f"Hello from Compose! This page has been seen {visits} times.\n"
text
# api/requirements.txt
flask==3.1.2
redis==6.4.0
dockerfile
# api/Dockerfile
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
CMD ["flask", "--app", "app", "run", "--host", "0.0.0.0", "--port", "8000"]

The Compose file

Two services. api is built from the api/ folder, redis uses an official image. Only the API publishes a port; Redis stays private on the project network, where the API reaches it by its service name redis.

compose · try it yourself
# $ docker compose config --no-path-resolution
name: counter
services:
  api:
    build: ./api
    ports:
      - "8000:8000"
    environment:
      REDIS_HOST: redis
    depends_on:
      - redis
  redis:
    image: redis:8-alpine
name: counter
services:
  api:
    environment:
      REDIS_HOST: redis
    networks:
      default: null
    build:
      context: ./api
      dockerfile: Dockerfile
    depends_on:
      redis:
        condition: service_started
        required: true
    ports:
      - mode: ingress
        target: 8000
        published: "8000"
        protocol: tcp
  redis:
    image: redis:8-alpine
    networks:
      default: null
networks:
  default:
    name: counter_default

The example uses --no-path-resolution so the build context stays relative (./api). Without it Compose prints the absolute path of the folder on your machine. Read the output carefully:

  • name: counter overrides the default project name (the folder name). All resources will be prefixed with it.
  • build: ./api became a build block with a context and the default dockerfile: Dockerfile.
  • The short list depends_on: [redis] became a map with condition: service_started: Compose starts redis before api, but does not wait for Redis to be ready. Healthchecks fix that.
  • The port became a structured entry, and the value of REDIS_HOST is a string.

Start it

Run up from the project folder. -d (detached) returns your terminal once the containers are running; --build rebuilds images whose sources changed.

bash
$ docker compose up -d --build
[+] Building 9.4s (11/11) FINISHED
 => [api internal] load build definition from Dockerfile                   0.0s
 => [api 1/5] FROM docker.io/library/python:3.13-slim                     2.1s
 => [api 4/5] RUN pip install --no-cache-dir -r requirements.txt          5.8s
 => [api] exporting to image                                              0.4s
[+] Running 4/4
 ✔ api                        Built                                       0.0s
 ✔ Network counter_default    Created                                     0.1s
 ✔ Container counter-redis-1  Started                                     0.4s
 ✔ Container counter-api-1    Started                                     0.6s

(Sample output.) Compose built counter-api, created the network, then started the containers in dependency order. Try it:

bash
$ curl http://localhost:8000/
Hello from Compose! This page has been seen 1 times.
$ curl http://localhost:8000/
Hello from Compose! This page has been seen 2 times.

Look around

bash
$ docker compose ps
NAME              IMAGE            COMMAND                  SERVICE   CREATED          STATUS          PORTS
counter-api-1     counter-api      "flask --app app run…"   api       12 seconds ago   Up 11 seconds   0.0.0.0:8000->8000/tcp
counter-redis-1   redis:8-alpine   "docker-entrypoint.s…"   redis     12 seconds ago   Up 12 seconds   6379/tcp

$ docker compose logs api
api-1  |  * Serving Flask app 'app'
api-1  |  * Running on http://172.19.0.3:8000
api-1  | 172.19.0.1 - - [18/Oct/2026 09:12:40] "GET / HTTP/1.1" 200 -

$ docker compose exec redis redis-cli get visits
"2"

ps only lists this project's containers. logs prefixes each line with the service, and exec runs a command in a running service container, here the Redis CLI, which confirms where the counter lives.

How the pieces talk

The API connects to redis:6379. That works because Compose attached both containers to counter_default, and Docker's embedded DNS answers the service name with the container's IP. The model below plays both sides: a dict stands in for Redis, and a tiny resolver stands in for the network's DNS.

python · try it yourself
network = {"api": "172.19.0.3", "redis": "172.19.0.2"}
redis_server = {}

def resolve(name):
    if name not in network:
        raise LookupError(f"Error -3 connecting to {name}:6379. Temporary failure in name resolution.")
    return network[name]

def handle_request(redis_host):
    ip = resolve(redis_host)
    redis_server["visits"] = redis_server.get("visits", 0) + 1
    return f"[{ip}] Hello from Compose! This page has been seen {redis_server['visits']} times."

for _ in range(3):
    print(handle_request("redis"))

try:
    handle_request("localhost-redis")
except LookupError as err:
    print("api error:", err)
[172.19.0.2] Hello from Compose! This page has been seen 1 times.
[172.19.0.2] Hello from Compose! This page has been seen 2 times.
[172.19.0.2] Hello from Compose! This page has been seen 3 times.
api error: Error -3 connecting to localhost-redis:6379. Temporary failure in name resolution.

The last call shows the classic first-day mistake: using a name (or localhost) that doesn't exist on the project network. Inside a container, localhost is the container itself, not your laptop and not another service.

Change something

Edit the file, for example publish Redis on the loopback interface so a desktop GUI can inspect it, and run up -d again. Compose compares the new configuration with the running containers and recreates only the service that changed:

bash
$ docker compose up -d
[+] Running 2/2
 ✔ Container counter-redis-1  Recreated                                   0.3s
 ✔ Container counter-api-1    Running                                     0.0s

The counter is gone after that recreate, because Redis kept its data inside the container. A named volume would have kept it.

Tear it down

bash
$ docker compose down
[+] Running 3/3
 ✔ Container counter-api-1    Removed                                     0.3s
 ✔ Container counter-redis-1  Removed                                     0.2s
 ✔ Network counter_default    Removed                                     0.1s

down removes containers and networks. Named volumes survive unless you add -v, and built images stay unless you add --rmi local.

The workflow in one table

Step Command
Check the file docker compose config
Build and start docker compose up -d --build
Status docker compose ps
Logs docker compose logs -f api
Shell in a service docker compose exec api sh
Apply edits docker compose up -d
Stop and clean up docker compose down

Learn more: The Compose File · The Compose CLI · Compose Basics in the Docker course

Test yourself

How does the api container find Redis in this project?

  1. Through localhost:6379
  2. By the service name redis on the project network
  3. Through the published host port
  4. Compose writes Redis's IP into app.py

You change only the redis service and run docker compose up -d again. What happens?

  1. Every container is recreated
  2. Only the redis container is recreated
  3. Nothing until you run down
  4. Compose rebuilds the api image

What does plain docker compose down leave behind?

  1. Nothing
  2. Named volumes and images
  3. Containers
  4. The default network