00:00

Docker Compose Support in Spring Boot

Last updated:

Docker Compose support in Spring Boot removes the most tedious part of local development: starting the database, cache and message broker your application needs, and copying their connection details into configuration. With the spring-boot-docker-compose module on the classpath, running the application starts the services in your compose.yaml, waits until they are ready, and connects to them automatically, including random ports and passwords.

This tutorial shows how the feature works, how to set it up with PostgreSQL and Redis for a product catalog, which settings control the container lifecycle, how to use it in tests, and how it compares with Testcontainers at development time.

1. What Is Docker Compose Support?

Docker Compose runs several containers defined in one YAML file, usually compose.yaml. Developers often run docker compose up before starting an application and copy ports and passwords into application.properties.

Spring Boot's Docker Compose support automates both steps. It is a development-time feature: it is meant for running the application from your IDE or with ./mvnw spring-boot:run, and it is excluded from the production JAR by default.

Analogy: Without it, you are a cook who must switch on every appliance and read the oven's dial before cooking. With it, the kitchen powers up the appliances when you walk in and tells you the temperatures; you just cook.

2. How It Works

How Spring Boot's Docker Compose support starts servicesWhen the application starts, Spring Boot finds compose.yaml in the working directory and runs docker compose up. It waits for the containers to be ready, reads the running containers' images, mapped ports and environment variables, and creates service connection beans for supported images such as PostgreSQL and Redis. Auto-configuration uses these connection details to configure the DataSource and Redis client. When the application stops, Spring Boot runs docker compose stop. Application starts (IDE or spring-boot:run) Find compose.yaml run docker compose up wait until ready Service connections from image name, mapped port and container env vars Auto-configuration DataSource, Redis client connect to the running containers On shutdown: docker compose stop (configurable)
Spring Boot starts the compose services, discovers their ports and credentials, and wires them into auto-configuration.

When the module is on the classpath, Spring Boot:

  1. Looks for compose.yaml (or other common Compose file names) in the working directory.
  2. Runs docker compose up, unless the services are already running.
  3. Creates service connection beans for each supported container, based on its image name.
  4. Runs docker compose stop when the application shuts down, if it started the services itself.

3. Adding the Dependency

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-docker-compose</artifactId>
    <optional>true</optional>
</dependency>

In Gradle, use the developmentOnly configuration: developmentOnly("org.springframework.boot:spring-boot-docker-compose"). Spring Initializr adds the dependency and a matching compose.yaml when you select "Docker Compose Support". Docker (or a compatible runtime such as Podman with Docker Compose) must be installed.

4. A Complete Example: PostgreSQL and Redis for a Catalog

4.1 The Compose File

compose.yaml
services:
  postgres:
    image: 'postgres:17'
    environment:
      - 'POSTGRES_DB=catalog'
      - 'POSTGRES_USER=catalog'
      - 'POSTGRES_PASSWORD=local-only-password'
    ports:
      - '5432'
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U catalog -d catalog']
      interval: 2s
      timeout: 3s
      retries: 15
  redis:
    image: 'redis:8'
    ports:
      - '6379'

Ports are listed without a host port ('5432' rather than '5432:5432'), so Docker maps them to random free ports. That avoids clashes with other projects; Spring Boot discovers the real port. The password is for local use only.

4.2 Dependencies

pom.xml (dependencies)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-docker-compose</artifactId>
    <optional>true</optional>
</dependency>

4.3 Application Code

src/main/resources/schema.sql
CREATE TABLE IF NOT EXISTS product (
    sku   VARCHAR(20) PRIMARY KEY,
    name  VARCHAR(100) NOT NULL,
    price NUMERIC(10, 2) NOT NULL
);
CatalogService.java
package com.javabytechie.shop.catalog;

import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;

@Service
public class CatalogService {

    private static final Logger log = LoggerFactory.getLogger(CatalogService.class);
    private final JdbcClient jdbc;
    private final StringRedisTemplate redis;

    public CatalogService(JdbcClient jdbc, StringRedisTemplate redis) {
        this.jdbc = jdbc;
        this.redis = redis;
    }

    public void add(Product product) {
        jdbc.sql("INSERT INTO product (sku, name, price) VALUES (:sku, :name, :price)")
            .param("sku", product.sku())
            .param("name", product.name())
            .param("price", product.price())
            .update();
        redis.opsForValue().increment("catalog:changes");
        log.info("Added {}", product.sku());
    }

    public List<Product> all() {
        return jdbc.sql("SELECT sku, name, price FROM product ORDER BY sku").query(Product.class).list();
    }

    public long changeCount() {
        String value = redis.opsForValue().get("catalog:changes");
        return value == null ? 0 : Long.parseLong(value);
    }

    public record Product(String sku, String name, BigDecimal price) {
    }
}
CatalogController.java
package com.javabytechie.shop.catalog;

import com.javabytechie.shop.catalog.CatalogService.Product;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/products")
public class CatalogController {

    private final CatalogService catalog;

