Skip to lesson

A local development setup with Compose

You change ShopLite's code dozens of times an hour, and rebuilding an image for every change is slow. Compose can run only the database in a container, so your daily loop stays fast.

Two ways to work

The inner loop is the cycle you repeat many times an hour: edit the code, run it, check the result. A good development setup keeps this loop down to a few seconds.

The faster your edit-run-check loop, the more you learn per hour. Compare two ways to run ShopLite: the whole stack in Compose, or only MySQL in Compose with the app in your IDE.

Terminal
# way 1: whole stack, rebuild on every changedocker compose up -d --build# way 2: only MySQL in Docker, the app runs in the IDEdocker compose up -d db# IDE: run ShopliteApiApplication with DB_URL=jdbc:mysql://localhost:3307/shoplite

Example 1 · How much waiting each way costs in a day

DevLoopDemo.javaJava
public class DevLoopDemo {    record Setup(String name, int secondsPerChange) {}
    public static void main(String[] args) {        int changesPerDay = 60;            // small edits you want to try        Setup[] setups = {            new Setup("app in IDE, MySQL in Compose", 8),            new Setup("everything in Compose (--build)", 45)        };        for (Setup s : setups) {            int minutes = s.secondsPerChange() * changesPerDay / 60;            System.out.printf("%-33s %3d s per change, %3d min per day%n",                    s.name(), s.secondsPerChange(), minutes);        }        System.out.println("Before pushing: one full-stack run to check the image.");    }}
Output
app in IDE, MySQL in Compose        8 s per change,   8 min per day
everything in Compose (--build)    45 s per change,  45 min per day
Before pushing: one full-stack run to check the image.

What this code does

  • The numbers are assumptions for a mid-range laptop, not measurements; plug in your own. Waiting 45 seconds sixty times a day costs most of an hour.
  • That is why the inner loop (edit, run, check) uses the IDE, and the full stack is a check you run less often.

Everything in Compose means the API also runs as a container built from your Dockerfile. It is closest to production and needs nothing on your laptop except Docker, but every code change needs an image rebuild.

Only the database in Compose means MySQL runs in a container while you start ShopliteApiApplication from the IDE. You still get the exact MySQL 8.4 of production. Most developers use this way while coding and the first one before pushing.

Predict the output

Pick the setup

Way A runs the whole stack in Compose. Way B runs only MySQL in Compose and the app in the IDE.

Round 1 of 2

You are chasing a bug with breakpoints and many small edits. Which way fits?

# A: whole stack in Compose
docker compose up -d --build
# B: only MySQL, the app runs in the IDE
docker compose up -d db

spring-boot-docker-compose: Boot starts the database for you

spring-boot-docker-compose is a Spring Boot dependency that runs docker compose up when the app starts in development, waits for the containers, and builds the DataSource settings from them.

With one dependency, Boot starts MySQL for you and finds the connection details itself, so you set no DB_URL at all. The snippet adds the dependency and names the compose file.

XML
<!-- pom.xml: no version, Spring Boot manages it --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-docker-compose</artifactId>    <optional>true</optional></dependency># application-dev.yml: Boot starts only the database filespring:  docker:    compose:      file: compose.db.yaml      lifecycle-management: start-only   # leave MySQL running when the app stops

Example 2 · compose.db.yaml, compose.yaml and the Boot start-up log

Runs in: the shoplite-api project with spring-boot-docker-compose and Docker 27+

YAML
# compose.db.yaml: only MySQL (used by Spring Boot in the IDE)name: shopliteservices:  db:    image: mysql:8.4    ports:      - "3307:3306"    environment:      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD is required}      MYSQL_DATABASE: shoplite      MYSQL_USER: shoplite      MYSQL_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD is required}    volumes:      - mysql-data:/var/lib/mysql    healthcheck:      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u root -p$$MYSQL_ROOT_PASSWORD --silent"]      interval: 10s      retries: 10      start_period: 30svolumes:  mysql-data:# compose.yaml: the whole stackname: shoplite                 # same project as compose.db.yamlinclude:  - compose.db.yamlservices:  api:    build: .    ports:      - "8080:8080"    environment:      DB_URL: jdbc:mysql://db:3306/shoplite      DB_USER: shoplite      DB_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD is required}    depends_on:      db:        condition: service_healthy
Sample output
(IDE run with the dev profile, log prefix trimmed)
DockerComposeLifecycleManager : Using Docker Compose file /home/asha/shoplite-api/compose.db.yaml
DockerCli                     : Container shoplite-db-1  Creating
DockerCli                     : Container shoplite-db-1  Started
DockerCli                     : Container shoplite-db-1  Waiting
DockerCli                     : Container shoplite-db-1  Healthy
HikariDataSource              : HikariPool-1 - Start completed.
DbMigrate                     : Successfully applied 3 migrations to schema `shoplite`, now at version v2
ShopliteApiApplication        : Started ShopliteApiApplication in 24.318 seconds

What this code does

  • Starting the app in the IDE started MySQL, waited for the healthcheck, then built the DataSource from the container's variables and port; no DB_URL was set.
  • include: puts the database definition in one place: the IDE way uses compose.db.yaml alone, the full-stack way uses compose.yaml, which pulls it in. Both share the project name and the volume, so the data is the same.

For a mysql image Boot reads MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD and the published port. Mark the dependency <optional>true</optional> so it never ends up in the production jar.

It is skipped in tests by default (spring.docker.compose.skip.in-tests=true); tests use Testcontainers, the next module. Boot starts every service of the file it uses, so ShopLite keeps MySQL in compose.db.yaml, which the main compose.yaml pulls in with include:.

Tools under a profile: Adminer

A profile is a label on a Compose service. A service with profiles: [tools] starts only when you ask for that profile, and plain docker compose up skips it.

You want a database browser sometimes, not every day. Put Adminer under a profile, so it starts only when you ask for it.

Example 3 · Adminer only when you ask for it

Runs in: the shoplite-api project folder with Docker 27+

YAML
# added to compose.yaml  adminer:    image: adminer:5    profiles: [tools]          # not started by plain "docker compose up"    ports:      - "127.0.0.1:8081:8080"    environment:      ADMINER_DEFAULT_SERVER: db    depends_on:      - db
Sample output
$ docker compose up -d
 ✔ Container shoplite-db-1    Healthy   12.1s
 ✔ Container shoplite-api-1   Started   12.3s

$ docker compose --profile tools up -d
 ✔ Container shoplite-db-1       Running   0.0s
 ✔ Container shoplite-adminer-1  Started   0.4s
 ✔ Container shoplite-api-1      Running   0.0s

What this code does

  • Plain up starts only db and api; Adminer appears only with --profile tools. Setting COMPOSE_PROFILES=tools in your own .env turns it on for every command on your machine.
  • ADMINER_DEFAULT_SERVER: db fills the login form's server field with the service name. The port is bound to 127.0.0.1, so only your computer can open it.

Adminer is a one-page database browser that runs in a container; phpMyAdmin is a bigger alternative. Start it with docker compose --profile tools up -d, open http://localhost:8081, and log in with server db, user shoplite and your password.

Adminer runs inside the project network, so it uses the service name db, like the API does.

Fix the error

Fix the profile key

Compose rejects the file. Pick the replacement for the highlighted line.

Adminer should start only with --profile tools.

adminer:
image: adminer
ports:
- "127.0.0.1:8081:8080"
profile: tools

Error

validating compose.yaml: services.adminer additional properties 'profile' not allowed

compose.override.yaml for dev-only settings

compose.override.yaml is a second file that Compose merges into compose.yaml automatically when both sit in the same folder. Put settings there that only developers need.

A debug port and bind mounts help on your laptop but must not reach a server. Put them in compose.override.yaml, which Compose merges in by itself.

Example 4 · compose.override.yaml: debug port and a log folder

Runs in: the shoplite-api project folder with Docker 27+

YAML
# compose.override.yaml: merged automatically on developer machinesservices:  api:    environment:      SPRING_PROFILES_ACTIVE: dev      JAVA_TOOL_OPTIONS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005    ports:      - "127.0.0.1:5005:5005"   # added to 8080 from compose.yaml    volumes:      - ./logs:/app/logs        # bind mount: log files appear in your project folder
Sample output
$ docker compose config --format json | jq -c ".services.api.ports[] | {published, target}"
{"published":"8080","target":8080}
{"published":"5005","target":5005}

$ docker compose logs api | head -1
api-1  | Picked up JAVA_TOOL_OPTIONS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005

What this code does

  • The merged file has both ports: lists are combined, so 8080 from compose.yaml stays and 5005 is added. environment keys are merged the same way.
  • In IntelliJ, a Remote JVM Debug configuration on localhost:5005 attaches to the container. A server uses docker compose -f compose.yaml up -d, which ignores the override file.

Example 5 · The merge rules in plain Java

OverrideMergeDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class OverrideMergeDemo {    public static void main(String[] args) {        // compose.yaml        String image = "shoplite-api";        Map<String, String> env = new LinkedHashMap<>(Map.of("DB_USER", "shoplite"));        env.put("SPRING_PROFILES_ACTIVE", "prod");        List<String> ports = new ArrayList<>(List.of("8080:8080"));
        // compose.override.yaml        String overrideImage = "shoplite-api:dev";        Map<String, String> overrideEnv = Map.of("SPRING_PROFILES_ACTIVE", "dev");        List<String> overridePorts = List.of("127.0.0.1:5005:5005");
        image = overrideImage;        env.putAll(overrideEnv);        ports.addAll(overridePorts);
        System.out.println("image: " + image);        System.out.println("environment: " + env);        System.out.println("ports: " + ports);    }}
Output
image: shoplite-api:dev
environment: {DB_USER=shoplite, SPRING_PROFILES_ACTIVE=dev}
ports: [8080:8080, 127.0.0.1:5005:5005]

What this code does

  • Three kinds of value, three rules: the override's image replaces the base one, SPRING_PROFILES_ACTIVE is overwritten while DB_USER stays, and the debug port is added to the list.
  • This is a simplified model; the full rules are in the Compose documentation under merging. docker compose config always shows the real merged result.

Merging follows simple rules: single values (such as image) are replaced, environment is merged key by key, and lists such as ports are combined. A server or CI pipeline that must not get the dev settings names the file explicitly: docker compose -f compose.yaml up -d.

The debug port 5005 lets your IDE attach a debugger to the Java process inside the container, using the JVM's JDWP agent.

Predict the output

What does the merge give?

compose.yaml and compose.override.yaml sit in the same folder.

Round 1 of 3

After docker compose up -d, which ports does the api publish?

# compose.yaml
services:
api:
ports:
- "8080:8080"
# compose.override.yaml
services:
api:
ports:
- "127.0.0.1:5005:5005"
Publish the debug port only on your laptop: anyone who can reach a JDWP port can run code inside your app.

Rebuilding: up --build and watch

docker compose watch (Compose 2.22 or later) watches your files and rebuilds or updates a service automatically each time a file changes.

An image does not change when you edit src/. Compose can rebuild it for you, either when you ask or automatically as you save.

Example 6 · docker compose watch rebuilds on code changes

Runs in: the shoplite-api project folder with Docker Compose 2.22+

YAML
# in compose.yaml, under the api service    develop:      watch:        - action: rebuild          path: ./src        - action: rebuild          path: pom.xml
Sample output
$ docker compose watch
 ✔ Container shoplite-db-1   Healthy   11.8s
 ✔ Container shoplite-api-1  Started   12.0s
Watch enabled
(edit ProductService.java and save)
Rebuilding service(s) ["api"] after changes were detected...
[+] Building 9.7s (17/17) FINISHED
 ✔ Container shoplite-api-1  Recreated   0.6s
["api"] Successfully rebuilt

What this code does

  • Saving a file under src/ triggers a rebuild of only the api image and a recreate of only its container; MySQL and its data are untouched.
  • The rebuild took about 10 seconds because the dependency layers were cached. Without watch, run docker compose up -d --build after your changes.

docker compose up -d --build rebuilds the images whose source changed and recreates only those containers; MySQL keeps running.

Under a service's develop: watch: you list paths and an action. For a Java app the useful action is rebuild: when a file under src/ or pom.xml changes, Compose rebuilds the image and replaces the container. With the layer caching from the Dockerising module, a rebuild after a small change takes seconds, not minutes.

Find the bug

Find why the old code still runs

Tap the line that keeps the old behaviour.

You edited ProductController.java, but the API shows the old response.

Round 1 of 2

Next step

Check your understanding

11 quick questions