00:00

Run Apache Kafka with Docker and Docker Compose

Last updated:

Running Apache Kafka with Docker is the fastest way to get a working broker on your laptop. With one command you get a real Kafka 4 broker in KRaft mode, with no ZooKeeper and no manual installation, that your Java and Spring Boot applications can connect to.

This tutorial starts with a one-line docker run, then builds a docker-compose.yml you can keep in your project: listeners that work from both your laptop and other containers, persistent data, a health check, and a three-broker variant. It also explains the mistakes that cause most “cannot connect to Kafka” errors.

1. What You Get with the Official Kafka Image

The Apache Kafka project publishes two Docker images on Docker Hub:

ImageWhat it isWhen to use it
apache/kafkaThe standard JVM-based Kafka brokerLocal development, integration tests, anything close to production behaviour
apache/kafka-nativeA GraalVM native build of the broker, available since Kafka 3.8, with faster startup and lower memory useFast test suites; the project describes it as experimental, so do not use it in production

Both images run Kafka in KRaft mode: the same process acts as broker and controller, and cluster metadata is stored in Kafka itself. ZooKeeper was removed in Kafka 4.0, so tutorials that start a separate ZooKeeper container are outdated.

Note: Older blog posts often use third-party images such as confluentinc/cp-kafka or bitnami/kafka. They work, but their environment variables and defaults differ. This tutorial uses only the official apache/kafka image.

2. Quick Start: One Command

If you only need a broker for a few minutes, run:

Terminal
docker run -d --name kafka -p 9092:9092 apache/kafka:4.4.0

Without any configuration, the image starts a single combined broker and controller with the default configuration bundled in the image, listening on port 9092 and advertising localhost:9092. Clients on your laptop can connect to localhost:9092 straight away.

This is perfect for a quick experiment, but it has limits: other containers cannot reach the broker under the name localhost, and all data disappears when the container is removed. The Compose file in the next section fixes both.

3. A Docker Compose File for Development

Create docker-compose.yml in your project. It follows the single-node example published by the Kafka project, adds a volume for data and a health check:

docker-compose.yml
services:
  broker:
    image: apache/kafka:4.4.0
    container_name: broker
    hostname: broker
    ports:
      - "9092:9092"                      # for clients on your laptop
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_LISTENERS: CONTROLLER://:29093,PLAINTEXT_HOST://:9092,PLAINTEXT://:19092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT_HOST://localhost:9092,PLAINTEXT://broker:19092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
      CLUSTER_ID: 4L6g3nShT-eMCtK--X86sw
      KAFKA_LOG_DIRS: /var/lib/kafka/data
      # single broker: internal topics cannot have 3 replicas
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0   # development only
    volumes:
      - kafka-data:/var/lib/kafka/data
    healthcheck:
      test: ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 > /dev/null 2>&1"]
      interval: 10s
      timeout: 10s
      retries: 10

volumes:
  kafka-data:

The most important settings:

  • KAFKA_PROCESS_ROLES: broker,controller runs this node in combined mode. Production clusters usually separate controllers from brokers, but one combined node is ideal on a laptop.
  • CLUSTER_ID is used by the image to format the storage directory on first start. Any valid cluster ID works (kafka-storage.sh random-uuid generates one); keep it stable, because a node refuses to start if its stored data belongs to a different cluster ID.
  • Replication factor 1 for internal topics. Kafka defaults to 3 replicas for __consumer_offsets and the transaction and share-state topics. With a single broker those topics could not be created, so consumer groups and transactions would never work.
  • KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 removes the default 3-second wait before the first consumer-group rebalance, which makes local tests faster. Keep the default in production.
  • The named volume keeps topics and offsets across docker compose down and image upgrades. The image prepares /var/lib/kafka/data so that the Kafka user can write to it.

4. How Listeners Work in Docker

