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.

CsCode.ioUpdated
Share

Contents

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: start() returns only when the service is ready, for example when the database log says it accepts connections, not just when the process has started.
  • 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 PostgreSQLContainer know their image's defaults, wait strategy and JDBC URL format; GenericContainer runs any other image.

Spring Boot then has to point the application at the container. There are several ways, from the oldest to the most automatic:

Ways to connect a Spring Boot test to a container
ApproachSinceBest for
jdbc:tc: JDBC URLTestcontainers 1.xDatabases only, with no code change at all
@DynamicPropertySourceSpring Framework 5.2.5Any property, including your own, from a container's address
@ServiceConnection on a container fieldSpring Boot 3.1Supported services: databases, Kafka, Redis, RabbitMQ, MongoDB and more
Container @Bean in a @TestConfigurationSpring Boot 3.1Containers shared by many test classes, with Spring managing start and stop
SpringApplication.from(...).with(...)Spring Boot 3.1Running the application locally against containers

Spring Boot 4 manages Testcontainers 2. That release prefixed every module with testcontainers-, so org.testcontainers:postgresql became org.testcontainers:testcontainers-postgresql. It also moved the container classes to a package per module, such as org.testcontainers.postgresql, dropped the constructors without an image name, and removed JUnit 4 support.

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:

Java
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());
        }
    }
}
Output
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
  • DockerImageName.parse split mariadb:11.4 into the repository and the tag without contacting Docker. Spring Boot uses the repository name, mariadb, to decide which kind of connection a container provides.
  • isDockerAvailable() tried each way of reaching Docker in turn. The Unix socket /var/run/docker.sock did not exist and Docker Desktop's socket was not found, so it logged one ERROR listing both attempts and returned false.
  • Creating the container object worked: new MariaDBContainer<>(image) only stores the configuration. Docker is needed at start(), which threw 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_HOST environment variable, or with a docker.host entry in ~/.testcontainers.properties. That is how Testcontainers works with Podman, Colima or a remote daemon. On a CI runner, Docker must be reachable from the build container, which usually means mounting the socket or using a runner image that provides it.

A database test with @ServiceConnection (not run)

With the spring-boot-testcontainers module, one annotation on the container field connects the application to it. These are the test dependencies for a JPA application on PostgreSQL:

XML
<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:

Java
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);
    }
}
  • @Testcontainers registers the JUnit extension, which starts every @Container field. A static field is started once before the first test of the class and stopped after the last.
  • @ServiceConnection makes Spring Boot create a JdbcConnectionDetails bean from the container's URL, user name and password. Flyway or Liquibase, JPA and JdbcTemplate then all use the container, with no spring.datasource properties.
  • The image tag is pinned. postgres:latest changes under you, and a test suite should change its database version on purpose, in the same commit as production.

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 has no type to go on, so it needs a hint: @ServiceConnection(name = "redis").

How a service connection overrides the properties

@ServiceConnection does not set properties. It registers a ConnectionDetails bean, and Spring Boot's auto-configuration prefers such a bean to the matching spring.* properties. The mechanism needs no Docker, so this program registers a JdbcConnectionDetails by hand, pointing at an H2 database, while the properties point at a production PostgreSQL server:

Java
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));
        }
    }
}
Output
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 spring.datasource.url property still said jdbc:postgresql://prod-db:5432/shop; nothing changed it.
  • The Hikari pool was built from the connection details instead: URL jdbc:h2:mem:containerdb and user sa. The property's user name, shop_app, was ignored too.
  • The query ran on the database named CONTAINERDB, so the application really talked to the database from the details. There was no attempt to reach prod-db.

With a container, Spring Boot's JdbcContainerConnectionDetailsFactory builds the same kind of bean from the running container. This is also why a test with @ServiceConnection cannot reach the production database by accident through a forgotten property: the connection details win.

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:

Java
@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:

Java
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 advanced testing page shows. With container beans, Spring Boot also guarantees the shutdown order, so beans that use the database are closed before the database stops; with containers managed by the JUnit extension there is no such guarantee.

@ImportTestcontainers(MyContainers.class) is a third form: it imports the static @Container fields of an interface or class into a test configuration, which suits teams that already keep their containers in such an interface.

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 attribute turns that into a skip. This test class, with a container and a @DynamicPropertySource method, runs on the machine without Docker:

Java
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));
                    }
                });
    }
}
Output
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 @DynamicPropertySource method and its suppliers never ran, so getJdbcUrl() was never called on a container that had not started.
  • 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 and run them with the Maven Failsafe plugin in a separate phase.

The program also shows the @DynamicPropertySource form, which still has a place next to service connections. Use it for properties Spring Boot does not know, such as payments.base-url for a WireMock or mock-server container, or when a container type is not supported by @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. This program parses such a URL with the class the driver uses, which needs no Docker:

Java
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());
    }
}
Output
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 mariadb chooses the container module, and the tag 11.4 the image version.
  • The host part, /shop, 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.
  • Parameters that start with TC_ are options for Testcontainers. TC_INITSCRIPT runs an SQL script from the classpath once the database is up, and TC_DAEMON=true keeps the container running after the last connection closes; without it the container stops as soon as the pool closes all its connections.
  • Other parameters, here useSSL=false, are passed on to the real JDBC driver.

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 in new code.

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/java launches the application's own main method with the test configuration added:

Java
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 main method, or with ./mvnw spring-boot:test-run or ./gradlew bootTestRun. Spring Boot starts the containers, connects the application through the service connections, and stops them on shutdown.
  • With DevTools, annotate the container beans with @RestartScope as well, so that a restart after a code change keeps the database and its data instead of starting a fresh one.
  • The alternative is Docker Compose support: with spring-boot-docker-compose on the classpath, Spring Boot runs docker compose up for a compose.yml next to the application and creates service connections from it. It is skipped in tests by default.

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: withReuse(true) on a container, together with testcontainers.reuse.enable=true in ~/.testcontainers.properties, keeps the container running after the JVM ends, and the next run attaches to it. It is meant for local development, not CI.
  • 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: TESTCONTAINERS_RYUK_DISABLED=true is sometimes needed on locked-down CI systems, but then nothing removes containers left behind by a crashed build.

Choosing a setup

Testcontainers setups for common situations
SituationSetup
One test class needs a database@Testcontainers with a static @Container @ServiceConnection field
Many test classes need the same servicesContainer @Bean methods in a shared @TestConfiguration, or a singleton container
Your own property must point at a container@DynamicPropertySource
A service Spring Boot does not recogniseGenericContainer with @ServiceConnection(name = ...), or @DynamicPropertySource
Changing only the JDBC URL in an existing suitejdbc:tc: URL
Developers without Docker@Testcontainers(disabledWithoutDocker = true), with Docker required on CI
Running the application locallySpringApplication.from(...).with(...), or Docker Compose support

Testcontainers is for the tests where the real service matters: queries, migrations, transactions, message delivery. Plain unit tests and slices, covered on the Spring Boot testing page, stay faster for everything else. For the database code these tests exercise, see Spring Data JPA and Flyway migrations.