How to Use Docker Compose for Multi-Container Applications: A Practical Tutorial

Docker Compose lets you define and run multi-container Docker applications with a single configuration file. Instead of manually starting each container, you write a docker-compose.yml file that describes the services, networks, and volumes your app needs. This tutorial walks you through the essential steps to get a multi-container stack up and running quickly.

The core of Docker Compose is a YAML file where each service maps to a container image, port mapping, environment variables, and dependencies. For example, a web app might need a Node.js service for the front‑end and a PostgreSQL service for the database. Compose handles the orchestration so containers can communicate seamlessly.

Article illustration

1. Define Your Services in docker-compose.yml

Start by creating a docker-compose.yml file in your project root. Each service gets a name, an image (or build context), and optional ports:

version: '3'
services:
  web:
    build: .
    ports:
      - "3000:3000"
  db:
    image: postgres:13
    environment:
      POSTGRES_PASSWORD: example

Indentation matters; use spaces, not tabs. The version key specifies the Compose file format (3.x is standard for modern setups).

2. Wire Up Networking and Dependencies

By default, Compose creates a virtual network for your services. Containers reference each other by service name. Use depends_on to control startup order:

services:
  web:
    depends_on:
      - db
    environment:
      DATABASE_URL: postgres://postgres@db:5432/mydb

The depends_on key ensures the database starts before the web service, but Compose does not wait for the database to be ready – you may need a health check for production apps.

3. Manage Your Multi-Container Stack

Run the entire application with a single command: docker-compose up. Add -d to run in detached mode. To stop and remove containers, networks, and volumes, use docker-compose down. View logs with docker-compose logs -f. If you change the YAML file, run docker-compose up --build to rebuild images.

4. Add Volumes for Persistent Data

Define volumes in the YAML to keep data across container restarts:

services:
  db:
    volumes:
      - db_data:/var/lib/postgresql/data
volumes:
  db_data:

Named volumes are stored by Docker and outlive your containers. You can also mount host directories using ./local-folder:/container-path.

Docker Compose simplifies development, testing, and deployment of multi‑service apps. With one YAML file you control the entire stack, making it easy to share and reproduce environments across teams.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *