Testcontainers with Spring Boot
An in-memory database passes tests that the real database fails: different SQL, different types, different locking. Testcontainers starts the real database, broker or cache in Docker for the length of the test, and Spring Boot connects the application to it with one annotation. This page explains how that wiring works, runs the parts that need no Docker, and shows the container setups for Spring Boot 4.
Contents
What Testcontainers does Finding Docker, and failing without it A database test with @ServiceConnection (not run) How a service connection overrides the properties Container lifecycle and the context cache (not run) Skipping container tests when Docker is missing The jdbc:tc: URL shortcut Running the application against containers (not run) Speed and reliability Choosing a setup
What Testcontainers does
An integration test needs the services the application talks to: a database, a message broker, a cache. Replacing PostgreSQL with H2 in tests is quick, but H2 accepts SQL that PostgreSQL rejects, has different types and locks differently, so a green test suite can still ship a broken query. Testcontainers removes the substitute. It is a Java library that talks to the Docker API, starts the real service from its official image before the tests, and removes the container afterwards.
A few mechanisms make this work reliably:
- Random mapped ports: the container's port, such as 5432, is mapped to a free port on the host. Tests ask the container object for the address, so parallel builds on one machine never clash.
- Wait strategies:
returns only when the service is ready, for example when the database log says it accepts connections, not just when the process has started.start() - The Ryuk container: Testcontainers starts a small helper container that removes every container of the test run when the JVM ends, even if it crashes, so failed builds do not leave databases running.
- Typed modules: classes such as
know their image's defaults, wait strategy and JDBC URL format;PostgreSQLContainer runs any other image.GenericContainer
Spring Boot then has to point the application at the container. There are several ways, from the oldest to the most automatic:
| Approach | Since | Best for |
|---|---|---|
jdbc:tc: | Testcontainers 1.x | Databases only, with no code change at all |
@DynamicPropertySource | Spring Framework 5.2.5 | Any property, including your own, from a container's address |
@ServiceConnection | Spring Boot 3.1 | Supported services: databases, Kafka, Redis, RabbitMQ, MongoDB and more |
Container @Bean@TestConfiguration | Spring Boot 3.1 | Containers shared by many test classes, with Spring managing start and stop |
SpringApplication.from(...).with(...) | Spring Boot 3.1 | Running the application locally against containers |
Spring Boot 4 manages Testcontainers 2. That release prefixed every module with testcontainers-org.testcontainers:postgresqlorg.testcontainers:testcontainers-postgresqlorg.testcontainers.postgresql
Docker is not available where this page was built, so no container could start here. The programs that are shown running use Testcontainers 1.21.4 and Spring Boot 4.1 and need no Docker: they show detection, skipping, URL parsing and the connection-details mechanism. Every example that needs a running container is marked as not run; it is written for Testcontainers 2 and checked against the Spring Boot 4 and Testcontainers reference documentation.
Finding Docker, and failing without it
The first thing Testcontainers does is find a Docker daemon. This program asks whether one is available and then tries to start a MariaDB container anyway, on a machine without Docker:
package demo.tc.check;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.MariaDBContainer;
import org.testcontainers.utility.DockerImageName;
public class DockerCheck {
public static void main(String[] args) {
DockerImageName image = DockerImageName.parse("mariadb:11.4");
System.out.println("Image: repository = " + image.getRepository()
+ ", tag = " + image.getVersionPart());
System.out.println("Docker available: "
+ DockerClientFactory.instance().isDockerAvailable());
try (MariaDBContainer<?> db = new MariaDBContainer<>(image)) {
System.out.println("Container created, not started yet: running = " + db.isRunning());
db.start();
System.out.println("JDBC URL: " + db.getJdbcUrl());
} catch (IllegalStateException e) {
System.out.println("start() failed: " + e.getMessage());
}
}
}
Image: repository = mariadb, tag = 11.4
ERROR o.t.d.DockerClientProviderStrategy - Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
UnixSocketClientProviderStrategy: failed with exception InvalidConfigurationException (Could not find unix domain socket). Root cause NoSuchFileException (/var/run/docker.sock)
DockerDesktopClientProviderStrategy: failed with exception NullPointerException (Cannot invoke "java.nio.file.Path.toString()" because the return value of "org.testcontainers.dockerclient.DockerDesktopClientProviderStrategy.getSocketPath()" is null)As no valid configuration was found, execution cannot continue.
See https://java.testcontainers.org/on_failure.html for more details.
Docker available: false
Container created, not started yet: running = false
start() failed: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration
splitDockerImageName.parse into the repository and the tag without contacting Docker. Spring Boot uses the repository name,mariadb:11.4 , to decide which kind of connection a container provides.mariadb tried each way of reaching Docker in turn. The Unix socketisDockerAvailable() did not exist and Docker Desktop's socket was not found, so it logged one/var/run/docker.sock listing both attempts and returnedERROR .false- Creating the container object worked:
only stores the configuration. Docker is needed atnew MariaDBContainer<>(image) , which threwstart() .IllegalStateException - The message says the earlier attempt failed and it "will not retry". Testcontainers remembers the failed detection for the rest of the JVM, so a suite without Docker fails fast instead of waiting on every test class.
The detection order can be overridden with the DOCKER_HOSTdocker.host~/.testcontainers.properties
A database test with @ServiceConnection (not run)
With the spring-boot-testcontainers
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-postgresql</artifactId>
<scope>test</scope>
</dependency>
Spring Boot's dependency management sets the Testcontainers version, so none is given. The test itself:
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;
@Testcontainers
@SpringBootTest
class OrderRepositoryIT {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");
@Autowired
OrderRepository orders;
@Test
void savesAndFindsAnOrder() {
orders.save(new Order("book", 2));
assertThat(orders.findBySku("book")).hasSize(1);
}
}
registers the JUnit extension, which starts every@Testcontainers field. A@Container field is started once before the first test of the class and stopped after the last.static makes Spring Boot create a@ServiceConnection bean from the container's URL, user name and password. Flyway or Liquibase, JPA andJdbcConnectionDetails then all use the container, with noJdbcTemplate properties.spring.datasource- The image tag is pinned.
changes under you, and a test suite should change its database version on purpose, in the same commit as production.postgres:latest
Spring Boot chooses the kind of connection from the container's type or its image name. It supports JDBC and R2DBC databases, Kafka, Redis, RabbitMQ, ActiveMQ and Artemis, MongoDB, Cassandra, Couchbase, Elasticsearch, Neo4j, Pulsar (deprecated in Spring Boot 4.2), LDAP and OpenTelemetry collectors. A GenericContainer@ServiceConnection(name = "redis")
How a service connection overrides the properties
@ServiceConnectionConnectionDetailsspring.*JdbcConnectionDetails
package demo.tc.details;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.autoconfigure.JdbcConnectionDetails;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
public class ConnectionDetailsWin {
@SpringBootApplication
static class ShopApplication {
// what @ServiceConnection registers for a database container, written by hand:
// the connection details of a running service, which override spring.datasource.*
@Bean
JdbcConnectionDetails testDatabase() {
return new JdbcConnectionDetails() {
@Override
public String getJdbcUrl() {
return "jdbc:h2:mem:containerdb";
}
@Override
public String getUsername() {
return "sa";
}
@Override
public String getPassword() {
return "";
}
};
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(ShopApplication.class);
try (var context = app.run("--spring.main.banner-mode=off",
"--logging.level.root=WARN",
"--spring.datasource.url=jdbc:postgresql://prod-db:5432/shop",
"--spring.datasource.username=shop_app")) {
System.out.println("spring.datasource.url property: "
+ context.getEnvironment().getProperty("spring.datasource.url"));
HikariDataSource pool = (HikariDataSource) context.getBean(DataSource.class);
System.out.println("URL the pool really uses : " + pool.getJdbcUrl());
System.out.println("user the pool really uses : " + pool.getUsername());
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("query answered by : "
+ jdbc.queryForObject("SELECT DATABASE()", String.class));
}
}
}
spring.datasource.url property: jdbc:postgresql://prod-db:5432/shop
URL the pool really uses : jdbc:h2:mem:containerdb
user the pool really uses : sa
query answered by : CONTAINERDB
- The
property still saidspring.datasource.url ; nothing changed it.jdbc:postgresql://prod-db:5432/shop - The Hikari pool was built from the connection details instead: URL
and userjdbc:h2:mem:containerdb . The property's user name,sa , was ignored too.shop_app - The query ran on the database named
, so the application really talked to the database from the details. There was no attempt to reachCONTAINERDB .prod-db
With a container, Spring Boot's JdbcContainerConnectionDetailsFactory@ServiceConnection
Container lifecycle and the context cache (not run)
The JUnit extension stops a static container after its test class. The Spring test framework, though, caches the application context and hands it to the next test class with the same configuration. That context still holds a connection pool pointing at the stopped container's port, and the next class fails with connection errors. Spring Boot's documentation warns about exactly this. There are two reliable designs.
The first is to let Spring manage the container as a bean. It is then started before all other beans, stopped after them, and lives exactly as long as the cached context:
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
@Bean
@ServiceConnection
PostgreSQLContainer postgres() {
return new PostgreSQLContainer("postgres:17-alpine");
}
@Bean
@ServiceConnection
KafkaContainer kafka() {
return new KafkaContainer("apache/kafka-native:3.8.0");
}
}
@SpringBootTest
@Import(ContainersConfig.class)
class CheckoutIT {
// every test class that imports ContainersConfig shares one context and one set of containers
}
The second is a singleton container: a static field in a base class, started once in a static initializer and never stopped by the tests, so that Ryuk removes it when the JVM ends:
abstract class AbstractIntegrationTest {
@ServiceConnection
static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
static {
POSTGRES.start();
}
}
Both give one database for the whole test run instead of one per class, which saves a container start for every class after the first. The cost is shared state. Tests must clean up what they write, or run in a rolled-back transaction, as the
@ImportTestcontainers(MyContainers.class)@Container
Skipping container tests when Docker is missing
A developer without Docker, or a CI job that only runs unit tests, should not see every integration test fail with connection errors. The disabledWithoutDocker@DynamicPropertySource
package demo.tc.skip;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
public class SkipWithoutDocker {
@SpringBootApplication
static class ShopApplication {
}
@Testcontainers(disabledWithoutDocker = true)
@SpringBootTest(properties = "spring.main.banner-mode=off")
static class OrderRepositoryIT {
@Container
static MariaDBContainer<?> db = new MariaDBContainer<>("mariadb:11.4");
@DynamicPropertySource
static void datasource(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", db::getJdbcUrl);
registry.add("spring.datasource.username", db::getUsername);
registry.add("spring.datasource.password", db::getPassword);
}
@Test
void savesAnOrder() {
assertThat(db.isRunning()).isTrue();
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(OrderRepositoryIT.class))
.build(),
new TestExecutionListener() {
@Override
public void executionSkipped(TestIdentifier id, String reason) {
System.out.println(id.getDisplayName() + ": SKIPPED (" + reason + ")");
}
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
});
}
}
ERROR o.t.d.DockerClientProviderStrategy - Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
UnixSocketClientProviderStrategy: failed with exception InvalidConfigurationException (Could not find unix domain socket). Root cause NoSuchFileException (/var/run/docker.sock)
DockerDesktopClientProviderStrategy: failed with exception NullPointerException (Cannot invoke "java.nio.file.Path.toString()" because the return value of "org.testcontainers.dockerclient.DockerDesktopClientProviderStrategy.getSocketPath()" is null)As no valid configuration was found, execution cannot continue.
See https://java.testcontainers.org/on_failure.html for more details.
SkipWithoutDocker$OrderRepositoryIT: SKIPPED (disabledWithoutDocker is true and Docker is not available)
JUnit Jupiter: SUCCESSFUL
- The extension checked for Docker before the class ran, logged the same detection error as before, and reported the whole class as skipped with the reason
.disabledWithoutDocker is true and Docker is not available - No application context was started: the
method and its suppliers never ran, so@DynamicPropertySource was never called on a container that had not started.getJdbcUrl() - The run as a whole succeeded. The Testcontainers 1.x JUnit extension used here also worked unchanged on JUnit 6.
A skip is easy to miss, so use the attribute for local convenience, and make sure the CI build that matters has Docker and fails if the tests do not run. Another common split is to name integration tests *IT
The program also shows the @DynamicPropertySourcepayments.base-url@ServiceConnection
The jdbc:tc: URL shortcut
For databases, Testcontainers also ships a JDBC driver that starts a container when the first connection is opened. A test only changes its URL, for example with spring.datasource.url=jdbc:tc:mariadb:11.4:///shop
package demo.tc.url;
import org.testcontainers.jdbc.ConnectionUrl;
public class JdbcUrlParts {
public static void main(String[] args) {
String url = "jdbc:tc:mariadb:11.4:///shop"
+ "?TC_INITSCRIPT=db/schema.sql&TC_DAEMON=true&useSSL=false";
ConnectionUrl parsed = ConnectionUrl.newInstance(url);
System.out.println("URL : " + url);
System.out.println("database type: " + parsed.getDatabaseType());
System.out.println("image tag : " + parsed.getImageTag().orElse("(default)"));
System.out.println("host and db : " + parsed.getDbHostString());
System.out.println("init script : " + parsed.getInitScriptPath().orElse("(none)"));
System.out.println("daemon : " + parsed.isInDaemonMode());
System.out.println("TC options : " + parsed.getContainerParameters());
System.out.println("driver query : " + parsed.getQueryParameters());
}
}
URL : jdbc:tc:mariadb:11.4:///shop?TC_INITSCRIPT=db/schema.sql&TC_DAEMON=true&useSSL=false
database type: mariadb
image tag : 11.4
host and db : /shop
init script : db/schema.sql
daemon : true
TC options : {TC_INITSCRIPT=db/schema.sql, TC_DAEMON=true}
driver query : {useSSL=false}
- The database type
chooses the container module, and the tagmariadb the image version.11.4 - The host part,
, is kept but not used: Testcontainers' documentation says the host, port and database name in these URLs are ignored, because the container supplies its own./shop - Parameters that start with
are options for Testcontainers.TC_ runs an SQL script from the classpath once the database is up, andTC_INITSCRIPT keeps the container running after the last connection closes; without it the container stops as soon as the pool closes all its connections.TC_DAEMON=true - Other parameters, here
, are passed on to the real JDBC driver.useSSL=false
The URL form is the least code, but it only covers JDBC, the container is not visible to the test, and its lifetime is tied to connections rather than to the test context. Prefer @ServiceConnection
Running the application against containers (not run)
The same container configuration can start the real application for local development, with no database installed. A class in src/test/javamain
public class TestShopApplication {
public static void main(String[] args) {
SpringApplication.from(ShopApplication::main)
.with(ContainersConfig.class)
.run(args);
}
}
- Run it from the IDE like any
method, or withmain or./mvnw spring-boot:test-run . Spring Boot starts the containers, connects the application through the service connections, and stops them on shutdown../gradlew bootTestRun - With DevTools, annotate the container beans with
as well, so that a restart after a code change keeps the database and its data instead of starting a fresh one.@RestartScope - The alternative is Docker Compose support: with
on the classpath, Spring Boot runsspring-boot-docker-compose for adocker compose up next to the application and creates service connections from it. It is skipped in tests by default.compose.yml
Speed and reliability
- Start containers once: one container per class, or worse per method, multiplies start-up time. Container beans or a singleton container give one per test run.
- Keep the context cache working: every distinct test configuration starts its own context, and with container beans, its own containers too. The
advanced testing page shows how to keep the number of configurations small. - Reuse between runs:
on a container, together withwithReuse(true) intestcontainers.reuse.enable=true , keeps the container running after the JVM ends, and the next run attaches to it. It is meant for local development, not CI.~/.testcontainers.properties - Pin and pre-pull images: a pinned tag gives repeatable results, and a CI cache of the images avoids a download on every build.
- Do not disable Ryuk casually:
is sometimes needed on locked-down CI systems, but then nothing removes containers left behind by a crashed build.TESTCONTAINERS_RYUK_DISABLED=true
Choosing a setup
| Situation | Setup |
|---|---|
| One test class needs a database | @Testcontainers@Container @ServiceConnection |
| Many test classes need the same services | Container @Bean@TestConfiguration |
| Your own property must point at a container | @DynamicPropertySource |
| A service Spring Boot does not recognise | GenericContainer@ServiceConnection(name = ...)@DynamicPropertySource |
| Changing only the JDBC URL in an existing suite | jdbc:tc: |
| Developers without Docker | @Testcontainers(disabledWithoutDocker = true) |
| Running the application locally | SpringApplication.from(...).with(...) |
Testcontainers is for the tests where the real service matters: queries, migrations, transactions, message delivery. Plain unit tests and slices, covered on the