Docker Compose tutorial multi-container app

Docker Compose Tutorial: Run a Multi-Container App

Introduction

One container is easy. Two containers that must talk — a web application and its database — is where Docker gets fiddly. Docker Compose removes that friction: you describe the whole stack in one YAML file, and one command starts it. This tutorial builds a working web app with a PostgreSQL database, persistent storage and healthchecks. You should already know what a container and an image are — if not, read our Docker Tutorial for Beginners first.

Version note (27 Nov 2026): the current Compose line is v5; the latest release is 5.8.0, released 17 November 2026. The Go-based plugin was called v2 for years; the v2 line ended at 2.40.3 (October 2025), and development continued as v5. The old Python tool, docker-compose with a hyphen, is v1, end of life since June 2023. The command is docker compose, with a space.

What Docker Compose Is (and What It Is Not)

Docker Compose reads a YAML file — usually compose.yaml — and creates the containers, networks and volumes it describes. Each entry is a service: a web server, a database, a cache. Compose turns each service into containers, connects them to a shared network, and manages them as one application, a project.

Compose implements the Compose Specification. The old 2.x and 3.x formats were merged into it, and the top-level version: field in old examples is obsolete.

Compose is not an orchestrator for many machines: by default, everything runs on one Docker host, with no rolling updates and no rescheduling when a machine dies. Use it for local development, demos and test environments.

Installing and Checking Your Version

On Windows and macOS, install Docker Desktop — Compose is included. On Linux, install Docker Engine from Docker’s official repository and add docker-compose-plugin.

docker --version
docker compose version

You should see a Docker Engine version and a line like Docker Compose version v5.8.0. If the second command fails with docker: ‘compose’ is not a docker command, the plugin is missing; if it prints a 2.x version, update to the v5 line.

Your First Compose File

This section builds a real, runnable stack: a small Python web app backed by PostgreSQL — a page that counts visits and stores the count in the database. Create this layout:

compose-tutorial/
├── compose.yaml
└── web/
    ├── Dockerfile
    ├── requirements.txt
    └── app.py

web/app.py connects to the database and increments a counter on every visit:

import os

import psycopg
from flask import Flask

app = Flask(__name__)

def get_count():
    with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
        with conn.cursor() as cur:
            cur.execute("CREATE TABLE IF NOT EXISTS visits (id INT PRIMARY KEY, count INT)")
            cur.execute(
                "INSERT INTO visits (id, count) VALUES (1, 1) "
                "ON CONFLICT (id) DO UPDATE SET count = visits.count + 1 "
                "RETURNING count"
            )
            return cur.fetchone()[0]

@app.route("/")
def hello():
    count = get_count()
    return f"Hello from Docker Compose! This page has been seen {count} time(s).\n"

web/requirements.txt:

flask
psycopg[binary]

web/Dockerfile:

FROM python:3.12-alpine
WORKDIR /code
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["flask", "run", "--host=0.0.0.0"]

Now compose.yaml in the project root:

services:
  web:
    build: ./web
    ports:
      - "8000:5000"
    environment:
      - DATABASE_URL=postgresql://appuser:apppassword@db:5432/appdb
    depends_on:
      db:
        condition: service_healthy
    networks:
      - appnet

  db:
    image: postgres:18
    environment:
      POSTGRES_USER: appuser
      POSTGRES_PASSWORD: apppassword
      POSTGRES_DB: appdb
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s
    networks:
      - appnet

volumes:
  pgdata:

networks:
  appnet:

Three ideas do the work. A service is one piece of the stack: web is built from ./web, and db runs the official postgres:18 image. Ports map host to container: “8000:5000” means port 8000 on your machine reaches port 5000 in the container. Services reach each other by service name: db resolves to the database container.

Start it with docker compose up -d (-d runs detached). Open http://localhost:8000 — you should see a count of 1, rising on every refresh. Stop with docker compose down: it removes containers and the network, but not the pgdata volume, so the counter continues after the next up.

Volumes, Networks and Environment Variables

Volumes are where data lives. A container’s filesystem is disposable: remove the container and anything written inside it disappears. A named volume like pgdata is Docker-managed storage outside any container’s lifecycle, mounted where PostgreSQL stores data, so the data survives down and the next up. Delete it with docker compose down -v — the data is gone permanently.

A bind mount maps a host directory into a container instead: ./web:/code. Bind mounts are for development; named volumes are for data. A bind mount of an empty host directory over the database path hides the data instead of persisting it.

Networks are how services talk. Compose creates a project network automatically, and services resolve each other by name using Docker’s built-in DNS — that is why the app connects to db, not localhost. Ports are the other half: only published ports are reachable from outside the network, and the database publishes none.

Environment variables pass configuration in without editing the file. A .env file in the project directory is read automatically, and its values substitute into the file as ${VARIABLE}. Never commit a real password to Git; apppassword here is a throwaway local value.

depends_on, Healthchecks and Startup Order

The most common beginner bug is the startup race: the app starts, tries to connect, the database is not ready yet, and the app crashes.

