Learn Docker · 8/12

Multi-Container Apps with Docker Compose

7 min read

Introduction to Docker Compose: Managing the Chaos

Definition: Docker Compose is an orchestration tool that allows you to define, configure, and run multi-container Docker applications using a single configuration file (typically named compose.yaml or docker-compose.yml).

The Problem: Up until now, you have likely been starting containers using the docker run command. This is completely fine for a single container. However, modern applications are rarely just one isolated process. A standard application usually requires a web server, a database, a caching layer (like Redis), and maybe a background worker.

If you want to start this environment manually, you have to run something like this:

bash
docker network create my_app_network
docker run -d --name cache --network my_app_network redis
docker run -d --name db --network my_app_network -e POSTGRES_PASSWORD=secret postgres
docker run -d --name web -p 8080:80 --network my_app_network my_web_image

Doing this every morning when you sit down to code is a nightmare. Typing a 400-character string of commands only to realize you missed a -d flag—leaving your terminal held hostage by an endless stream of database logs—is enough to ruin anyone's day. Furthermore, if a coworker wants to run your app, they have to know the exact sequence, network names, and environment variables.

The Solution: Docker Compose solves this by utilizing "Infrastructure as Code" principles. You write down the exact state of your application (which containers you need, how they connect, what data they save) into a single text file. Then, you execute a single command, and Docker handles the entire setup process.

Imagine running a restaurant. If you (the manager) have to personally turn on the ovens, unlock the doors, assign tables to waiters, and prep the ingredients one by one every single morning, you will be exhausted before the first customer arrives. Docker Compose is essentially a checklist you hand to an automated manager. You say, "Turn on the ovens, hire the chef, and open the doors." The automated manager executes the checklist instantly in the correct order.


Writing Your First compose.yaml File

