EMZETT.
Login

Docker Compose: Starting several containers together

In short: Docker Compose describes several containers, networks and volumes in one file and starts them with one command; ideal for a web app with a database in development and on small servers.

In more detail: An application often consists of several parts: web app, database, cache, reverse proxy. With individual docker run commands this becomes confusing. Docker Compose combines everything in one compose.yaml.

In Depth

Example

services:
  web:
    build: .
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app
    volumes:
      - dbdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
volumes:
  dbdata:

Services reach each other by their name (db). Compose creates a shared network.

Important commands

docker compose up -d          # start (in background)
docker compose logs -f web    # follow logs
docker compose ps             # status
docker compose exec db psql -U app   # command in container
docker compose down           # stop and remove
docker compose down -v        # additionally delete volumes (data gone!)
docker compose up --build     # rebuild

Older syntax: docker-compose (with hyphen).

Configuration and security

  • Do not write secrets into the repository: .env file (in .gitignore), env_file: or Docker secrets.
  • Publish ports only where necessary; do not open internal services (database) to the outside (127.0.0.1: or no port at all).
  • Volumes for persistent data; plan backups.
  • Pin versions (postgres:16 instead of latest).
  • Healthchecks and restart: unless-stopped for stability.
  • With profiles and override files (compose.override.yaml) you separate development and production.

Limits

Compose runs on one machine. For many servers, automatic scaling and resilience use Kubernetes or Docker Swarm. For home servers and small projects Compose is usually ideal. Learn Docker basics first, then Compose.

See also: Docker, Docker volumes and networks, Kubernetes basics, Docker: port is already allocated, env files