Listeners are the part that confuses most people, because a client connects twice. First it contacts the bootstrap address you configured. The broker then returns its advertised address for each partition leader, and the client opens new connections to those addresses. If the advertised address is not reachable from where the client runs, the first connection works and everything after it fails.

Kafka listeners in DockerA Java application on the laptop connects to localhost:9092. Docker publishes port 9092 of the broker container, which listens there with the PLAINTEXT_HOST listener and advertises localhost:9092. An application container on the same Compose network connects to broker:19092 through the PLAINTEXT listener, which advertises broker:19092. The controller listener on port 29093 is used only inside the broker. Your laptop (host) Java / Spring appbootstrap: localhost:9092 Docker Compose network container "broker" PLAINTEXT_HOST :9092advertises localhost:9092 PLAINTEXT :19092advertises broker:19092 CONTROLLER :29093internal only App containerbootstrap: broker:19092 published with-p 9092:9092
Each listener is a separate door into the broker. Clients must use the door whose advertised address they can reach.
ListenerListens onAdvertised asUsed by
PLAINTEXT_HOST:9092 (published to the host)localhost:9092Applications and CLI tools on your laptop
PLAINTEXT:19092broker:19092Other containers on the Compose network, and other brokers
CONTROLLER:29093not advertised to clientsKRaft controller traffic

The listener names are free text; the KAFKA_LISTENER_SECURITY_PROTOCOL_MAP maps each name to a security protocol, here PLAINTEXT for all three. The SSL and SASL tutorial shows how to switch a listener to an encrypted, authenticated protocol.

5. Passing Configuration with Environment Variables

Every broker property can be set as an environment variable. The image converts the variable name back into the property name with these rules:

RuleExample propertyEnvironment variable
Prefix with KAFKA_, upper case, . becomes _log.retention.hoursKAFKA_LOG_RETENTION_HOURS
_ becomes __ (double underscore)abc_defKAFKA_ABC__DEF
- becomes ___ (triple underscore)abc-defKAFKA_ABC___DEF
Important: the bundled default configuration is used only when you pass no configuration at all. As soon as you provide environment variables, you must provide a complete KRaft configuration, as the Compose file above does. You can also mount a folder with your own server.properties to /mnt/shared/config; environment variables then override values from the file.

6. Starting Kafka and Running CLI Commands

Start the broker and wait until the health check reports healthy:

Terminal
docker compose up -d
docker compose ps            # STATUS should show "healthy"
docker compose logs -f broker

The Kafka command-line tools are inside the image under /opt/kafka/bin, so you do not need a local Kafka download. Create a topic, then produce and consume a few records:

Terminal
docker exec broker /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 \
  --create --topic orders --partitions 3 --replication-factor 1

docker exec -it broker /opt/kafka/bin/kafka-console-producer.sh \
  --bootstrap-server localhost:9092 --topic orders
# type a few lines, then press Ctrl+C

docker exec -it broker /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 --topic orders --from-beginning

Inside the container, localhost:9092 reaches the PLAINTEXT_HOST listener, so the same address works for commands run with docker exec. The Kafka CLI commands tutorial covers the tools in detail.

7. Connecting Java and Spring Boot Applications

An application running on your laptop uses localhost:9092. This small producer sends one record and prints where it was stored:

DockerKafkaCheck.java
package com.javabytechie.kafka;

import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

public class DockerKafkaCheck {

    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        try (var producer = new KafkaProducer<String, String>(props)) {
            RecordMetadata meta = producer
                    .send(new ProducerRecord<>("orders", "order-1001", "PLACED"))
                    .get();                       // wait only because this is a connectivity check
            System.out.printf("Stored in %s-%d at offset %d%n",
                    meta.topic(), meta.partition(), meta.offset());
        }
    }
}
Output
Stored in orders-2 at offset 0

The partition depends on the hash of the key, so your output may show a different partition number. For a Spring Boot application, point the auto-configuration at the same address:

