DOCKER · DOCKER FROM SCRATCH · CHAPTER 5

Docker Compose

A complete application, with five services, in a single file and a single command.

6 min readCourse: Docker from ScratchLevel: beginner

From point A to point B

Point A: you can run and build containers, but a real application has several: a website, a database, a cache, a background process. Launching them one by one with docker run, in the right order and connected to each other, is slow and easy to break. Point B: by the end of this chapter you will describe a complete application in a YAML file and bring it up, inspect it and remove it with a single command.

YAML in five minutes

Compose is written in YAML, a text format designed to be read by people. Three rules cover almost everything:

  • Key and value separated by a colon and a space: image: redis.
  • Indentation sets the hierarchy. Use spaces, never tabs, and always the same amount (two is the usual).
  • Lists start with a dash: - "8080:80".
server:              # dictionary
  name: web-01       # key: value
  ports:             # list
    - 80
    - 443
  active: true
Good to know. Most Compose errors are indentation errors: a key two spaces further left ends up belonging to another block. Kubernetes, Ansible and GitHub Actions also use YAML, so you will reuse this skill a lot.

The sample application: a voting app with five services

Docker publishes a sample application designed for learning: a vote between two options, made of five pieces in different languages.

The voting application in Compose Users reach vote on port 8080 and result on port 8081 through the front-end network. Vote sends votes to redis; worker reads them from redis and writes them to the db PostgreSQL database; result reads the count from db. Redis, worker and db are only on the back-end network. NETWORK · FRONT-END NETWORK · BACK-END browser · :8080browser · :8081 votePython resultNode.js redisin-memory queue worker.NET dbPostgreSQL · volume vote reads writes count

Two public websites and three internal services. Diagram: The House of Routing.

ServiceTechnologyWhat it does
votePythonWebsite where the user votes
redisRedisIn-memory queue that receives the votes
worker.NETReads the votes from Redis and stores them in the database
dbPostgreSQLPersistent store for the results
resultNode.jsWebsite that shows the tally

It is microservices architecture in miniature: each piece does one thing, in the language that suits it best, and talks to the others over the network.

First with docker run: the problem

With what you know so far, deploying it would take five commands. First the data, then the websites with their ports and finally the worker:

docker run -d --name redis redis:alpine
docker run -d --name db -e POSTGRES_PASSWORD=postgres postgres:17-alpine
docker run -d --name vote   -p 8080:80 dockersamples/examplevotingapp_vote
docker run -d --name result -p 8081:80 dockersamples/examplevotingapp_result
docker run -d --name worker dockersamples/examplevotingapp_worker

The containers start, but the application does not work: vote looks for a server called redis and cannot find it. On Docker's default network, containers do not resolve each other by name.

Older courses fix this with --link redis:redis, which writes the other container's name and IP into the /etc/hosts file. That option is legacy and Docker advises against it. The current way is to create your own network: inside it, Docker resolves container names automatically.

docker network create voting
docker run -d --name redis --network voting redis:alpine
# ...and the same with --network voting for the other four

It works, but that is six commands you have to remember, run in order and repeat on every machine. That is what Compose is for.

The same deployment in a compose.yaml file

Docker Compose describes all the services of an application in one file and runs them on the same host. Each docker run option has an equivalent key:

# compose.yaml
services:
  redis:
    image: redis:alpine

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres

  vote:
    image: dockersamples/examplevotingapp_vote
    ports:
      - "8080:80"

  result:
    image: dockersamples/examplevotingapp_result
    ports:
      - "8081:80"

  worker:
    image: dockersamples/examplevotingapp_worker
docker compose up -d      # creates the network and starts the five services
docker compose ps         # status of each service
docker compose logs -f worker
docker compose down       # stops and removes containers and network

Notice what is missing: there is no --name, no --network, no --link. Compose creates a network for the project, connects every service to it, and each one is reachable by its service name.

Two updates compared with older courses. The command is docker compose (with a space, a Docker plugin), not the old docker-compose. And the version: key at the top of the file is obsolete: Compose always validates against the latest schema and, if you include it, only returns a warning. The recommended file name is compose.yaml, although docker-compose.yml still works.

Building your own images with build

image: downloads an image that already exists in a registry. If the image is yours and you have not published it yet, use build: with the folder that contains its Dockerfile, and Compose builds it before starting:

services:
  vote:
    build: ./vote            # ./vote/Dockerfile must exist
    image: thor/vote:dev     # optional: the name given to the built image
    ports:
      - "8080:80"
docker compose up -d --build    # forces a rebuild before starting

Paths are relative to the folder where compose.yaml lives. If the folder has no Dockerfile, Compose fails when building.

Startup order with depends_on

