Spring Boot and Kafka using Docker Compose

Learn to create a Spring boot application, run a local Apache Kafka broker instance using Docker Compose, configure the Kafka to message producer as KafkaTemplate and message consumer using @KafkaListener.

1. Goals

In this tutorial, we will learn to:

  • Create a Spring boot application with Kafka dependencies.
  • Setup and run a local Kafka broker using an inbuilt docker-compose module.
  • Configure Kafka properties for message producer and listener.
  • Use KafkaTemplate to send messages to a topic
  • Use @KafkaListener to listen to messages sent to the topic in real-time

2. Maven

Open Spring initializr and create a Spring boot application with the following dependencies:

  • Spring for Apache Kafka
  • Spring Web
  • Docker Compose Support (Optional). It is needed if you plan to use a local Kafka installation running on a Docker container.

The generated project has the following dependencies in pom.xml.




3. Docker Compose File Kafka Broker

If you are planning to use a local Kafka broker running as the Docker container in your machine, you can follow this step. Create a docker-compose.yaml file in the application root and provide the following docker cluster configuration. Note that you can change the configuration based on your specific requirements.

The following configuration will create a single-node Kafka server with 1 zookeeper and 1 broker instance. The configuration also ensures that the Zookeeper server always starts before the Kafka server (broker) and stops after it.

The best part is that spring-boot-docker-compose module will automatically detect this configuration file, download the necessary images, and run the containers before the application is fully started to accept any request.

version: '3'
    image: confluentinc/cp-zookeeper:latest
    container_name: zookeeper
      - "22181:2181"

    image: confluentinc/cp-kafka:latest
    container_name: broker
      - "9092:9092"
      - zookeeper
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181

4. Kafka Configuration

Start with making small configuration changes and know what capability they provide.

4.1. Minimal Configuration

The Kafka configuration is controlled by the configuration properties with the prefix spring.kafka.*. For example, add the following property so Spring boot auto-configuration will create a KafkaTemplate and other necessary beans.


4.2. Create a New Topic

If we want to create a new Topic in the Kafka broker, if it does not exist, we can provide the topic configuration as follows:

public class KafkaConfig {

  public NewTopic taskTopic() {
    return TopicBuilder.name("task-topic")

4.3. Custom Key-Value Serializer and Deserializer

By default, Kafka supports message keys and values as normal String types. We can send the custom Java type as the message value, also, after configuring the appropriate serializers and deserializers.

Suppose, we message value to send is an instance of TaskStatus class.

public class TaskStatus implements Serializable {

  private String taskId;
  private String taskName;
  private float percentageComplete;
  private Status status;

  public enum Status {

We want to send the serialized value of TaskStatus as a JSON object so that it can be used by any consumer in a technology-agnostic manner.

# consumer config


# producer config


5. KafkaTemplate as Message Producer

If we want to configure a Kafka message producer in the application, KafkaTemplate is an excellent choice for its Template style usage, for example, as learned in DynamoDbTemplate or RestTemplate.

KafKaProducerService class uses autowired KafkaTemplate to send messages to the specified topic name.

public class KafkaProducerService {

  private final Logger LOGGER = LoggerFactory.getLogger(KafkaProducerService.class);

  KafkaTemplate<String, TaskStatus> kafkaTemplate;

  public void send(String topicName, String key, TaskStatus value) {

    var future = kafkaTemplate.send(topicName, key, value);

    future.whenComplete((sendResult, exception) -> {
      if (exception != null) {
      } else {
      LOGGER.info("Task status send to Kafka topic : "+ value);

We can use this service to send a message as follows:

KafkaProducerService kafkaProducerService;

//Using service

kafkaProducerService.send("general-task-topic", taskStatus.getTaskId(), taskStatus);

6. @KafkaListener as Message Consumer

Similarly, KafKaConsumerService class uses @KafkaListener to receive messages from the specified topic name and group id.

public class KafKaTopicListeners {

  private final Logger logger = LoggerFactory.getLogger(KafKaTopicListeners.class);

  @KafkaListener(topics = {"general-task-topic"}, groupId = "task-group")
  public void consume(TaskStatus taskStatus) {

    logger.info(String.format("Task status is updated : " + taskStatus));

7. Demo

For demo purposes, we can use the CommandLineRunner interface to send a few messages and then check the listener class for verification of the Kafka setup.

public class Application implements CommandLineRunner {

  KafkaTemplate kafkaTemplate;

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);

  public void run(String... args) throws Exception {

    kafkaTemplate.send("general-task-topic", "taskId", new TaskStatus("taskId", "taskName", 50.0f, Status.RUNNING));
    kafkaTemplate.send("general-task-topic", "taskId", new TaskStatus("taskId", "taskName", 100.0f, Status.FINISHED));

Observe the console logs:

c.h.d.jms.service.KafKaTopicListeners    : Task status is updated : TaskStatus(taskId=taskId, taskName=taskName, percentageComplete=50.0, status=RUNNING)

c.h.d.jms.service.KafKaTopicListeners    : Task status is updated : TaskStatus(taskId=taskId, taskName=taskName, percentageComplete=100.0, status=FINISHED)

8. Conclusion

In this spring boot Kafka example, we learned to create a spring boot application and configure Kafka broker instance, and used Spring boot autoconfiguration provided KafkaTemplate and KafkaListener.

Additionally, we verified the application by posting some messages using KafkaTemplate and then consuming the messages using @KafkaListener.

Happy Learning !!

Source Code on Github

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode