compose.yaml: services, ports and volumes
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite runs only on your laptop, and starting its API and MySQL takes two long docker run commands that nobody remembers. Write them down once in one file, and anyone can start the whole shop.
From docker run commands to one compose.yaml
Docker Compose is a tool that reads one YAML file, compose.yaml, which lists the containers of an app, and starts, stops and removes them together with one command.
ShopLite's MySQL needs a long docker run command like the one below. A compose file holds the same settings as plain keys, so nobody has to remember the flags.
docker run -d --name shoplite-db -p 3307:3306 \ -e MYSQL_ROOT_PASSWORD=rootpass -e MYSQL_DATABASE=shoplite \ -e MYSQL_USER=shoplite -e MYSQL_PASSWORD=shoplitepass \ -v mysql-data:/var/lib/mysql --restart unless-stopped mysql:8.4Example 1 · compose.yaml: MySQL with a named volume
Runs in: a folder with compose.yaml and Docker 27+ installed
name: shoplite # project name (default: the folder name)services: db: image: mysql:8.4 restart: unless-stopped ports: - "3307:3306" # host 3307 -> container 3306 environment: MYSQL_ROOT_PASSWORD: rootpass MYSQL_DATABASE: shoplite MYSQL_USER: shoplite MYSQL_PASSWORD: shoplitepass volumes: - mysql-data:/var/lib/mysqlvolumes: mysql-data:$ docker compose up -d [+] Running 3/3 ✔ Network shoplite_default Created 0.1s ✔ Volume "shoplite_mysql-data" Created 0.0s ✔ Container shoplite-db-1 Started 0.7s
What this code does
- Every flag of the
docker runcommand above has a key here; the file is easier to read, review and commit than a long command in a notes file. - Compose creates a network
shoplite_default, a volumeshoplite_mysql-dataand a containershoplite-db-1: all names start with the project name fromname:.
Example 2 · Turning docker run flags into Compose keys
import java.util.ArrayList;import java.util.List;
public class RunToComposeDemo { public static void main(String[] args) { String command = "docker run -d --name shoplite-db -p 3307:3306" + " -e MYSQL_DATABASE=shoplite -e MYSQL_USER=shoplite" + " -v mysql-data:/var/lib/mysql --restart unless-stopped mysql:8.4"; String[] parts = command.split(" ");
String name = ""; String restart = "no"; String image = parts[parts.length - 1]; List<String> ports = new ArrayList<>(); List<String> env = new ArrayList<>(); List<String> volumes = new ArrayList<>();
for (int i = 2; i < parts.length - 1; i++) { switch (parts[i]) { case "--name" -> name = parts[++i]; case "-p" -> ports.add(parts[++i]); case "-e" -> env.add(parts[++i]); case "-v" -> volumes.add(parts[++i]); case "--restart" -> restart = parts[++i]; default -> { } // -d is replaced by "docker compose up -d" } }
System.out.println("services:"); System.out.println(" " + name.replace("shoplite-", "") + ":"); System.out.println(" image: " + image); System.out.println(" restart: " + restart); System.out.println(" ports:"); for (String p : ports) { System.out.println(" - \"" + p + "\""); } System.out.println(" environment:"); for (String e : env) { String[] kv = e.split("=", 2); System.out.println(" " + kv[0] + ": " + kv[1]); } System.out.println(" volumes:"); for (String v : volumes) { System.out.println(" - " + v); } System.out.println("volumes:"); for (String v : volumes) { System.out.println(" " + v.split(":")[0] + ":"); } }}services:
db:
image: mysql:8.4
restart: unless-stopped
ports:
- "3307:3306"
environment:
MYSQL_DATABASE: shoplite
MYSQL_USER: shoplite
volumes:
- mysql-data:/var/lib/mysql
volumes:
mysql-data:What this code does
- Each flag maps to one key:
--namebecomes the service name,-paportsitem,-eanenvironmentpair,-vavolumesitem and--restarttherestartkey. The last word is the image. - The program also prints the top-level
volumes:block, because Compose needs every named volume declared there.-dhas no key: you choose detached mode when you rundocker compose up -d.
Name the file compose.yaml and keep it in the top folder of the project. Older projects use docker-compose.yml, which still works. Leave out the old version: "3.8" line: current Compose ignores it and warns that it is obsolete.
Type docker compose with a space. That is Compose v2, built into Docker Desktop and Docker 27+; the old hyphenated docker-compose program is no longer updated.
services: image vs build, ports, environment, volumes, restart
A service is one container definition in compose.yaml, such as db or api. Its name is the key under services:, and its settings say which image to run and how.
Each key under services: is a container you name. Below, db runs a ready image and api is built from ShopLite's own Dockerfile.
Example 3 · compose.yaml: the ShopLite API and its database
Runs in: the shoplite-api project folder with its Dockerfile and Docker 27+
name: shopliteservices: db: image: mysql:8.4 # ready image from Docker Hub restart: unless-stopped ports: - "3307:3306" environment: MYSQL_ROOT_PASSWORD: rootpass MYSQL_DATABASE: shoplite MYSQL_USER: shoplite MYSQL_PASSWORD: shoplitepass volumes: - mysql-data:/var/lib/mysql api: build: . # Dockerfile in this folder restart: on-failure ports: - "8080:8080" environment: SPRING_PROFILES_ACTIVE: dev DB_URL: jdbc:mysql://db:3306/shoplite DB_USER: shoplite DB_PASSWORD: shoplitepass JWT_SECRET: dev-only-secret-change-me-0123456789abcdefvolumes: mysql-data:$ docker compose up -d --build [+] Building 41.3s (17/17) FINISHED ... [+] Running 4/4 ✔ Service api Built 41.4s ✔ Network shoplite_default Created 0.1s ✔ Volume "shoplite_mysql-data" Created 0.0s ✔ Container shoplite-db-1 Started 0.6s ✔ Container shoplite-api-1 Started 0.9s
What this code does
dbusesimage:because MySQL is ready-made;apiusesbuild: ., so Compose builds the image from the Dockerfile of the Dockerising module before it starts the container.- The API reaches MySQL at
db:3306, the service name, notlocalhost. The Networking lesson explains why.--buildrebuilds the image so a code change is picked up.
A service needs either image: (a ready image from a registry, like mysql:8.4) or build: (build an image from a Dockerfile; build: . means the Dockerfile in this folder).
The other common keys map straight to docker run flags:
ports:is-p host:container, a list of"HOST:CONTAINER"strings.environment:is-e, written asKEY: valuepairs.volumes:is-v, eithervolume-name:/path/in/containeror./host/folder:/pathfor a bind mount.restart:is--restart:no(default),always,on-failureorunless-stopped.
Top-level volumes for named volumes
A named volume is storage that Docker manages and keeps when the container is removed. In Compose you declare it once in a top-level volumes: block and use it by name.
MySQL's tables must survive when its container is removed. Declare the volume once at the top level, then use it by name inside the service.
services: db: image: mysql:8.4 volumes: - mysql-data:/var/lib/mysql # named volume: MySQL data lives herevolumes: # top level, same indentation as services mysql-data: # empty = default local driverCompose adds the project name in front of the volume. With name: shoplite at the top of the file, the volume is really called shoplite_mysql-data, and docker volume ls shows that name.
If a service uses a volume that is not declared, Compose stops with service "db" refers to undefined volume mysql-data.
Fix the error
Fix the volume name
Compose refuses this file. Pick the replacement for the highlighted line.
The service uses mysql-data, but the top-level block declares something else.
Error
service "db" refers to undefined volume mysql-data: invalid compose project
docker compose up -d, ps, logs -f api, down vs down -v
A project is one running copy of a compose file. Compose names its containers, network and volumes after the project, and up and down act on the whole project at once.
Four commands cover daily work: up starts the whole stack, ps and logs show what happens, and down cleans up. Run them in the folder that holds compose.yaml.
Example 4 · up, ps, logs, down and down -v
Runs in: the shoplite-api project folder with Docker 27+
docker compose up -ddocker compose psdocker compose logs -f api # Ctrl+C stops following, the app keeps runningdocker compose down # containers + network removed, volume keptdocker volume lsdocker compose down -v # also deletes shoplite_mysql-datadocker volume ls$ docker compose ps NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS shoplite-api-1 shoplite-api "java -jar /app/app.…" api 15 seconds ago Up 14 seconds 0.0.0.0:8080->8080/tcp shoplite-db-1 mysql:8.4 "docker-entrypoint.s…" db 15 seconds ago Up 15 seconds 33060/tcp, 0.0.0.0:3307->3306/tcp $ docker compose logs -f api api-1 | Started ShopliteApiApplication in 6.912 seconds (process running for 7.6) $ docker compose down [+] Running 3/3 ✔ Container shoplite-api-1 Removed 0.4s ✔ Container shoplite-db-1 Removed 1.2s ✔ Network shoplite_default Removed 0.2s $ docker volume ls DRIVER VOLUME NAME local shoplite_mysql-data $ docker compose down -v [+] Running 1/1 ✔ Volume shoplite_mysql-data Removed 0.0s $ docker volume ls DRIVER VOLUME NAME
What this code does
- After plain
down,docker volume lsstill listsshoplite_mysql-data: the nextupfinds your tables and rows again. down -vremoves the volume too. Use it on purpose when you want a fresh database, never as a habit.
docker compose up -d creates the network, the volumes and the containers and starts them in the background (-d means detached). Run it again and only containers whose settings changed are recreated.
These commands do the rest:
docker compose pslists this project's containers with their status and ports.docker compose logs -f apifollows one service's logs; press Ctrl+C to stop following.docker compose downremoves the containers and the network but keeps named volumes, so the database survives.docker compose down -valso deletes the named volumes. Your MySQL data is gone.
Predict the output
Does the data survive?
The shoplite project is running, and the app has just added 15 products to MySQL.
Round 1 of 2
You stop the stack and start it again. How many products are in the database?
YAML pitfalls: indentation, quoting and yes/no
YAML is a text format where indentation shows structure. Compose files are YAML, so one wrong indent moves a key under the wrong parent.
Many broken Compose files are just small YAML slips. The snippet below shows the quoting habits that prevent most of them.
services: api: ports: - "8080:8080" # quoted: always a string environment: FEATURE_COUPONS: "yes" # quoted: stays the text yes LOG_JSON: "false" # quoted: stays the text falseExample 5 · Trap: a tab and a wrong indent
Runs in: a folder with compose.yaml and Docker 27+
services: db: image: mysql:8.4 ports: - "3307:3306" volumes: # wrong: indented under services - mysql-data:/var/lib/mysql$ docker compose config services.volumes must be a mapping (after moving volumes under db but forgetting the top-level block) $ docker compose config service "db" refers to undefined volume mysql-data: invalid compose project
What this code does
- With two spaces,
volumes:sits underservices:, so Compose thinks it is a service calledvolumesand rejects the list. It belongs four spaces in, underdb:. docker compose configchecks and prints the file without starting anything; run it after every edit. The exact wording of errors changes a little between Compose versions.
Use spaces only, never tabs, and the same number of spaces for keys at the same level (two spaces is the common style). Quote port mappings such as "8080:8080"; the Compose documentation itself recommends writing ports as strings.
Quote values like "yes", "no", "on", "off", "true" and "false" in environment:. YAML may read them as booleans, and Compose expects environment values to be strings, numbers or empty.
Find the bug
Find the YAML slip
Each snippet breaks the stack. Tap the wrong line.
Compose says: services.volumes must be a mapping.
Round 1 of 2Next step
Check your understanding
12 quick questions