How to Use Docker Compose for Multi-Container Applications

Docker Compose lets you define and run multi-container Docker applications with a single YAML file. Instead of managing containers individually with lengthy docker run commands, Compose handles networking, volumes, and dependencies automatically. This tutorial walks you through the essential steps to get started.

Before diving in, ensure Docker Desktop or Docker Engine is installed on your system. Docker Compose comes bundled with modern Docker installations—verify with docker compose version. You’ll also need a project directory with your application code.

Article illustration

1. Create a docker-compose.yml File

The heart of Compose is the docker-compose.yml file. It defines your application’s services, networks, and volumes. Here’s a minimal example with a web server and a database:

  • Service definition: Each service maps to a container. For example:
  • version: '3.8'
    services:
      web:
        image: nginx:latest
        ports:
          - "8080:80"
      db:
        image: postgres:15
        environment:
          POSTGRES_PASSWORD: example
  • Volumes & networks: Add volumes for persistent data and networks to isolate services.

2. Run and Manage Your Stack

Navigate to the directory containing your docker-compose.yml and use these fundamental commands:

  • Start services: docker compose up -d (detached mode). Compose pulls images, creates networks, and starts containers.
  • View logs: docker compose logs -f follows output from all services.
  • Stop & clean up: docker compose down stops containers and removes networks. Add -v to delete volumes.

3. Scale Services and Use Environment Variables

Compose makes scaling simple. For instance, docker compose up -d --scale web=3 runs three web containers behind a common network. You can also inject variables using an .env file or the environment key inside your YAML.

  • Example scaling: docker compose up -d --scale worker=5 for horizontal scaling.
  • Environment variables: Define them in environment: blocks or reference ${VAR} from an .env file.

4. Use Volumes for Persistence

Without volumes, container data disappears on restart. Add a volumes block to keep database files or uploads across sessions:

  • Define named volumes under volumes: in the top level of the YAML.
  • Mount them inside a service: db: volumes: - db-data:/var/lib/postgresql/data.

Docker Compose transforms complex multi-container setups into a single, repeatable process. Start with a simple docker-compose.yml, then expand with networks, volumes, and scaling to match your development or testing needs.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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