1. Home
  2. Blog
  3. DevOps

DevOps

Docker Compose Tutorial: Run Multi-Container Apps Step by Step

This Docker Compose tutorial shows you how to describe a whole app in one file, start it with a single command and manage volumes, health checks and logs like a pro.

8 min read
Docker Compose tutorial: run multi-container apps step by step

Key takeaways

  • Docker Compose describes all services of an app in one compose.yaml file.
  • Start everything with docker compose up -d and remove it with docker compose down.
  • Services reach each other by service name, so the web app connects to redis, not to localhost.
  • depends_on only controls start order; add a health check to wait until a service is really ready.

Running one container is easy. Running a web app, a database and a cache means three long docker run commands that you must remember in the right order. Docker Compose replaces them with one file and one command.

In this Docker Compose tutorial you will build a small web app that counts page visits in Redis. If containers are new to you, read our Docker tutorial for beginners first.

What Docker Compose does

Compose reads a YAML file that lists your services (containers), the images or Dockerfiles they use, their ports, variables and storage. It then creates a private network, so every service can reach the others by name.

Modern Docker ships Compose as a plugin, so the command is docker compose with a space. The older standalone docker-compose (with a hyphen) is the previous generation and you should use the plugin on new projects.

The sample app

Create a folder with three small files. The app is a Flask page that increments a counter in Redis.

# app.py
import os
import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host=os.environ.get("REDIS_HOST", "localhost"), port=6379)

@app.route("/")
def hello():
    count = cache.incr("hits")
    return f"Hello! This page was viewed {count} times.\n"
# requirements.txt
flask
redis
# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
CMD ["flask", "--app", "app", "run", "--host", "0.0.0.0"]

Note --host 0.0.0.0. Without it Flask listens only inside the container and you cannot reach it from your browser. For a leaner image, see our Dockerfile best practices.

The compose.yaml file

Add this file next to the others. It defines two services and one named volume.

services:
  web:
    build: .
    ports:
      - "8000:5000"
    environment:
      REDIS_HOST: redis
    depends_on:
      - redis
  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data

volumes:
  redis-data:

build: . builds the image from your Dockerfile. ports maps your computer’s port 8000 to the container’s 5000. REDIS_HOST: redis is the key line: redis is the service name and Compose resolves it on the private network.

Run and test it

docker compose up -d
docker compose ps
curl http://localhost:8000
docker compose logs -f web

Each curl call raises the counter, for example “This page was viewed 1 times.” and then 2. The -d flag runs everything in the background, ps shows the state of each service and logs -f follows the output of the web container. Stop and delete the containers and network with:

docker compose down

Volumes and environment variables

The redis-data volume keeps the counter alive when you recreate the container. docker compose down keeps volumes, so the count survives. Add -v only when you want to delete the data too.

To avoid hard-coding values, use a .env file next to the compose file. Compose reads it automatically.

# .env
WEB_PORT=8000

# compose.yaml
ports:
  - "${WEB_PORT:-8000}:5000"

The part after :- is a default, used when the variable is not set. Never commit real passwords in .env; keep the file out of Git.

Start order and health checks

By default, depends_on starts Redis first, but it does not wait until Redis can accept connections. Your app may crash on its first request. A health check fixes this.

  web:
    depends_on:
      redis:
        condition: service_healthy
  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

Now Compose starts web only after redis-cli ping succeeds. This is the same idea that CI pipelines use to wait for services, which we cover in our GitHub Actions CI/CD guide.

Docker Compose commands you will use daily

Command What it does
docker compose up -d Create and start all services in the background
docker compose up --build Rebuild images before starting
docker compose ps List services and their state
docker compose logs -f web Follow the logs of one service
docker compose exec redis redis-cli get hits Run a command inside a running service
docker compose stop Stop services without removing them
docker compose down -v Remove containers, network and volumes

Tip: after you change only the compose file, docker compose up -d recreates just the services that changed. After you change code that is copied into the image, add --build.

Common Docker Compose mistakes

  • Using localhost between services. Inside a container, localhost is the container itself. Use the service name.
  • Tabs in YAML. YAML allows spaces only. Use two spaces per level.
  • Expecting depends_on to wait. Add a health check and condition: service_healthy.
  • Forgetting the port mapping. A service without ports is reachable only from other services.
  • Deleting data by accident. down -v removes volumes. Use plain down day to day.

Final thoughts

Docker Compose turns a pile of commands into a file you can review, share and commit. Start with two services, add a volume, then a health check, and you will cover most real projects.

Frequently asked questions

What is Docker Compose used for?

It runs multi-container applications from one YAML file. You describe services, networks and volumes once and start the whole stack with a single command.

What is the difference between docker-compose and docker compose?

docker-compose is the older standalone tool. docker compose is the newer plugin built into Docker and is the one to use for new projects.

How do containers talk to each other in Compose?

Compose creates a private network where each service is reachable by its service name, for example redis, on that service’s internal port.

Does docker compose down delete my data?

No. It removes containers and networks but keeps named volumes. Add the -v flag only if you also want to delete the volumes.

Is Docker Compose good for production?

It is excellent for local development, testing and small single-host deployments. Large production systems usually use an orchestrator such as Kubernetes.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →