Testcontainers and database lifecycles

Why Apache Ant remains relevant in 2025, excelling in simplicity, flexibility, and niche use cases compared to Maven, Gradle, SBT, Buildr, and Bazel.

The deadly Spring Testcontainer footgun

An integration test that touches the database needs a real database - real PostgreSQL - but it must not be the developer's database, and it must not make the suite so slow that nobody runs it.

Those pulls fight each other. The cheap answer (an in-memory database) is fast and not real. The real answer (a Postgres) is heavy. Testcontainers is the modern reconciliation: a real Postgres, started on demand, thrown away after.

The interesting part is not "use Testcontainers" - everyone does that now. The interesting part is the lifecycle: when the container starts and stops, and what that means for Spring's context cache.

The trap in the official docs

Spring Boot's docs and the Testcontainers JUnit 5 guide both show code like this:

@Testcontainers
@SpringBootTest
class MyTests {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres =
            new PostgreSQLContainer<>("postgres:18-alpine");

    @Test
    void works() { ... }
}

This code is good. For one self-contained test class, it is exactly right. Here is what it does. The @Testcontainers extension sees @Container. It starts the container before the class's tests run. It stops the container after the class. Then @ServiceConnection hands the URL, username, and password to Spring Boot. So you write no @DynamicPropertySource and no properties file.

The trouble is the phrase after the class.

Why it hurts

Spring's test framework caches the ApplicationContext across test classes. As long as two classes describe the same configuration, they share one context - and, with @ServiceConnection, one datasource, pointing at one container.

But JUnit's @Testcontainers extension owns the container's lifetime, and its default is per-class: it starts before the class and stops when the class ends. So the moment the first test class finishes, the container dies - while the cached Spring context (and its datasource) is still sitting there pointing at a URL that no longer answers. The second test class that reuses that context talks to a corpse.

You can paper over this. @Testcontainers(disabledWithoutDocker = true) doesn't help. Making the container static doesn't help - the extension still stops it after the class's @AfterAll. Testcontainers' reuse feature (.withReuse(true) plus testcontainers.reuse.enable=true) keeps a container alive between JVM runs, which is a different thing from what we need and comes with its own state-leak warnings.

Spring even endorses a "singleton container" pattern for exactly this: start one container once, share it across the suite. The docs describe it, but the mechanics - where you start it, how every class gets the same one, how it stops - are left to you. Our TestPostgres is that singleton, made explicit.

What to do instead

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class TestPostgres {

    @ServiceConnection
    static final PostgreSQLContainer postgres = start();

    private static PostgreSQLContainer start() {
        PostgreSQLContainer container = new PostgreSQLContainer("postgres:18-alpine");
        container.start();
        return container;
    }
}

Four decisions, each load-bearing:

  1. No @Testcontainers, no @Container. The extension is not used at all, precisely because it would take ownership of the stop. The container is started in a static initializer and simply lives for the JVM. It is never stopped by us; the Testcontainers Ryuk sidecar reaps it when the JVM exits. That lifetime - one per JVM, outliving every test class - is the whole point.

  2. A shared base class. Every test extends TestPostgres, so every class sees the same static container, and Spring sees the same configuration, so it reuses one cached context. One container, one context, N test classes.

  3. @ServiceConnection. This annotation (with the spring-boot-testcontainers dependency) is what removes the wiring: Boot inspects the container, learns the JDBC URL and credentials, and registers a ConnectionDetails bean. No @DynamicPropertySource, no duplicated spring.datasource.* in a test properties file.

  4. @ActiveProfiles("test"). The test profile sets ddl-auto: update - and here is the second lifecycle trap: create-drop would drop the tables at context shutdown, and because the container (unlike a @Container) outlives the context, the next test class would find an empty database. update leaves the schema in place.

The bill that comes due: shared state