depends_on alone only controls order. The short form, depends_on: [db], waits for the container to start — nothing more. PostgreSQL can be running for several seconds before it accepts connections. The long form waits for a condition, and the one that matters is service_healthy, used in this tutorial’s file. It needs a healthcheck: a command Compose runs inside the container to test readiness. Ours uses pg_isready, which succeeds only when the server accepts connections. (The $$ escapes Compose’s own ${…} substitution.) The timings: wait 10 seconds before counting failures (start_period), then check every 5 seconds, allowing 3 seconds per check, and mark the container unhealthy after 5 failures.

Two limits: service_healthy waits for the healthcheck, not for your app to be ready to serve traffic; and it does not help if the app never retries a failed connection. Use both.

Everyday Commands (up, logs, exec, down, profiles)

These are the commands you will use day to day.

docker compose up -d          # start everything, detached
docker compose ps             # list the project's containers and their health
docker compose logs -f        # follow the combined logs of all services
docker compose logs -f web    # follow one service's logs only
docker compose exec web sh    # open a shell inside the running web container
docker compose exec db psql -U appuser -d appdb   # run psql inside the database
docker compose stop           # stop the containers, keep them and their data
docker compose start          # start stopped containers again
docker compose down           # stop and remove containers and networks, keep volumes
docker compose down -v        # also remove named volumes — data deleted permanently

logs -f is the first command to reach for when something is wrong: combined output of every service, with the service name on each line. exec runs a command in a running container; run starts a new one-off container.

Profiles solve the “sometimes I need this service” problem. A service with a profiles list does not start with a plain up — only when its profile is active:

  adminer:
    image: adminer
    ports:
      - "8080:8080"
    depends_on:
      db:
        condition: service_healthy
    profiles:
      - debug
    networks:
      - appnet

Run docker compose –profile debug up -d and Adminer appears at http://localhost:8080. Without the flag, the service does not start.

Docker Compose vs Kubernetes — When to Use Each

Compose runs on one host. Kubernetes runs across a cluster of machines. That single difference explains almost everything else: Kubernetes can reschedule a container onto a healthy machine when one fails, spread replicas across machines, and roll out a new version with zero downtime. Compose cannot — there is no second machine to reschedule onto.

Compose is simpler by design: a few dozen lines of YAML and one command. Kubernetes needs a cluster, and its equivalent is a set of Deployments, Services, ConfigMaps, PersistentVolumeClaims and Ingress resources. Our Kubernetes Tutorial for Beginners walks through those from zero.

The practical rule: develop and test locally with Compose, deploy to production on Kubernetes. Compose is not an orchestrator in the Kubernetes sense: it never decides which machine runs a container.

Common Beginner Mistakes

  • Writing version: “3” at the top of the file. The field is obsolete — delete it.
  • Using docker-compose with a hyphen. That is Compose v1, end of life since June 2023.
  • Using depends_on without a healthcheck. The short form only waits for the container to start.
  • Publishing the database port. A database with no outside users should publish no port.
  • Committing real passwords to Git. Use a gitignored .env file.
  • Running docker compose down -v without thinking. It deletes named volumes and their data.
  • Forgetting that up does not rebuild. After changing code, run docker compose up –build.
  • One giant Compose file for every environment. Split with override files or profiles.

FAQ

Is Docker Compose the same as Docker? No. Docker is the platform that runs containers; Compose is a tool on top of it that manages multi-container applications from a single YAML file.

Do I need Kubernetes to use Docker Compose? No — Compose runs on one Docker host with no cluster at all.

What is the difference between docker compose stop and docker compose down? stop halts the containers but keeps them, so start brings the same ones back. down removes the containers and networks, so the next up creates fresh ones — but it keeps named volumes, so the data survives. Add -v and the volumes go too.

Why does my app fail to connect to the database on the first start, but work after a restart? That is the startup race: the app started before PostgreSQL was ready. Add a healthcheck to the database and condition: service_healthy to the app’s depends_on.

Can I use Docker Compose in production? For a small application on a single server, yes. For high availability or scaling across machines, use Kubernetes instead.

What happened to Compose v2, and should I install it? The v2 line ended at 2.40.3 in October 2025, and development continued as v5. Install v5 — not v2, and not the Python v1 tool, end of life since June 2023.

Conclusion

You now have a complete multi-container application in one file: a web service built from your code, a PostgreSQL database with persistent storage, a healthcheck that makes startup order real, and a debug tool you can switch on with a profile.

Next, put the Compose file in the same repository as your application and wire it into CI — our GitHub Actions Tutorial shows how that pipeline looks.

Sources checked 27 Nov 2026: Docker Compose Quickstart (https://docs.docker.com/compose/gettingstarted/); Compose file reference (https://docs.docker.com/reference/compose-file/); Docker Docs profiles and startup-order pages; docker/compose GitHub releases via release trackers (v5.8.0, 17 Nov 2026; v2 ended at 2.40.3, Oct 2025); Docker blog, 31 Jan 2023 (v1 support ended June 2023). Re-check the latest 5.x release on the publication date.

—

Scroll to Top