    public CatalogController(CatalogService catalog) {
        this.catalog = catalog;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void add(@RequestBody Product product) {
        catalog.add(product);
    }

    @GetMapping
    public List<Product> all() {
        return catalog.all();
    }
}
application.properties
spring.application.name=catalog
spring.sql.init.mode=always

Notice what is not in the configuration: no spring.datasource.url, user or password, and no Redis host or port.

4.4 Run It

Terminal
./mvnw spring-boot:run
Console (shortened)
Using Docker Compose file /home/dev/catalog/compose.yaml
Container catalog-postgres-1  Started
Container catalog-redis-1  Started
Container catalog-postgres-1  Healthy
Started CatalogApplication in 6.84 seconds (process running for 7.12)
Terminal
curl -s -X POST localhost:8080/api/products -H "Content-Type: application/json" \
     -d '{"sku":"KB-100","name":"Mechanical keyboard","price":79.99}'
curl -s localhost:8080/api/products
Response
[{"sku":"KB-100","name":"Mechanical keyboard","price":79.99}]

Stop the application and the containers are stopped too; start it again and they are restarted with their data, because stop keeps the containers.

5. Service Connections

A service connection is a bean that tells auto-configuration how to reach a service. Connection details from a service connection take precedence over connection properties such as spring.datasource.url. Spring Boot recognizes containers by image name; supported images include PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, MongoDB, Redis, RabbitMQ, Kafka (Apache and Confluent images), Elasticsearch, Cassandra, ActiveMQ, Zipkin and the OpenTelemetry collector, among others. The full list is in the reference documentation.

If you use a custom image name, tell Spring Boot what it is with a label:

compose.yaml (custom image)
services:
  postgres:
    image: 'registry.example.com/shop/postgres-with-extensions:17'
    labels:
      org.springframework.boot.service-connection: postgres
    ports:
      - '5432'

To make Spring Boot ignore a service entirely, for example an admin UI, add the label org.springframework.boot.ignore: true.

6. Configuration Options

PropertyDefaultMeaning
spring.docker.compose.enabledtrueSwitch the feature off without removing the dependency
spring.docker.compose.fileauto-detectedPath to a Compose file with another name or location
spring.docker.compose.lifecycle-managementstart-and-stopnone, start-only or start-and-stop
spring.docker.compose.start.commandupup or start
spring.docker.compose.stop.commandstopstop keeps containers and data; down removes them
spring.docker.compose.profiles.activenoneDocker Compose profiles to activate
spring.docker.compose.skip.in-teststrueWhether to skip the feature when running tests

A popular setting during active development is start-only: containers keep running between application restarts, which makes restarts, including DevTools restarts, faster.

7. Waiting for Containers to Be Ready

A database container may be "started" before it accepts connections. The recommended way to wait is a healthcheck in the Compose file, as in the example; Spring Boot waits until Docker reports the container healthy. Without a health check, Spring Boot checks that the mapped TCP ports accept connections, which is a weaker signal. Waiting can be switched off per service with the label org.springframework.boot.readiness-check.tcp.disable: true, and the timeout is configurable with spring.docker.compose.readiness.timeout.

8. Docker Compose in Tests

By default the feature is skipped in tests, because each test run would otherwise start and stop containers. To use it in tests anyway, set spring.docker.compose.skip.in-tests=false (in Gradle, also use testAndDevelopmentOnly). For most integration tests, Testcontainers with @ServiceConnection is the better fit: each test controls its own containers in Java code, and CI does not depend on a Compose file.

9. Docker Compose vs Testcontainers at Development Time

AspectDocker Compose supportTestcontainers at development time
Where services are definedcompose.yamlJava @Bean methods in a test configuration
How you start the appNormal run from the IDE or spring-boot:runA separate test main class (SpringApplication.from(...))
Reuse by non-Java toolsYes, anyone can run docker compose upNo
Shared with integration testsUsually notYes, same container definitions
Best forTeams already using Compose, polyglot setupsTeams that want one container setup for tests and local runs

10. Common Problems

  • "Unable to start docker process": Docker is not running or not on the PATH of the process that starts the application, a common issue with IDEs started from a desktop shortcut.
  • Properties seem ignored: service connection details take precedence over spring.datasource.url and similar properties. Remove the service from Compose or label it ignored if you want your properties.
  • Fixed host ports clash: '5432:5432' fails if a local PostgreSQL already runs. Use container-only ports.
  • Feature active in a packaged JAR: it is excluded from repackaged archives by default; do not add it back for production.
  • Wrong Compose file picked: the working directory decides which file is found. Set spring.docker.compose.file in multi-module projects.

11. Best Practices

  • Keep compose.yaml next to the application and commit it, so every developer gets the same services.
  • Use container-only ports and let Spring Boot discover the mapped ports.
  • Add health checks for databases and brokers so startup waits until they are really ready.
  • Pin image versions that match production, such as postgres:17, rather than latest.
  • Use only local, throwaway credentials in the Compose file; real secrets never belong there.
  • Prefer Testcontainers for automated tests and keep Docker Compose for interactive development.

12. Summary

Docker Compose support in Spring Boot turns compose.yaml into a zero-configuration local environment. With spring-boot-docker-compose as an optional or development-only dependency, starting the application runs docker compose up, waits for health checks, creates service connections from the running containers and lets auto-configuration connect to PostgreSQL, Redis, Kafka and other services without any connection properties, then stops them on shutdown. Tune the lifecycle with spring.docker.compose.* properties, use labels for custom or ignored services, and use Testcontainers for automated tests.

13. References