Testcontainers Reuse Pattern: Speed Up Your Test Suite with Persistent Containers
Testcontainers makes integration tests correct. The reuse pattern makes them fast. If your test suite starts a PostgreSQL container for every run and you iterate frequently, those 5–10 seconds of startup time add up to minutes of waiting per hour. The reuse feature keeps containers alive between runs so startup cost is paid only once.
The Problem: Container Startup Overhead
A typical Testcontainers test suite without reuse:
[10:00:00] Starting postgres container... (8s)
[10:00:08] Running 42 tests... (12s)
[10:00:20] Stopping container.
[10:00:22] Starting postgres container... (8s) ← you saved a file and re-ran
[10:00:30] Running 42 tests... (12s)With reuse, the second run looks like:
[10:00:22] Reusing existing postgres container. (0.1s)
[10:00:22] Running 42 tests... (12s)The container stays running between runs. Testcontainers finds it by a fingerprint hash derived from its configuration and reattaches to it rather than starting a new one.
Enabling Reuse: Two Steps
Reuse requires an opt-in at two levels: in your test code and in your environment.
Step 1: .withReuse(true) in code
// Java
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb")
.withUsername("testuser")
.withPassword("testpass")
.withReuse(true); // keep this container alive after the test finishes# Python
from testcontainers.postgres import PostgresContainer
postgres = PostgresContainer("postgres:16-alpine").with_reuse()// Node.js / @testcontainers/testcontainers
const container = await new PostgreSqlContainer("postgres:16-alpine")
.withReuse()
.start();Step 2: TC_REUSE_ENABLE=true in the environment
The environment flag is a safety valve. Without it, .withReuse(true) is silently ignored. This prevents a developer from accidentally leaving long-lived containers on a CI agent where isolation is required.
Add it to your local shell profile:
# ~/.zshrc or ~/.bashrc
export TESTCONTAINERS_RYUK_DISABLED=false
export TC_REUSE_ENABLE=trueOr set it per command:
TC_REUSE_ENABLE=true mvn test
TC_REUSE_ENABLE=true pytest
TC_REUSE_ENABLE=true npx jestOn CI, keep TC_REUSE_ENABLE unset (or set to false) unless you explicitly want containers to survive between jobs on a self-hosted runner.
How the Fingerprinting Works
Testcontainers computes a hash from the container's configuration: image name, environment variables, exposed ports, volume mounts, and command. If you change any of these — for example upgrading from postgres:15 to postgres:16 — the hash changes, a new container is started, and the old one is eventually cleaned up by Ryuk.
This means reuse is safe with respect to configuration drift: you always get a container matching your current test specification.
Java: Full Example with Reuse and Per-Test Cleanup
When containers are reused, data from previous runs is still present. You need a cleanup strategy. The most common approach is truncating tables between tests rather than dropping and recreating the schema:
@Testcontainers
class ProductRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb")
.withUsername("testuser")
.withPassword("testpass")
.withReuse(true);
static DataSource dataSource;
@BeforeAll
static void setup() {
dataSource = DataSourceBuilder.create()
.url(postgres.getJdbcUrl())
.username(postgres.getUsername())
.password(postgres.getPassword())
.build();
// Run migrations once; idempotent migrations handle reruns gracefully
Flyway.configure().dataSource(dataSource).load().migrate();
}
@BeforeEach
void truncate() throws Exception {
try (var conn = dataSource.getConnection();
var stmt = conn.createStatement()) {
stmt.execute("TRUNCATE TABLE products RESTART IDENTITY CASCADE");
}
}
@Test
void createProduct_AssignsId() {
var repo = new ProductRepository(dataSource);
var product = repo.save(new Product("Widget", BigDecimal.valueOf(9.99)));
assertNotNull(product.getId());
}
}The TRUNCATE ... RESTART IDENTITY CASCADE resets all sequences and clears related tables, giving each test a clean slate without touching the schema.
Python: Reuse with pytest fixture scope
import pytest
from testcontainers.postgres import PostgresContainer
import psycopg2
@pytest.fixture(scope="session")
def pg():
with PostgresContainer("postgres:16-alpine").with_reuse() as container:
yield container
@pytest.fixture(autouse=True)
def clean_db(pg):
conn = psycopg2.connect(pg.get_connection_url())
cur = conn.cursor()
cur.execute("TRUNCATE TABLE orders RESTART IDENTITY CASCADE")
conn.commit()
cur.close()
conn.close()
def test_create_order(pg):
conn = psycopg2.connect(pg.get_connection_url())
cur = conn.cursor()
cur.execute("INSERT INTO orders (customer_id) VALUES (%s) RETURNING id", ("cust-1",))
order_id = cur.fetchone()[0]
conn.commit()
assert order_id > 0When to Use Reuse (and When Not To)
Use reuse locally during active development when you run tests repeatedly and startup time is slowing your feedback loop.
Do not use reuse in CI unless you are on a self-hosted runner with persistent Docker state between runs. Managed runners (GitHub Actions, GitLab SaaS) provision a fresh VM per job, so reuse has no effect.
Do not use reuse when testing migrations. If you are testing that a migration runs correctly from scratch, you need a clean container every time. Reuse would leave the previous migration state in place.
Use reuse for stateless services like Redis or Kafka where your cleanup strategy is to delete keys or purge topics between tests rather than recreating the service.
Disabling Ryuk
By default Testcontainers starts a Ryuk container that cleans up any containers left behind by crashed test processes. When using reuse, Ryuk is still running but it will not remove reused containers because they are marked with a specific label.
If your environment does not allow privileged containers (some restricted CI setups), you can disable Ryuk entirely:
export TESTCONTAINERS_RYUK_DISABLED=trueBe aware this means orphaned containers from crashed runs will not be cleaned up automatically — you are responsible for cleanup.
Measuring the Speedup
Time your test suite before and after enabling reuse:
# Without reuse
time mvn test -Dgroups=integration
# Enable reuse
export TC_REUSE_ENABLE=true
time mvn test -Dgroups=integration # first run: same as before
time mvn test -Dgroups=integration # second run: should be fasterOn a typical project with a PostgreSQL container, expect to save 5–15 seconds per run. Over a day of active development with 50+ test runs, that is 5–12 minutes returned to you.
Closing Thoughts
The reuse pattern is a quality-of-life improvement for active development. It does not change what you are testing — your tests stay honest, running against real infrastructure — it just removes the friction of waiting for containers to start.
Once your suite is fast and green, HelpMeTest can take over monitoring from there: running your critical test scenarios 24/7 against your live environments so you know the moment something breaks in production.