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.

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-pluginpackage, 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:
| Command | What it does |
|---|---|
docker compose up -d | Create the networks and volumes, then start all services in the background |
docker compose ps | List the services and their status |
docker compose logs -f | Follow the logs of all services (add a service name for one) |
docker compose stop / start | Stop or start the services without removing them |
docker compose down | Stop and remove the containers and the default network |
docker compose down --volumes | Same, and also delete the named volumes (this deletes the data) |
docker compose build | Build images for services that have a build: key |
docker compose pull | Pull the latest images for services that use image: |
docker compose exec <service> sh | Open a shell in a running service container |
docker compose config | Print 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.
services:
web:
build: .
ports:
- "8000:5000"
redis:
image: "redis:alpine"webis built from theDockerfilein the current folder;redisuses a ready image.- Service names are arbitrary. Name them by role, for example
frontend,backendordatabase. - Compose creates a default network for the project, and each service can reach the others by service name. Here
webconnects to Redis at hostnameredis.
Ports
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
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:
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:
$ docker compose --env-file compose.env pull
$ docker compose --env-file compose.env up -d2. 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:
services:
backend:
build: ./BackEnd
env_file:
- ./BackEnd/config.envBoth file types follow the same syntax rules:
| Line in the file | Value the app gets |
|---|---|
VAR=VAL or VAR="VAL" or VAR='VAL' | VAL |
VAR=VAL # comment | VAL (an inline comment needs a space before #) |
VAR=VAL# not a comment | VAL# 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 lines | Ignored |
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.
MYSQL_ROOT_PASSWORD=root@123
MYSQL_DATABASE=mydb
MYSQL_USER=dipen
MYSQL_PASSWORD=password
TAG=8.0.42-oraclelinux9services:
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:
schedulerandstorefrontare built from the Dockerfiles in their folders and published on host ports 8000 and 8001.databaseuses the MySQL image tag fromTAGin.env, and the official image creates the database and user from theMYSQL_*variables on first start../mysql:/docker-entrypoint-initdb.d:rois a read-only bind mount. The MySQL image runs any.sqlor.shfiles in that folder the first time the database is created, which is useful for seed data.kinetecois a named volume, so the database files survivedocker compose down.
Validate the file, start the stack, check its status and logs, then stop it:
$ docker compose config
$ docker compose up -d --build
$ docker compose ps
$ docker compose logs -f database
$ docker compose downWaiting 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:
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: 10Common mistakes
- Using
docker-compose: on new installs the v1 command does not exist. Usedocker compose. - Variable shows as blank: the
.envfile is not in the project folder, or the variable name is misspelled.docker compose configshows the filled-in values. - Data gone after a restart:
docker compose down --volumesdeletes named volumes. Use plaindownto 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 acompose.yamlfile; drop theversion:key. - Services on the same Compose project reach each other by service name.
.envfills in variables in the YAML;env_file:passes variables into the container.- Named volumes keep data across
down;down --volumesremoves it. depends_onwithcondition: service_healthywaits for a service to be ready, not only started.
Next in this series: Docker Swarm.
Keep reading
- Dockerfile Instructions, Best Practices and Harbor Registry
Every Dockerfile instruction in one table, an annotated multi-stage build, image best practices, and pushing images to a private Harbor registry and Docker Hub.
- Why My Secrets Looked Missing in ECS
Every env var list in our ECS container was missing the Secrets Manager values. Here is why, and how the Node inspector found them.
- Docker Swarm: Building a Cluster with Vagrant
Build a Docker Swarm cluster on Vagrant VMs, then initialise it, join nodes, run and scale services, and use overlay networks and volumes in swarm mode.