Docker Compose uses YAML (YAML Ain't Markup Language) for its configuration files. YAML relies heavily on indentation (spaces, not tabs) to represent nested data structures.

Industry standard note: Historically, the file was named docker-compose.yml. Today, the official Docker Compose specification recommends naming it compose.yaml. Both work perfectly, but we will stick to the modern standard.

Here is the anatomy of a standard compose.yaml file:

yaml
# In older tutorials, you will see `version: '3.8'` here. 
# According to the modern Compose Specification, the version field is now obsolete and optional.

services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
  
  database:
    image: postgres:15
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: supersecretpassword

Breaking Down the Concepts

Before we write complex files, you only need to understand the concept of a Key-Value Pair and Lists in YAML.

  • Key-Value: image: nginx:latest (The key is image, the value is nginx:latest).
  • Lists: The - under ports represents an array/list. You can have multiple ports exposed.
  • Indentation: The nested structure tells Docker that web and database belong to services, and image belongs to web.

If your indentation is off by even one space, Docker Compose will fail and throw a parsing error. YAML is highly sensitive to whitespace.


Defining Services, Networks, and Volumes in Compose

In the industry, a production-grade or local-development Compose file revolves around three fundamental blocks: Services, Networks, and Volumes.

1. Services

Definition: A service is a single configuration block that defines how a specific container should run in your application.
Usage: Under the services: block, you give your container a custom name (e.g., api, frontend, db).

Inside a service, you define exactly what you used to put in your docker run flags:

  • image: Which image to pull from Docker Hub.
  • build: If you want Docker to build an image from a local Dockerfile instead of pulling one.
  • ports: Maps HostPort:ContainerPort.
  • environment: Passes environment variables to the container.
  • depends_on: Tells Compose to start another service before starting this one.

2. Networks

Definition: Networks are isolated communication channels between containers.
The Problem: If your Node.js application needs to fetch data from your PostgreSQL database, it needs a way to find it. In traditional networking, you would need IP addresses, which change every time a container restarts.
The Solution: By default, Docker Compose automatically creates a single custom network for your entire app. Every service defined in the compose.yaml file is connected to it.

Under the hood: Docker sets up an internal DNS (Domain Name System) server. This means containers can talk to each other using their service names as hostnames. Your web server does not need to know the database's IP; it just connects to http://database:5432.

3. Volumes

Definition: Volumes are persistent data storage mechanisms that live outside the container's lifecycle.
The Problem: Containers are completely ephemeral. If your database container restarts or crashes, all the user data stored inside it vanishes.
The Solution: You define a volume that maps a secure folder on your host computer to a folder inside the container. Even if the container is destroyed, the data remains safely on your computer.

Putting it all together: A Practical Industry Example

Let's look at a highly typical boilerplate for a Node.js backend connected to a PostgreSQL database.

yaml
services:
  api:
    build: .                 # Build the image from the Dockerfile in the current directory
    ports:
      - "3000:3000"
    environment:
      - DB_HOST=db           # Notice how the host is simply the name of the database service
      - DB_USER=myuser
      - DB_PASSWORD=mypass
    depends_on:
      - db                   # Don't start the API until the DB is running

  db:
    image: postgres:15       # Pull pre-built image from Docker Hub
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypass
      POSTGRES_DB: myappdb
    volumes:
      - pgdata:/var/lib/postgresql/data  # Map the volume to the DB's storage folder

# Declare the persistent volume globally so Compose knows it exists
volumes:
  pgdata:

Essential Compose CLI Commands: Up, Down, Build, and Logs

Docker recently migrated Compose from a standalone program (docker-compose) to a built-in Docker CLI plugin (docker compose). Always use the space, not the hyphen, to ensure you are using the modern Version 2 of Compose.

1. Starting the application: docker compose up

Definition: Builds, (re)creates, starts, and attaches to containers for a service.
Problem: By default, running this will lock up your terminal window with a wall of logs from every container. If you hit Ctrl+C, it kills all your containers.
Industry Standard: Always run it in detached mode using the -d flag.

bash
docker compose up -d

Under the hood: Compose reads the YAML file, provisions the network, creates the volume pgdata, pulls the postgres image, builds the api image from your Dockerfile, and boots them up in the correct order based on depends_on.

2. Stopping the application: docker compose down

Definition: Stops containers and removes containers, networks, volumes, and images created by up.
Usage:

bash
docker compose down

When you are done working for the day, running this command gracefully shuts down your containers and deletes the temporary default network.

Important Practicality: docker compose down does not delete your volumes by default. Your database data is safe! If you actually want to destroy everything, including the persistent volumes (often needed when resetting a broken local database), you run:

bash
docker compose down -v

3. Rebuilding changes: docker compose build

Definition: Rebuilds the images associated with your services.
Problem: If you change the code in your Node.js app or modify the Dockerfile, running docker compose up -d will not reflect the changes. Compose is lazy; if an image already exists locally, it just uses it to save time.
Solution: Force Compose to rebuild the image with the new code.

bash
docker compose build
# Or combine the process:
docker compose up -d --build

4. Viewing the chaos: docker compose logs

Definition: Displays log output from services.
Problem: Because you ran up -d to keep your terminal free, you can no longer see if your application is throwing errors.
Solution: Use the logs command.

bash
docker compose logs

Industry Standard: The above command prints a massive wall of past logs and exits. Usually, you want to monitor the logs in real-time. Use the -f (follow) flag.

bash
docker compose logs -f

If you only care about why the database specifically is crashing, you can append the service name:

bash
docker compose logs -f db

External References and Further Reading

Challenge

Docker Compose Challenge: Three-Tier Application

Your task is to write a complete compose.yaml file to define and run a multi-service application. The application consists of a custom API backend, a PostgreSQL database, and a Redis cache.

Requirements:

  1. Define three services: api, db, and cache.

  2. api Service:

    • Build from a Dockerfile located in the current directory (.).
    • Map port 8080 on the host to port 3000 in the container.
    • Set the following environment variables:
      • DB_HOST=db
      • DB_USER=myuser
      • DB_PASSWORD=mypassword
      • DB_NAME=mydatabase
      • REDIS_HOST=cache
    • Ensure this service only starts after the db and cache services are running.
  3. db Service:

    • Use the postgres:13 image from Docker Hub.
    • Set the POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB environment variables to match the credentials defined in the api service.
    • Persist the database data using a named volume called db-data. This volume should be mapped to the container's /var/lib/postgresql/data directory.
  4. cache Service:

    • Use the redis:latest image from Docker Hub.
  5. Top-Level Definitions:

    • Define the named volume db-data at the top level of the compose.yaml file.
    • Define a custom bridge network named app-net at the top level and configure all three services to use it.

Constraint: Do not include the obsolete version key at the top of your file.

Expected result

A valid compose.yaml file that defines a top-level services block containing three services: api, db, and cache.

The file should also include top-level volumes and networks blocks.

  • The api service must correctly specify the build context, ports mapping, environment variables, and a depends_on clause listing both db and cache.
  • The db service must use the specified postgres image, define its required environment variables, and mount the named db-data volume to the correct path.
  • The cache service must use the specified redis image.
  • All three services must be explicitly connected to the app-net network.
  • The db-data volume and app-net network must be declared in their respective top-level sections.
  • The YAML syntax and indentation must be correct throughout the file.
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.