Docker Compose Support in Spring Boot
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.
2. How It Works
When the module is on the classpath, Spring Boot:
- Looks for
compose.yaml(or other common Compose file names) in the working directory. - Runs
docker compose up, unless the services are already running. - Creates service connection beans for each supported container, based on its image name.
- Runs
docker compose stopwhen the application shuts down, if it started the services itself.
3. Adding the Dependency
<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
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
<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
CREATE TABLE IF NOT EXISTS product (
sku VARCHAR(20) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) NOT NULL
);
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) {
}
}
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();
}
}
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
./mvnw spring-boot:run
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)
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
[{"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:
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
| Property | Default | Meaning |
|---|---|---|
spring.docker.compose.enabled | true | Switch the feature off without removing the dependency |
spring.docker.compose.file | auto-detected | Path to a Compose file with another name or location |
spring.docker.compose.lifecycle-management | start-and-stop | none, start-only or start-and-stop |
spring.docker.compose.start.command | up | up or start |
spring.docker.compose.stop.command | stop | stop keeps containers and data; down removes them |
spring.docker.compose.profiles.active | none | Docker Compose profiles to activate |
spring.docker.compose.skip.in-tests | true | Whether 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
| Aspect | Docker Compose support | Testcontainers at development time |
|---|---|---|
| Where services are defined | compose.yaml | Java @Bean methods in a test configuration |
| How you start the app | Normal run from the IDE or spring-boot:run | A separate test main class (SpringApplication.from(...)) |
| Reuse by non-Java tools | Yes, anyone can run docker compose up | No |
| Shared with integration tests | Usually not | Yes, same container definitions |
| Best for | Teams already using Compose, polyglot setups | Teams 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
PATHof 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.urland 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.filein multi-module projects.
11. Best Practices
- Keep
compose.yamlnext 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 thanlatest. - 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
Docker Compose Support in Spring Boot Interview Questions and Answers
Common interview questions on Docker Compose Support in Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Q. How does Spring Boot know which containers in compose.yaml it can connect to?
Answer: It looks at each running container's image name, such as postgres or redis, and creates a service connection for images it supports, reading the mapped port and settings such as credentials from the container's environment. For a custom image name, add the label org.springframework.boot.service-connection with the service type; to skip a container, add org.springframework.boot.ignore: true.
Q. What is a service connection, and how does it relate to properties such as spring.datasource.url?
Answer: A service connection is a bean of a ConnectionDetails type that describes how to reach a service: host, mapped port, credentials and similar. Docker Compose support and Testcontainers' @ServiceConnection both create them. When present, their details take precedence over the corresponding connection properties, which is why a spring.datasource.url can appear to be ignored.
Q. Why list container ports without a host port in compose.yaml?
Answer: A mapping such as '5432' lets Docker choose a random free host port, so the project never clashes with a local database or another project's containers. Spring Boot reads the actual mapped port from Docker and configures the connection with it. Fixed mappings like '5432:5432' fail whenever that port is already in use.
Q. What is the difference between stop and down for spring.docker.compose.stop.command?
Answer: stop, the default, stops the containers but keeps them, so a database keeps its data and the next start is quick. down stops and removes the containers, so the next start begins from a clean state unless data lives in named volumes. Use down when you want a fresh environment for every run.
Q. Restarting the application takes long because the database container restarts every time. How do you speed this up?
Answer: Set spring.docker.compose.lifecycle-management=start-only, so containers are started once and left running between application restarts; Spring Boot reuses running services and only creates the connection beans. Combined with DevTools restarts this makes the edit-run loop much faster. Stop the containers yourself with docker compose stop when you are done.