Docker

Docker Compose in Practice: From up to Healthchecks

The structure of a Compose file, the everyday commands, healthchecks with depends_on conditions, and keeping secrets in a .env file.

Docker Compose in Practice: From up to Healthchecks
Table of contents
  1. File structure
  2. The everyday commands
  3. Healthchecks and start order
  4. Secrets and the .env file
  5. Automatic restarts

Docker Compose defines and runs multi-container applications from a single YAML file. Instead of several long docker run commands, you describe the whole stack in one docker-compose.yml and bring it up with one command.

File structure

Every service has a name, and that name is also how containers find each other through Compose’s internal DNS:

services:
  db:
    image: mariadb:10.11
    environment:
      MARIADB_ROOT_PASSWORD: changeme
    volumes:
      - db_data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
      interval: 10s
      timeout: 5s
      retries: 10
  app:
    image: wordpress:latest
    depends_on:
      db:
        condition: service_healthy
    ports:
      - "8080:80"

volumes:
  db_data:

The everyday commands

  • docker compose up -d: create and start everything in the background
  • docker compose ps: container status, including healthcheck state
  • docker compose logs -f app: follow the logs of one service
  • docker compose exec app sh: open a shell in a running container
  • docker compose down: stop and remove the containers (volumes are kept)

Healthchecks and start order

The difference between “running” and “ready” is the single most important idea in Compose: a database can take a couple of minutes after its container starts before it actually accepts connections. A healthcheck probes the real state of the service every 10 seconds, and depends_on with condition: service_healthy makes the dependent service wait until the database is genuinely ready. The interval, timeout, retries and start_period fields control the probe precisely.

Secrets and the .env file

Do not write passwords into the YAML file. Compose automatically reads a .env file next to the project and substitutes ${VAR} variables:

environment:
  MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}

Add .env to your .gitignore.

Automatic restarts

The line restart: unless-stopped brings services back up after a server reboot, unless you stopped them yourself. For a production database and web server, that is the right choice.

About the author

Sina Farahmand

DevOps and back-end developer, into automation, CI/CD and command-line tools. If he has to do something twice, he writes a script for it.

All articles by Sina Farahmand

Comments

No comments yet. For technical questions, include the details (OS version, the exact error and the command you ran) to get a precise answer.

Leave a comment