The worker is useless without Redis and PostgreSQL. With depends_on, Compose starts the dependencies first:

  worker:
    image: dockersamples/examplevotingapp_worker
    depends_on:
      - redis
      - db

Careful: this only guarantees that the database container started, not that it already accepts connections. If your service needs to wait until the dependency is ready, combine a healthcheck with the service_healthy condition:

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: postgres
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 5

  worker:
    image: dockersamples/examplevotingapp_worker
    depends_on:
      redis:
        condition: service_started
      db:
        condition: service_healthy

Networks: separating public from internal traffic

By default, all services share one network. In production it pays to separate them: a front-end network for what faces users and a back-end network for internal traffic. That way, the database cannot be reached from any service that does not need it.

You declare the networks at the end of the file, under the top-level networks key, and connect each service to the ones it needs:

services:
  vote:
    image: dockersamples/examplevotingapp_vote
    ports: ["8080:80"]
    networks: [front-end, back-end]
  result:
    image: dockersamples/examplevotingapp_result
    ports: ["8081:80"]
    networks: [front-end, back-end]
  redis:
    image: redis:alpine
    networks: [back-end]
  db:
    image: postgres:17-alpine
    networks: [back-end]
  worker:
    image: dockersamples/examplevotingapp_worker
    networks: [back-end]

networks:
  front-end:
  back-end:

Compose creates the networks when you run up and removes them with down. You do not have to create them by hand.

Lab: the complete voting application

Put it all together: images, variables, ports, dependencies that wait, networks and a volume so the votes survive a down.

mkdir voting && cd voting
# compose.yaml
services:
  vote:
    image: dockersamples/examplevotingapp_vote
    ports: ["8080:80"]
    depends_on: [redis]
    networks: [front-end, back-end]

  result:
    image: dockersamples/examplevotingapp_result
    ports: ["8081:80"]
    depends_on:
      db:
        condition: service_healthy
    networks: [front-end, back-end]

  worker:
    image: dockersamples/examplevotingapp_worker
    depends_on:
      redis:
        condition: service_started
      db:
        condition: service_healthy
    networks: [back-end]

  redis:
    image: redis:alpine
    networks: [back-end]

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres     # for practice only
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 5
    networks: [back-end]

networks:
  front-end:
  back-end:

volumes:
  db-data:
docker compose up -d
docker compose ps                    # wait until db shows as healthy
# Vote at http://localhost:8080 and see the result at http://localhost:8081
docker compose logs -f worker        # you will see each vote processed

docker compose down                  # removes containers and networks; the volume stays
docker compose up -d                 # the votes are still there
docker compose down -v               # now it removes the volume too
Connecting to what you know. The db-data volume is the same as -v in docker run, but managed by Docker instead of a folder of yours. You will see it in depth in the next chapter.

Cheat sheet: from docker run to Compose

docker runcompose.yaml
--name webthe service name: web:
redis:alpineimage: redis:alpine
docker build ./votebuild: ./vote
-p 8080:80ports: ["8080:80"]
-e KEY=valueenvironment:
-v data:/pathvolumes:
--network netnetworks:
--link (legacy)not needed: services call each other by name

Commands: docker compose up -d, ps, logs -f, exec service sh, down and down -v.

Challenge

Answer before you open the solution. Getting it wrong here is the cheapest way to learn.

1. You launch two containers with docker run, with no network options. Can one reach the other by name?

No. The default bridge network has no name resolution. Create your own network or use Compose, which creates it for you.

2. When do you use build: instead of image:?

When the image is yours and is not in a registry. build: points to the folder with the Dockerfile and Compose builds it.

3. The worker has depends_on: [db] and still fails to connect at startup. Why?

Because depends_on only waits for the container to start, not for PostgreSQL to accept connections. Add a healthcheck to db and condition: service_healthy.

4. In the lab, can worker talk to vote?

Yes. Both are on the back-end network. What cannot reach db is any service that is only on front-end.

5. You run docker compose down. Do you lose the votes?

No. down removes containers and networks, but not named volumes. Only down -v removes them.

What you take away

  • Compose describes a complete application in a YAML file and manages it with a single command.
  • In YAML, indentation with spaces is the structure.
  • Compose creates one network per project: services find each other by name. Forget --link.
  • image: downloads; build: builds from a Dockerfile.
  • depends_on orders startup; with service_healthy it waits until the dependency is ready.
  • Separate front-end and back-end networks so internal services cannot be reached from outside.
  • It is docker compose, without a dash, and without version: in the file.

In the next chapter you open the box: how Docker Engine works inside, how it isolates and limits containers and where it stores your data.

Official resources

Source and credits. Chapter written from Jesús Espinoza's study notes on KodeKloud's Docker for Absolute Beginners course (December 2024). Text drafted with AI assistance; original diagrams by The House of Routing. Technical details were checked against the official Docker documentation.

Navigate