Testcontainers can be used to automatically instantiate and manage Apache Kafka containers. More precisely Testcontainers uses the official Docker images for Confluent OSS Platform
- Running a single node Kafka installation with just one line of code
- No need to manage external Zookeeper installation, required by Kafka. But see below
KafkaContainer to use it in your tests:
KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1"))
The correspondence between Confluent Platform versions and Kafka versions can be seen in Confluent documentation
Now your tests or any other process running on your machine can get access to running Kafka broker by using the following bootstrap server location:
Using external Zookeeper
If for some reason you want to use an externally running Zookeeper, then just pass its location during construction:
KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1")) .withNetwork(network) .withExternalZookeeper("zookeeper:2181");
Using Kraft mode
KRaft mode was declared production ready in 3.3.1 (confluentinc/cp-kafka:7.3.x)"
KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.4.0")).withKraft()
See the versions interoperability matrix for more details.
If your test needs to run some other Docker container which needs access to Kafka, do the following:
- Run your other container on the same network as Kafka container, e.g.:
GenericContainer<?> application = new GenericContainer<>(DockerImageName.parse("alpine")) .withNetwork(network)
kafka.getNetworkAliases().get(0)+":9092"as bootstrap server location. Or just give your Kafka container a network alias of your liking.
You will need to explicitly create a network and set it on the Kafka container as well as on your other containers that need to communicate with Kafka.
Adding this module to your project dependencies
Add the following dependency to your
<dependency> <groupId>org.testcontainers</groupId> <artifactId>kafka</artifactId> <version>1.18.3</version> <scope>test</scope> </dependency>