Testcontainers
Real Postgres, Kafka and Redis in tests, container reuse, and the CI configuration that makes it fast.
An integration test against H2 proves that your code works against H2. Production runs PostgreSQL 16, whose RETURNING, jsonb, partial indexes, ON CONFLICT, timezone handling and locking rules H2 either lacks or imitates loosely — and every one of those differences is a test that is green on Tuesday and a deploy that fails on Wednesday. Testcontainers starts the real thing in Docker for the duration of the test run. This repository ran every test of its former Java service that way, and its HTTP contract suite still runs against a throwaway PostgreSQL container for the same reason.
Why the real dependency
The argument is not purity; it is the list of things that only the real database catches. A migration that PostgreSQL rejects (ALTER TABLE ... ADD COLUMN ... NOT NULL without a default on a populated table). A query that uses DISTINCT ON. An entity whose ddl-auto=validate passes against Hibernate's own DDL and fails against the schema Flyway actually created. A SELECT ... FOR UPDATE SKIP LOCKED that H2 parses and does not honour. The same applies one level up: a Kafka listener tested against an in-memory broker has never met a rebalance, and a Redis client tested against a Map has never met a TTL.
The cost is Docker on the developer machine and in CI, and seconds of startup — and the startup is the thing to manage, because it is paid per container, not per test.
The Postgres container, as this repository runs it
@TestConfiguration(proxyBeanMethods = false)
public class PostgresTestcontainer {
@Bean
@ServiceConnection
PostgreSQLContainer postgres() {
PostgreSQLContainer container = new PostgreSQLContainer("postgres:16-alpine");
container.start();
SchemaMigrate.migrate(container.getJdbcUrl(), container.getUsername(), container.getPassword());
return container;
}
}Three decisions are in those lines. postgres:16-alpine is the version production runs, pinned — a floating latest is a test that changes under you. @ServiceConnection (Boot 3.1+) reads the container's host, port and credentials into spring.datasource.* with no @DynamicPropertySource boilerplate; the same annotation works for Kafka, Redis, Mongo and the rest. And the schema is applied by the same migration code the deploy runs, before Spring sees the database, so ddl-auto=validate checks the entities against the schema production actually has rather than one Hibernate generated for the test. A test class @Imports this configuration, or a composed @IntegrationTest annotation does it for all of them.
The alternative form, for a test that owns its container rather than sharing Spring's:
@Testcontainers
class ContentImportTest {
@Container static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:16-alpine");
...
}static means one container per class; an instance field means one per test method, which is almost never what you want.
Kafka, Redis and the rest
@Bean @ServiceConnection KafkaContainer kafka() { return new KafkaContainer("apache/kafka:3.9.0"); }
@Bean @ServiceConnection GenericContainer<?> redis() { return new GenericContainer<>("redis:7-alpine").withExposedPorts(6379); }The Kafka container is the one that changes what you can test: a real broker means a real consumer group, real rebalances when you start a second listener, real acks=all and a real dead-letter topic. Test the listener from the Kafka course end to end — produce with KafkaTemplate, wait for the side effect with Awaitility (await().atMost(5, SECONDS).untilAsserted(...)), never Thread.sleep — and the retry topic and DLT tests become possible at all. For a module with no Spring, GenericContainer plus getHost() and getMappedPort(6379) is the whole API.
Making it fast: one container per JVM, and reuse
The naive layout starts a container per test class, and a suite of twenty classes spends its time in Docker. Two fixes, in order of how much they buy:
- One container per JVM. A
staticcontainer in a shared base class, or the@ServiceConnectionbean above in a configuration every test imports, is started once and shared: Spring's context cache (the slices lesson) keeps the bean, and the container lives until the JVM exits. Test isolation then comes from rolled-back transactions or aTRUNCATEin@BeforeEach, not from a fresh database. - Reuse across runs.
withReuse(true)on the container plustestcontainers.reuse.enable=truein~/.testcontainers.propertiesleaves the container running after the JVM exits and finds it again on the next run — startup drops from seconds to milliseconds on a developer machine. It is a local convenience, not a CI setting: a reused container carries the last run's state, so it works only with tests that clean up.
For scale, this repository's numbers from one run of the quality gate while it still had a Java service (retired under ADR-0026), on a laptop: the Spring Boot test suite against a Postgres container completes in about 40 seconds including the container's start, and the HTTP contract suite — 260 tests against the built jar and a throwaway docker run Postgres — in about 3 minutes, of which the jar build and the container start are the fixed cost and the tests themselves are seconds each.
CI
CI needs a Docker daemon the tests can reach. On GitHub Actions the Ubuntu runners have one, and nothing else is required; on a Kubernetes-based CI the usual answers are a Docker-in-Docker sidecar or Testcontainers Cloud, and the usual mistake is a runner where DOCKER_HOST is set but the socket is not mounted. Pull the images in a cached layer or accept the first-run pull; pin the tags, as above, so the pull is cacheable at all. And make the tests skip with a message rather than fail when Docker is absent — assumeTrue(DockerClientFactory.instance().isDockerAvailable()) — so a developer without Docker sees "skipped: no Docker" and not a stack trace from deep inside the container library. This repository's guard scripts follow that rule; the Java-fixture guard prints its skip reason and the build carries on.
Under the hood: how Testcontainers actually talks to Docker, and how cleanup survives a crash
Testcontainers does not shell out to the docker CLI. DockerClientFactory resolves a Docker Engine API endpoint — DOCKER_HOST if set, otherwise the platform default (the Unix domain socket /var/run/docker.sock on Linux and on Docker Desktop for Mac, a named pipe or a TCP proxy on Docker Desktop for Windows, where the real daemon runs inside a VM) — and every operation from there is an HTTP call against that same REST API the docker CLI itself speaks: POST /containers/create, POST /containers/{id}/start, log streaming to detect readiness, and so on. No CLI binary needs to be installed for a test to run; only a reachable daemon does.
container.start() also does not return once the process has merely launched. It blocks until the container's configured WaitStrategy is satisfied — PostgreSQLContainer's default strategy tails the container's log output and waits for the specific line Postgres prints once it is actually ready to accept connections. That is why a test never races a container that technically exists but has not finished initialising: "started" here means "ready", not "process launched".
The cleanup mechanism is the part worth understanding precisely, because it explains a real failure mode. The moment the first container is requested, Testcontainers starts a second, small container of its own — Ryuk — and holds a TCP connection open to it for the life of the JVM session. Ryuk's entire job is: when that connection drops, remove every container, network and volume tagged with this session's id. That is not a JVM shutdown hook — a shutdown hook only runs on a clean or gracefully-signalled exit, and a kill -9 skips shutdown hooks entirely. Ryuk works even then, because it is a wholly separate process watching a connection, not code that has to run inside the dying JVM. TESTCONTAINERS_RYUK_DISABLED=true turns this off, and the one honest reason to set it is a CI environment where Ryuk itself cannot run — nested containers without the privileges a sibling container needs. Turning it off anywhere else just trades a hard-to-notice cost (an occasional orphaned container) for no benefit at all.
Try it yourself
Reason about what survives a force-killed test run
A CI job runs this lesson's Postgres-backed test suite, and partway through, the whole job is force-killed (kill -9 on the JVM process) because it hit a timeout — no graceful shutdown, no JVM shutdown hooks run. Using the mechanism above: does the Postgres test container get cleaned up, and if so, by what?
Why the JVM dying does not leave the container behind
kill -9 skips every JVM shutdown hook, so any cleanup that depended on Runtime.addShutdownHook running would never fire — and if that were the only mechanism, the container would be orphaned. But Ryuk is a separate process holding a TCP connection to the JVM's session, not code executing inside the JVM: when kill -9 ends the JVM, that connection simply drops, and Ryuk — still running, entirely unaffected by the JVM's death — treats the drop as "this session has ended" and removes every container, network and volume it tagged for that session. The cleanup survives the crash specifically because it was never designed to depend on the crashing process being the one that performs it.
Misconceptions
- "Testcontainers wraps the
dockerCLI." It talks to the Docker Engine API directly over the socket or named pipe; the CLI binary is not involved and does not need to be installed, only a daemon Testcontainers can reach. - "Setting
TESTCONTAINERS_RYUK_DISABLED=truespeeds up the tests." It does not — Ryuk runs alongside the tests, not in their critical path, and its overhead is one extra lightweight container per session. Disabling it does not make anything faster; it just moves the job of removing leftover containers from Ryuk onto whoever eventually notices disk usage climbing.
Sources
- Testcontainers documentation — architecture overview and Ryuk resource-reaping.
- Docker Engine API reference.