Practice: Docker Compose
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most broken Compose setups fail for the same few reasons, and each one has a short fix. This optional checkpoint lets you practise spotting them on ShopLite's stack, the way you would on the job.
Five bugs in one compose file
Read a compose file in this order: valid YAML, declared volumes, service names in URLs, a healthy database before the API, and no secrets in the file. The file below breaks all five.
Example 1 · The broken file and what Compose says
Runs in: the shoplite-api project folder with Docker 27+
name: shopliteservices: db: image: mysql:8.4 environment: MYSQL_ROOT_PASSWORD: Shop@2024 # bug 5: real password in a committed file MYSQL_DATABASE: shoplite volumes: - mysql-data:/var/lib/mysql # bug 3: volume never declared api: build: . ports: - "8080:8080" depends_on: - db # bug 4: no healthcheck, no condition environment: DB_URL: jdbc:mysql://localhost:3306/shoplite # bug 1 + bug 2: localhost, wrong indent DB_USER: root$ docker compose config --quiet services.api additional properties 'DB_URL', 'DB_USER' not allowed (after fixing the indent) $ docker compose config --quiet service "db" refers to undefined volume mysql-data: invalid compose project
What this code does
- Only bugs 2 and 3 stop
config; the error wording varies a little by Compose version. Bugs 1, 4 and 5 pass validation and fail later, at run time or in a security review. - With the indent wrong,
DB_URLandDB_USERbecome keys of the service itself, which Compose rejects as unknown properties.
Example 2 · The fixed file
Runs in: the shoplite-api project folder with a .env file and Docker 27+
name: shopliteservices: db: image: mysql:8.4 environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD is required} # fix 5 MYSQL_DATABASE: shoplite MYSQL_USER: shoplite MYSQL_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD is required} volumes: - mysql-data:/var/lib/mysql healthcheck: # fix 4 test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u root -p$$MYSQL_ROOT_PASSWORD --silent"] interval: 10s timeout: 5s retries: 10 start_period: 30s api: build: . restart: on-failure ports: - "8080:8080" depends_on: db: condition: service_healthy # fix 4 environment: # fix 2 DB_URL: jdbc:mysql://db:3306/shoplite # fix 1 DB_USER: shoplite DB_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD is required}volumes: # fix 3 mysql-data:$ docker compose up -d ✔ Container shoplite-db-1 Healthy 20.4s ✔ Container shoplite-api-1 Started 20.6s
What this code does
- The API now uses its own database user instead of root, reads the password from
.env, and connects to the service namedbon the container port. - The healthcheck plus
condition: service_healthyremoves the start-up race;restart: on-failurecovers later crashes.
docker compose config catches the first two at once. The other three only show up when the stack runs, which is why it pays to look for them on purpose.
Find the bug
Spot the bug
Each snippet hides one of the five bugs. Tap the wrong line.
The API cannot reach MySQL.
Round 1 of 3From docker run commands to one compose.yaml
Every docker run flag has a Compose key, and a few things simply disappear. Look at the three commands below, then at the one file that replaces them.
Example 3 · Three docker run commands become one file
Runs in: the shoplite-api project folder with Docker 27+
# Before:# docker network create shopnet# docker run -d --name shop-db --network shopnet -e MYSQL_ROOT_PASSWORD=... -e MYSQL_DATABASE=shoplite -v shopdata:/var/lib/mysql mysql:8.4# docker run -d --name shop-api --network shopnet -p 8080:8080 -e DB_URL=jdbc:mysql://shop-db:3306/shoplite shoplite-api:1.0# docker run -d --name shop-adminer --network shopnet -p 8081:8080 adminer:5name: shopliteservices: db: image: mysql:8.4 environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD is required} MYSQL_DATABASE: shoplite volumes: - shopdata:/var/lib/mysql api: image: shoplite-api:1.0 ports: - "8080:8080" environment: DB_URL: jdbc:mysql://db:3306/shoplite # container name shop-db -> service name db adminer: image: adminer:5 profiles: [tools] ports: - "127.0.0.1:8081:8080"volumes: shopdata:$ docker compose --profile tools up -d ✔ Network shoplite_default Created 0.1s ✔ Volume "shoplite_shopdata" Created 0.0s ✔ Container shoplite-db-1 Started 0.6s ✔ Container shoplite-api-1 Started 0.7s ✔ Container shoplite-adminer-1 Started 0.7s
What this code does
docker network createand every--networkflag vanish: Compose makesshoplite_defaultand joins all services to it.- The URL's host changes from the container name
shop-dbto the service namedb. A new volumeshoplite_shopdatais created, so copy data from the oldshopdatavolume if you need it.
--name becomes the service name, -p goes to ports, -e to environment, -v to volumes (plus a top-level declaration for named volumes) and --restart to restart. --network disappears because Compose creates the project network itself.
When you convert, also replace container names and IPs in URLs with service names, and move passwords to .env.
Reading ps and logs: why the api keeps restarting
A STATUS of Restarting (1) 5 seconds ago means the main process keeps exiting with code 1. docker compose ps tells you that it happens; docker compose logs api tells you why.
Example 4 · A restarting API: ps, then logs
Runs in: the shoplite-api project folder with Docker 27+
docker compose ps --format "table {{.Service}}\t{{.Status}}"docker compose logs --tail 6 apidocker compose exec db mysql -u shoplite -p -e "SELECT 1" # does the user work at all?$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE STATUS
api Restarting (1) 4 seconds ago
db Up 3 minutes (healthy)
$ docker compose logs --tail 6 api
api-1 | HikariPool-1 - Exception during pool initialization.
api-1 | java.sql.SQLException: Access denied for user 'shoplite'@'172.18.0.3' (using password: YES)
api-1 | Application run failed
api-1 | ...
api-1 | Caused by: java.sql.SQLException: Access denied for user 'shoplite'@'172.18.0.3' (using password: YES)
api-1 | api-1 exited with code 1What this code does
dbis healthy and the error is Access denied, not Connection refused, so the network is fine and the password is wrong. A common cause:MYSQL_PASSWORDwas changed in.env, but the old volume still has the user with the first password, because init variables apply only to an empty volume.- Fix it by changing the password inside MySQL (
ALTER USER) or, on a dev machine, bydocker compose down -vand starting again with an empty volume.
Read the logs from the bottom up to the first Caused by:. For a Spring Boot API the usual causes are a wrong database address (Connection refused or UnknownHostException), a wrong password (Access denied), a missing required setting, or a database that was not ready yet.
Predict the output
What does the log say?
The api is restarting. Read the last log lines and pick the cause.
Round 1 of 3
Which cause fits this log line?
ports or expose for each service
Ask one question per service: does anything outside Docker need to connect to it? The API: yes. MySQL on a laptop: maybe, for Workbench. MySQL on a server: no. Adminer: only you.
Example 5 · Deciding ports for each service
import java.util.List;
public class PortsDecisionDemo { record Service(String name, int port, boolean neededOutsideDocker, boolean onlyYou) {}
static String decide(Service s, boolean onServer) { if (!s.neededOutsideDocker() || (onServer && s.onlyYou())) { return "no ports (network only, " + s.name() + ":" + s.port() + ")"; } if (s.onlyYou()) { return "ports: \"127.0.0.1:" + (s.port() == 3306 ? 3307 : 8081) + ":" + s.port() + "\""; } return "ports: \"" + s.port() + ":" + s.port() + "\""; }
public static void main(String[] args) { List<Service> services = List.of( new Service("api", 8080, true, false), new Service("db", 3306, true, true), new Service("adminer", 8080, true, true), new Service("mailer", 8025, false, false)); for (boolean onServer : new boolean[] {false, true}) { System.out.println(onServer ? "On a server:" : "On your laptop:"); for (Service s : services) { System.out.printf(" %-8s %s%n", s.name(), decide(s, onServer)); } } }}On your laptop: api ports: "8080:8080" db ports: "127.0.0.1:3307:3306" adminer ports: "127.0.0.1:8081:8080" mailer no ports (network only, mailer:8025) On a server: api ports: "8080:8080" db no ports (network only, db:3306) adminer no ports (network only, adminer:8080) mailer no ports (network only, mailer:8025)
What this code does
- Only the API is published for everyone. Tools that only you use are bound to
127.0.0.1on a laptop and not published on a server. - A service that only other containers use, like the mailer, needs no
portsanywhere; the others reach it byname:port.
Anything that only other containers use needs no ports at all; expose is optional documentation. The Java model applies the same questions to four services.
Interview drill: finding each other and start-up order
Two questions come up in almost every Docker interview for a backend role. Practise saying each answer aloud in about 60 seconds.
A strong answer covers these points:
- How do containers find each other? One project network, Docker DNS resolves service names to current IPs, so the API uses
db:3306;localhostis the container itself. - How do you control start-up order?
depends_onalone orders start-up only; a healthcheck on the database pluscondition: service_healthywaits for readiness; the app still retries and restarts on failure.
Finish up
Mark complete & continue
Next: Project: ShopLite stack with one command