DevLearningTools

LEARN · DOCKER

Docker Compose

Docker Compose runs several containers together from one compose.yaml file, so a web app and its database start, connect, and stop with a single command.

A real application usually needs more than one container, for example a web app and a database. Compose lets you describe all of them in one file, then start or stop the whole set with one command.

Learning Objectives

  • Write a compose.yaml file that defines two connected services.
  • Start, check, and stop the whole stack with Compose commands.
  • Keep data safe with a named volume and avoid hardcoding secrets.

How Compose Fits Together

compose.yaml

describes every service

docker compose up

creates and starts all services

Services Share a Network

they reach each other by service name

docker compose down

stops and removes the stack

Step by Step: A Web App With a Database

  • Save the file as compose.yaml in your project folder.
  • Run docker compose up -d to start both services in the background.
  • Check status with docker compose ps, and read a service's output with docker compose logs web.
  • Stop and remove everything with docker compose down. Add -v only when you really want to delete the database volume.
compose.yaml
services:
  web:
    image: nginx:1.27
    ports:
      - "8080:80"
    depends_on:
      - db

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:
Shell
docker compose up -d
docker compose ps
docker compose logs web
docker compose down

Common Mistakes

Adding a top-level version key

Compose's official docs say the version key is obsolete and produces a warning. Leave it out and start the file with services.

Expecting depends_on to wait until the database is ready

depends_on only controls start order. The database may still be starting when the web service begins. Have the app retry its connection, or use a health check.

Writing passwords directly in the file

Anyone who reads or shares the file sees the password. Use a secret or an env file that stays out of version control.

Running docker compose down -v by accident

The -v flag also deletes named volumes, which means the database data is gone.

Interview Questions

What is Docker Compose used for?

Defining and running a multi-container application from one file, with one command to start and stop it.

What's the difference between docker compose down and docker compose stop?

stop only stops the containers. down stops them and removes the containers and networks it created.

Summary

Compose describes a multi-container app in compose.yaml. Start it with docker compose up, watch it with ps and logs, and stop it with down, taking care with volumes.