A container that lives for the whole JVM means the database is shared by every test class, and there is no automatic isolation between them. This is not a bug to fix; it is the trade, and it changes how tests must be written.

  • Roll back what you write. A test annotated @Transactional runs in a transaction Spring rolls back at the end, leaving no trace. @Transactional only rolls back the test's own thread, though - a test that hands work to another thread (or to the async pipeline executor) writes outside that transaction and must be written so its leftover rows cannot affect anyone else.
  • Assert about the rows you created, never about a whole table. "The table has one user" is a lie the moment another test class ran first. "The user I just saved has this id" is not.
  • Use real ids. Join from a row you created instead of hardcoding 1L, which is whichever row happened to land first in a shared database.
  • Seed only when empty. The app's own SeedData runner uses count() == 0 for the same reason: a running suite must not stomp on rows another class seeded.

None of this is unique to Testcontainers - it is the cost of any shared, long-lived database. The per-class @Container approach hides the cost by giving each class a fresh database, at the price of a fresh container and a fresh Spring context per class, which is the slowness we were trying to avoid in the first place.

What @ServiceConnection actually replaced

Before Boot 3.1 (2023), wiring a container into Spring looked like this:

@DynamicPropertySource
static void properties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
}

@DynamicPropertySource (Spring 5.2.5, 2020) was the answer to that being impossible without a custom ApplicationContextInitializer. @ServiceConnection removed even the @DynamicPropertySource boilerplate for well-known containers by making Boot connection-details-aware per container type. A container, a @ServiceConnection, and nothing else.

A short history, because the ground moved a lot

The "right way" to integration-test against a database in a Spring app has changed more than once in the last decade, and it is worth knowing why older code and older blog posts look nothing like this.

~2015–2018 - H2 and the embedded database era. The default answer was an in-memory database: H2 (or HSQLDB, Derby) with spring.jpa.hibernate.ddl-auto=create-drop. It was fast, it needed no Docker, and @DataJpaTest rolled it up for you. This is what a huge amount of 2015-era Spring tutorial content teaches. Its failure mode was that it is not your database: H2's dialect is not PostgreSQL's. PostgreSQL-specific things - jsonb, text-vs-varchar, generated-id behavior, timestamptz precision, check constraints emitted from enums - either fail loudly or, worse, pass in H2 and break in production. A suite green on H2 that fails on Postgres is a genre of bug.

2015, and slowly after - Testcontainers is born. Richard North's testcontainers-java appears in 2015 with the idea that a test can start a real Docker container, use it, and let it be reaped. It gains real traction only around 2019, once Docker is ubiquitous in CI. The early wiring is manual: GenericContainer with .withExposedPorts(5432), read getMappedPort(5432), then push it into Spring by hand.

~2019–2022 - real databases win, wiring stays painful. Teams move from H2 to Testcontainers, trading speed for fidelity. @DynamicPropertySource (2020) cleans up the URL plumbing. Two lifecycle patterns appear and compete: the per-class @Container (clean isolation, slow - a container and a Spring context per class) and the singleton/"shared" container (one container for the suite, fast, but you own the start/stop and the shared-state discipline).

2023 - Spring Boot 3.1 turns the container into a first-class test citizen. spring-boot-testcontainers ships @ServiceConnection, and Docker Compose support lands (spring-boot-docker-compose). Wiring becomes one annotation. Boot also documents the singleton container pattern as the recommended shape for multi-class suites - which is exactly the pattern we implement by hand, because the documented pattern is still a pattern, not a turnkey base class.

2023–2025 - Testcontainers 2.x, Boot 4, and the small-print churn. The 2.x line renames every module (testcontainers-postgresql, testcontainers-junit-jupiter - note the package moved too, to org.testcontainers.postgresql), which is why we need to pin those coordinates explicitly: Boot's BOM does not manage them. Boot 4 splits the old spring-boot-starter-test into per-slice *-test starters. Through all of it, the lifecycle question - who owns the container, and does it outlive the Spring context - stays the thing you actually have to get right.

How the community avoids bleeding feet

"Use Testcontainers" is table stakes by 2026. The hard part has always been the lifetime: a container that dies with its test class will betray the Spring context cache the moment a second class reuses that context. Mason's answer is to stop fighting the framework - own the container at JVM scope, share it, wire it with @ServiceConnection, and pay for the sharing with test discipline (roll back, assert on your own rows, real ids). One Postgres, one context, every test class, and a database no test can mistake for the developer's.