How to Share Containers Across Tests and Speed Up the Suite
Cut Testcontainers overhead: static containers, the singleton pattern, Spring context caching, local reuse and cleaning state between tests.

A Testcontainers suite that starts a PostgreSQL container for each of forty test classes spends minutes starting databases. The tests are not slow, the setup is. Sharing the container fixes the setup cost, and creates a new problem: tests now share state. This covers both. It uses Testcontainers 1.21, JUnit Jupiter 6 and Spring Boot 4 on JDK 25.
What costs time
A container start means creating the container, waiting for the process to be ready (a database may take two to five seconds), and for a fresh machine, pulling the image. Multiplied by classes, it dominates. Measure with the test report: if most time is before the first assertion, share.
Pattern 1: the singleton container
abstract class DatabaseTest {
static final PostgreSQLContainer<?> DB = new PostgreSQLContainer<>("postgres:17-alpine");
static {
DB.start(); // once per JVM
}
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", DB::getJdbcUrl);
r.add("spring.datasource.username", DB::getUsername);
r.add("spring.datasource.password", DB::getPassword);
}
}
@SpringBootTest
class OrderIT extends DatabaseTest { }
@SpringBootTest
class CustomerIT extends DatabaseTest { }The static initializer runs once when the base class loads. There is no stop(): the Ryuk sidecar container that Testcontainers starts removes everything when the JVM exits. A @Container field would stop the container after each class, which is what you are avoiding.
Pattern 2: bean containers and the context cache
With ServiceConnection, define containers in a @TestConfiguration and import it:
@SpringBootTest
@Import(Containers.class)
class OrderIT { }Spring caches the ApplicationContext by its configuration key. Test classes with the same configuration share one context, hence one set of containers. Anything that changes the key creates a new context and new containers: different @MockitoBean declarations, different properties, @DirtiesContext. A suite with many variations loses the sharing. Keep a standard configuration and few exceptions, as in Spring test context caching.
Isolating state
A shared database retains rows between tests. Options:
| Technique | Notes |
|---|---|
@Transactional test, rolled back | Fast; hides commit-time behaviour and does not span threads |
truncate ... restart identity cascade in @BeforeEach | Explicit, works for any code path |
| Unique ids or tenants per test | No cleanup needed, data accumulates |
| Per-class schema or database | Strong isolation, more setup |
@BeforeEach
void clean(@Autowired JdbcTemplate jdbc) {
jdbc.execute("truncate table orders, customers restart identity cascade");
}Tests that depend on leftovers from another test are bugs; run them in random order to find them, see test ordering.
Reuse across runs: local only
Testcontainers can keep a container alive after the JVM exits, so the next run connects to it:
# ~/.testcontainers.properties
testcontainers.reuse.enable=truenew PostgreSQLContainer<>("postgres:17-alpine").withReuse(true);The next run finds a container with the same configuration and uses it, saving the start time. It is an experimental feature intended for local work. State persists between runs, so data left by the previous run is still there, and Ryuk does not clean it. Do not enable it on CI, where a clean environment is the point.
Parallel tests
Shared containers and parallel test execution together need per-test isolation by unique data, because truncation in one test destroys another's rows. A database per worker (a template database cloned per test class) is a more advanced answer.
Memory and the image
Choose small images (-alpine), set withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) for PostgreSQL to keep data in memory, and consider fsync off for speed in tests:
.withCommand("postgres", "-c", "fsync=off")These trade durability, which tests do not need, for speed.
Empty the tables between tests, not the container
A shared database keeps its rows from one test to the next, and tests that assume an empty table fail depending on order. Truncating the tables before each test is cheaper than a fresh container, and one helper does it for every class:
@Component
class DatabaseCleaner {
private final JdbcTemplate jdbc;
DatabaseCleaner(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
void clean() {
jdbc.execute("truncate table order_line, orders, customer restart identity cascade");
}
}
@SpringBootTest
abstract class IntegrationTest {
@Autowired DatabaseCleaner cleaner;
@BeforeEach
void emptyDatabase() {
cleaner.clean();
}
}restart identity resets sequences so ids are predictable, and cascade follows foreign keys. List the tables once, or read them from the metadata, and exclude the migration history table such as flyway_schema_history, which must keep its rows. A truncate of ten small tables takes a few milliseconds on PostgreSQL.
Reuse between runs with an explicit opt-in
A container can stay alive after the JVM exits, so the next run on the same machine skips the start. The feature is off by default, and two switches turn it on, one in the code and one in the user's own settings:
static final PostgreSQLContainer<?> DB = new PostgreSQLContainer<>("postgres:17").withReuse(true);# ~/.testcontainers.properties
testcontainers.reuse.enable=trueThe user-level property is on purpose: CI should never reuse, because a container left over from another job carries someone else's data. With reuse on, the container is not cleaned up, so remove it with docker rm -f when a schema or image changes. A developer who reuses containers also needs the truncate step above, since the data survives the run.
One database per test class when isolation matters
Some tests cannot share data, such as those that count rows or run schema migrations. Creating a database per class inside one shared server keeps the isolation and the speed:
static String createDatabase(String name) throws SQLException {
try (Connection c = DriverManager.getConnection(DB.getJdbcUrl(), DB.getUsername(), DB.getPassword());
Statement s = c.createStatement()) {
s.execute("create database " + name + " template template_migrated");
}
return DB.getJdbcUrl().replaceFirst("/[^/?]+", "/" + name);
}template template_migrated copies a database that already has the schema applied, so each new database is created in milliseconds and no migration runs. Build the template once at suite start, then clone it for each class. Validate the name before concatenating it, since it goes into SQL.
What to watch in CI
| Concern | Advice |
|---|---|
| Image pull time | Pin the tag, and cache Docker layers on the runner |
| Parallel jobs on one host | Each job starts its own containers, so ports are random and do not clash |
| Docker unavailable | Fail with a clear message, not a skipped suite |
| Cleanup of leftover containers | Keep the Ryuk reaper enabled, it removes containers when the JVM exits |
| Startup wait | Use the container's wait strategy and a timeout of a minute or so |
Disabling Ryuk to save a second leaves orphaned containers on every crashed build, and a CI host fills its memory within days. Keep it on.
The test of whether sharing is safe
A shared container is safe when each test cleans before it runs and no test depends on rows from another. Run the suite in random order a few times with a JUnit setting junit.jupiter.testclass.order.default=org.junit.jupiter.api.ClassOrderer$Random. A test that fails only in some orders has a hidden dependency, and it is better to find it now than during a Friday release.
Keeping the suite honest as it grows
A shared container makes tests faster, and speed hides problems that only show later. Track the run time of the suite on CI and alert when it grows by more than ten percent in a week. Look at the slowest tests every month, and move those that do not need a database into plain unit tests. Review the number of distinct Spring contexts, which tends to grow quietly as people add mocks.
A suite that stays under ten minutes is run before every commit, and one that takes forty minutes is run by nobody until the build breaks.
Where this does not apply
If a suite has one or two container classes, the complexity is not worth it. Reference: the Testcontainers singleton pattern and reusable containers.


