- 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
The following field in your JUnit test class will prepare a container running Kafka:
@ClassRule public static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"));
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:
If for some reason you want to use an externally running Zookeeper, then just pass its location during construction:
KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE) .withNetwork(network) .withExternalZookeeper("zookeeper:2181");
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.15.2</version> <scope>test</scope> </dependency>