Run Apache Kafka with Docker and Docker Compose
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:
| Image | What it is | When to use it |
|---|---|---|
apache/kafka | The standard JVM-based Kafka broker | Local development, integration tests, anything close to production behaviour |
apache/kafka-native | A GraalVM native build of the broker, available since Kafka 3.8, with faster startup and lower memory use | Fast 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.
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:
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:
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,controllerruns this node in combined mode. Production clusters usually separate controllers from brokers, but one combined node is ideal on a laptop.CLUSTER_IDis used by the image to format the storage directory on first start. Any valid cluster ID works (kafka-storage.sh random-uuidgenerates 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_offsetsand 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: 0removes 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 downand image upgrades. The image prepares/var/lib/kafka/dataso 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.
| Listener | Listens on | Advertised as | Used by |
|---|---|---|---|
PLAINTEXT_HOST | :9092 (published to the host) | localhost:9092 | Applications and CLI tools on your laptop |
PLAINTEXT | :19092 | broker:19092 | Other containers on the Compose network, and other brokers |
CONTROLLER | :29093 | not advertised to clients | KRaft 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:
| Rule | Example property | Environment variable |
|---|---|---|
Prefix with KAFKA_, upper case, . becomes _ | log.retention.hours | KAFKA_LOG_RETENTION_HOURS |
_ becomes __ (double underscore) | abc_def | KAFKA_ABC__DEF |
- becomes ___ (triple underscore) | abc-def | KAFKA_ABC___DEF |
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:
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:
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:
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());
}
}
}
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:
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:
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:
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
| Symptom | Cause | Fix |
|---|---|---|
| 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 resolve | Use 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 broker | Set KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 (and the transaction settings) |
| Container exits right after start with a cluster ID mismatch | CLUSTER_ID changed but the volume still holds data from the old cluster | Keep the ID stable, or delete the volume with docker compose down -v |
| All topics are gone after a restart | No volume, or the stack was removed with down -v | Use a named volume and docker compose stop or plain down |
| Setup copied from an old tutorial fails to start | It still defines ZooKeeper settings | Kafka 4 runs only in KRaft mode; remove ZooKeeper containers and settings |
Bind for 0.0.0.0:9092 failed: port is already allocated | Another Kafka (or old container) already uses the port | Stop it, or publish a different host port and advertise that port |
10. Best Practices
- Pin the image version (
apache/kafka:4.4.0), neverlatest, 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_healthyinstead 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.
12. Related Reading
- Kafka KRaft mode: how the controller quorum replaces ZooKeeper
- Kafka cluster: brokers, controllers and how a cluster is organised
- Kafka with Spring Boot: build a producer and consumer against this broker
- Testing Kafka applications: embedded Kafka and Testcontainers
13. References
Kafka Docker Setup Interview Questions and Answers
Common interview questions on Kafka Docker Setup, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Which Docker image should you use to run Apache Kafka 4, and does it need ZooKeeper?
Answer: The official apache/kafka image, pinned to a version such as apache/kafka:4.4.0. It runs Kafka in KRaft mode, where the broker process also acts as controller and stores metadata in Kafka itself, so no ZooKeeper container is needed; ZooKeeper support was removed in Kafka 4.0. The apache/kafka-native image starts faster but is experimental and meant for testing, not production.
Q. How do you pass a broker property such as log.retention.hours to the Kafka container?
Answer: As an environment variable prefixed with KAFKA_, in upper case, with dots replaced by underscores: KAFKA_LOG_RETENTION_HOURS=24. Underscores in the property become double underscores and dashes become triple underscores. Alternatively, mount a folder with a server.properties file to /mnt/shared/config; environment variables override values from that file.
Intermediate questions
Q. Why does a Docker-based Kafka setup usually need two client listeners?
Answer: Because clients connect in two steps: they bootstrap with any address, then reconnect to the advertised address of each partition leader. Applications on the host can only reach the published port as localhost:9092, while containers on the Compose network reach the broker by its service name, such as broker:19092. One listener cannot advertise both, so each network gets its own listener and advertised address.
Q. Why must internal topic replication factors be set to 1 on a single-broker Docker setup?
Answer: Internal topics such as __consumer_offsets and __transaction_state default to 3 replicas. A cluster with one broker cannot place three replicas, so the topics are never created: consumer groups cannot find a coordinator and transactional producers fail. Setting KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR and the transaction-state settings to 1 makes the single broker usable. A three-node cluster should keep 3.
Q. What is CLUSTER_ID used for in the apache/kafka image, and what happens if you change it?
Answer: On first start the image formats the storage directory with this cluster ID, as kafka-storage.sh format would. The ID is written into the metadata files on disk. If the container later starts with a different ID but the same volume, the node refuses to start because the stored data belongs to another cluster. Keep the ID stable, or delete the volume when you really want a fresh cluster.
Tricky and scenario questions
Q. A Spring Boot app on a laptop connects to Kafka in Docker but fails with "could not resolve broker". The bootstrap server is localhost:9092. What is wrong?
Answer: The bootstrap connection worked, but the broker advertised an internal address such as broker:19092 for the listener the app reached, and the laptop cannot resolve broker. The fix is in the broker configuration, not the app: the listener published on port 9092 must advertise localhost:9092, and a separate listener should advertise the container name for clients inside Docker.
Q. Your team’s integration tests use a shared Kafka container started with Docker Compose, and tests fail randomly when run in parallel. What would you change?
Answer: The tests share topics, consumer groups and leftover data, so they interfere with each other. Start an isolated broker per test run with Testcontainers (or Spring’s embedded Kafka), use unique topic and group names per test, and wait for records with a timeout instead of fixed sleeps. Keep the Compose file for local manual development, where a long-lived broker is useful.