application.yml
spring:
  kafka:
    bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:localhost:9092}

When the application itself runs as a container in the same Compose file, set KAFKA_BOOTSTRAP_SERVERS=broker:19092 for it and add depends_on with condition: service_healthy, so it starts only after the broker is ready:

docker-compose.yml (additional service)
  order-service:
    image: com.javabytechie/order-service:latest
    environment:
      KAFKA_BOOTSTRAP_SERVERS: broker:19092
    depends_on:
      broker:
        condition: service_healthy

For automated tests, starting Kafka from the test itself is usually better than a shared Compose file; see Testing Kafka Applications.

8. Running a Three-Broker Cluster

A single broker cannot show replication, leader election or what happens when a broker fails. For that, run three nodes. Each node needs its own KAFKA_NODE_ID, hostname and host port, and all three list the same controller quorum. The settings that change compared with the single-node file are:

docker-compose.yml (node 2 of 3, excerpt)
  kafka-2:
    image: apache/kafka:4.4.0
    hostname: kafka-2
    ports:
      - "39092:9092"
    environment:
      KAFKA_NODE_ID: 2
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka-1:9093,2@kafka-2:9093,3@kafka-3:9093
      KAFKA_LISTENERS: PLAINTEXT://:19092,CONTROLLER://:9093,PLAINTEXT_HOST://:9092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-2:19092,PLAINTEXT_HOST://localhost:39092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      CLUSTER_ID: 4L6g3nShT-eMCtK--X86sw     # identical on all nodes
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 3
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 3
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 2

Each node advertises its own host port (29092, 39092, 49092 for nodes 1–3) so that a client on your laptop can reach every partition leader. With three nodes you can create topics with --replication-factor 3, stop one container and watch leader election happen. The official Kafka repository also contains an example with a dynamic controller quorum, which uses KAFKA_CONTROLLER_QUORUM_BOOTSTRAP_SERVERS instead of a fixed voter list.

9. Common Mistakes

SymptomCauseFix
Client connects, then fails with “Connection to node 1 (broker/…:19092) could not be established”The client on the host was given the container listener and received an address it cannot resolveUse localhost:9092 from the host and broker:19092 from containers
Consumers never receive records; logs show COORDINATOR_NOT_AVAILABLE__consumer_offsets needs 3 replicas but there is one brokerSet KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 (and the transaction settings)
Container exits right after start with a cluster ID mismatchCLUSTER_ID changed but the volume still holds data from the old clusterKeep the ID stable, or delete the volume with docker compose down -v
All topics are gone after a restartNo volume, or the stack was removed with down -vUse a named volume and docker compose stop or plain down
Setup copied from an old tutorial fails to startIt still defines ZooKeeper settingsKafka 4 runs only in KRaft mode; remove ZooKeeper containers and settings
Bind for 0.0.0.0:9092 failed: port is already allocatedAnother Kafka (or old container) already uses the portStop it, or publish a different host port and advertise that port

10. Best Practices

  • Pin the image version (apache/kafka:4.4.0), never latest, so everyone on the team runs the same broker.
  • Keep the Compose file in the repository so new developers start Kafka with one command.
  • Use the health check and service_healthy instead of fixed sleeps before starting dependent services.
  • Name listeners by purpose (for example PLAINTEXT_HOST) so it is obvious which address belongs to which network.
  • Treat this setup as development only. It has no encryption, no authentication and a single replica; production needs separate controllers, replication factor 3 and security.
  • Prefer Testcontainers for automated tests, so each test run gets a clean broker on a random port.

11. Summary

The official apache/kafka image gives you a KRaft broker with one command, and a short Compose file turns it into a reliable development environment. The two settings that decide whether it works are the advertised listeners (one address per network that clients connect from) and replication factor 1 for internal topics on a single broker. Add a named volume for persistence, a health check for startup ordering, and pin the image version; scale to three nodes when you want to see replication and failover.

13. References