Skip to content
DBDeependra Bhatta~/notes
Docker#docker · #docker-compose · #dockerfile

Docker Compose: Multi-Container Apps with compose.yaml

Define a whole multi-container stack in one compose.yaml with Docker Compose v2: services, ports, named volumes, .env variables and a MySQL-backed example.

· updated · 7 min read
ON THIS PAGE

Running an app with a database by hand means several long docker run commands, a network and a few volumes, all typed in the right order. Docker Compose declares all of that in one YAML file and starts the whole stack with one command.

This guide covers the Compose CLI, the structure of a compose.yaml file, how variables and .env files work, and a three-service stack backed by MySQL.

Prerequisites

  • Docker Engine with the docker-compose-plugin package, installed as in part 2
  • Familiarity with Dockerfiles and image builds from part 3

Compose v2: docker compose, not docker-compose

Compose is now a plugin of the Docker CLI, installed as docker-compose-plugin (see part 2). Use docker compose with a space. The old standalone docker-compose (v1) is no longer supported.

The default file name is compose.yaml. Compose also reads the older docker-compose.yml, but new projects should use compose.yaml. The top-level version: key is obsolete; Compose v2 ignores it and prints a warning.

Commands

Run these in the folder that holds compose.yaml:

CommandWhat it does
docker compose up -dCreate the networks and volumes, then start all services in the background
docker compose psList the services and their status
docker compose logs -fFollow the logs of all services (add a service name for one)
docker compose stop / startStop or start the services without removing them
docker compose downStop and remove the containers and the default network
docker compose down --volumesSame, and also delete the named volumes (this deletes the data)
docker compose buildBuild images for services that have a build: key
docker compose pullPull the latest images for services that use image:
docker compose exec <service> shOpen a shell in a running service container
docker compose configPrint the final file after variables are filled in. Good for checking a file before up.

The shape of a compose.yaml

The smallest useful file has a services: section. Each service becomes one or more containers.

YMLcompose.yaml
services:
  web:
    build: .
    ports:
      - "8000:5000"
  redis:
    image: "redis:alpine"
  • web is built from the Dockerfile in the current folder; redis uses a ready image.
  • Service names are arbitrary. Name them by role, for example frontend, backend or database.
  • Compose creates a default network for the project, and each service can reach the others by service name. Here web connects to Redis at hostname redis.

Ports

YMLcompose.yaml
services:
  frontend:
    image: "${FRONTEND_IMAGE}"
    ports:
      - "3000:80"
    networks:
      - mynetwork
 
networks:
  mynetwork:

3000 is the host port and 80 is the container port. Quote port mappings: YAML can misread some unquoted xx:yy values as numbers.

Named volumes

YMLcompose.yaml
services:
  mongodb:
    image: mongo:4.4
    command: [--bind_ip_all]
    volumes:
      - mongo-data:/data/db
 
volumes:
  mongo-data:

mongo-data is a named volume that Docker manages (under /var/lib/docker/volumes/ on Linux), and /data/db is the path inside the container. The volume must also be listed under the top-level volumes: key. It survives docker compose down, but not down --volumes.

Variables and .env files

Two features look alike but do different jobs.

1. The project .env file fills in ${VARIABLES} in compose.yaml. Compose reads .env from the project folder (next to compose.yaml) automatically:

YMLcompose.yaml
services:
  webapp:
    image: my-webapp-image
    environment:
      - DEBUG=${COMPOSE_DEBUG}

To use a file with another name, pass it with --env-file. Deploy scripts commonly use this form:

terminal
$ docker compose --env-file compose.env pull
$ docker compose --env-file compose.env up -d

2. env_file: passes variables into a container's environment. The variables go to the app at runtime; they are not used to fill in the YAML:

YMLcompose.yaml
services:
  backend:
    build: ./BackEnd
    env_file:
      - ./BackEnd/config.env

Both file types follow the same syntax rules:

Line in the fileValue the app gets
VAR=VAL or VAR="VAL" or VAR='VAL'VAL
VAR=VAL # commentVAL (an inline comment needs a space before #)
VAR=VAL# not a commentVAL# not a comment
VAR="VAL # not a comment"VAL # not a comment
VAR='${OTHER}'${OTHER} literally (single quotes turn off interpolation)
Lines starting with #, blank linesIgnored

See the official Docker Compose environment variables docs for the full rules and precedence.

Example: two web apps sharing one MySQL database

This stack builds two web apps from local folders and runs a MySQL database they both use. The database settings come from .env.

DOT.env
MYSQL_ROOT_PASSWORD=root@123
MYSQL_DATABASE=mydb
MYSQL_USER=dipen
MYSQL_PASSWORD=password
 
TAG=8.0.42-oraclelinux9
YMLcompose.yaml
services:
  scheduler:
    build: scheduler/.
    ports:
      - "8000:80"
    depends_on:
      - database
  storefront:
    build: storefront/.
    ports:
      - "8001:80"
    depends_on:
      - database
  database:
    image: "mysql:${TAG}"
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
    volumes:
      - ./mysql:/docker-entrypoint-initdb.d:ro
      - kineteco:/var/lib/mysql
volumes:
  kineteco:

What each part does:

  • scheduler and storefront are built from the Dockerfiles in their folders and published on host ports 8000 and 8001.
  • database uses the MySQL image tag from TAG in .env, and the official image creates the database and user from the MYSQL_* variables on first start.
  • ./mysql:/docker-entrypoint-initdb.d:ro is a read-only bind mount. The MySQL image runs any .sql or .sh files in that folder the first time the database is created, which is useful for seed data.
  • kineteco is a named volume, so the database files survive docker compose down.

Validate the file, start the stack, check its status and logs, then stop it:

terminal
$ docker compose config
$ docker compose up -d --build
$ docker compose ps
$ docker compose logs -f database
$ docker compose down

Waiting for the database to be ready

depends_on as a simple list only waits for the database container to start, not for MySQL to accept connections. If an app fails because the database is not ready yet, give the database a health check and wait for service_healthy. The following example shows the pattern with the MongoDB health check from one of my other projects:

YMLcompose.yaml
services:
  backend:
    build: ./BackEnd
    depends_on:
      mongodb:
        condition: service_healthy
  mongodb:
    image: mongo:4.4
    healthcheck:
      test: mongo --eval "db.adminCommand('ping')"
      interval: 5s
      timeout: 5s
      retries: 10

Common mistakes

  • Using docker-compose: on new installs the v1 command does not exist. Use docker compose.
  • Variable shows as blank: the .env file is not in the project folder, or the variable name is misspelled. docker compose config shows the filled-in values.
  • Data gone after a restart: docker compose down --volumes deletes named volumes. Use plain down to keep them.
  • Changed MYSQL_* values have no effect: the official image only applies them when the data volume is empty, on first start.

Key takeaways

  • Use docker compose (v2) and a compose.yaml file; drop the version: key.
  • Services on the same Compose project reach each other by service name.
  • .env fills in variables in the YAML; env_file: passes variables into the container.
  • Named volumes keep data across down; down --volumes removes it.
  • depends_on with condition: service_healthy waits for a service to be ready, not only started.

Next in this series: Docker Swarm.