Running Kafka Locally
This setup uses the official Kafka 3.9.1 image apache/kafka:3.9.1 in KRaft (Kafka Raft — Raft-based metadata management that replaces ZooKeeper) mode: a single node plays both broker and controller, so there is no ZooKeeper and no JDK (Java Development Kit) on the host — everything runs inside the container.
Data lives in the host directory ~/kafka-demo/data (configurable), so it survives container restarts and removal and can be inspected and backed up directly. The only purpose of this setup is a local cluster for functional verification and debugging; do not put real data on it. Concepts and selection are covered in Kafka Concepts and When to Use It.
Prerequisites
| Item | Requirement | Notes |
|---|---|---|
| Docker | Docker Desktop / Engine | Docker Desktop is recommended on macOS |
| Memory | At least 2 GB for Docker | The broker uses about 1 GB of heap, the rest is page cache |
| Port | Host port 9092 free | 9093 is the controller port inside the container and is not published |
| Java | Not needed | Bundled in the image |
| Disk | 5 GB+ recommended | Data lives in ~/kafka-demo/data; the default retention is 7 days, so logs keep growing |
Install Docker
On macOS install Docker Desktop with Homebrew:
brew install --cask docker-desktop
open -a Docker
# wait for Docker Desktop to finish its first start and authorization
docker infoOn Linux install Docker Engine:
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"usermod changes group membership, which takes effect after you log in again; run newgrp docker in the current terminal to enter a new shell immediately. Confirm the daemon is usable:
docker infoOption 1: one docker run
Create the data directory first, then start the container:
mkdir -p ~/kafka-demo/data
docker run -d \
--name kafka-demo \
--restart unless-stopped \
-p 9092:9092 \
-v ~/kafka-demo/data:/var/lib/kafka/data \
-e CLUSTER_ID=4L6g3nShT-eMCtK--X86sw \
-e KAFKA_NODE_ID=1 \
-e KAFKA_PROCESS_ROLES=broker,controller \
-e KAFKA_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 \
-e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 \
-e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \
-e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER \
-e KAFKA_INTER_BROKER_LISTENER_NAME=PLAINTEXT \
-e KAFKA_CONTROLLER_QUORUM_VOTERS=1@localhost:9093 \
-e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 \
-e KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 \
-e KAFKA_NUM_PARTITIONS=3 \
-e KAFKA_AUTO_CREATE_TOPICS_ENABLE=true \
-e KAFKA_LOG_DIRS=/var/lib/kafka/data \
--health-cmd '/opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list >/dev/null 2>&1 || exit 1' \
--health-interval 10s \
--health-timeout 10s \
--health-retries 10 \
--health-start-period 30s \
apache/kafka:3.9.1The important settings, one by one:
| Setting | Value | Purpose |
|---|---|---|
--name / --restart | kafka-demo / unless-stopped | fixed container name, restarted with Docker |
-p | 9092:9092 | host clients connect on 9092 |
-v | ~/kafka-demo/data:/var/lib/kafka/data | data in a host directory, survives container recreation and is easy to back up |
CLUSTER_ID | fixed string | KRaft cluster id, used to format the storage directories |
KAFKA_NODE_ID | 1 | node id |
KAFKA_PROCESS_ROLES | broker,controller | one node plays both roles, no ZooKeeper needed |
KAFKA_CONTROLLER_QUORUM_VOTERS | 1@localhost:9093 | single-node quorum has only itself |
KAFKA_LISTENERS | PLAINTEXT://:9092, CONTROLLER://:9093 | clients on 9092, controller on 9093 |
KAFKA_ADVERTISED_LISTENERS | PLAINTEXT://localhost:9092 | the address clients get back; wrong value means no connection |
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR | 1 | must be 1 on a single node |
KAFKA_TRANSACTION_STATE_LOG_* | 1 / 1 | replication factor and min ISR for transaction topics, same reason |
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS | 0 | skips the initial consumer-group rebalance wait for faster local runs |
KAFKA_NUM_PARTITIONS | 3 | default partition count for auto-created topics |
KAFKA_AUTO_CREATE_TOPICS_ENABLE | true | convenient for demos, disable in production |
KAFKA_LOG_DIRS | /var/lib/kafka/data | exactly the mount point of the host directory |
--health-cmd runs kafka-topics.sh --list inside the container: listing topics proves the broker can really serve. Combined with docker inspect you can wait for healthy before running clients and avoid the false failure of "connected but the broker is not ready".
The most common mistake is
ADVERTISED_LISTENERS: a client connects to 9092 for metadata, and the broker address returned by that metadata is the advertised one. If it contains a container-internal hostname, a client on the host tries to resolve an address that does not exist, which shows up as "connects but always times out".
Option 2: manage it with Makefile and the script
Reading the raw command once is enough; day to day use the Makefile shipped with the demo project. Assuming the repository is cloned locally, run the following commands in the demo project directory:
git clone https://github.com/zq-xu/zq-xu.github.io.git
cd zq-xu.github.io/docs/public/demos/kafkaStart, stop and restart with make targets; each target maps to one operation of scripts/kafka.sh:
make kafka-up # create the container if missing, wait until healthy
make kafka-status # container status, ports and data dir
make kafka-logs # follow the broker log (first step when debugging)
make kafka-down # stop the container, keep the data dir
make kafka-restart # stop + start
make kafka-reset # remove the container and the data dir for a clean state| Target | Behavior | Data |
|---|---|---|
make kafka-up | create the container if missing, start and wait for healthy | reads/writes ~/kafka-demo/data |
make kafka-down | stop the container | kept |
make kafka-restart | stop then start | kept |
make kafka-reset | remove the container and the data dir | wiped |
make help lists every target, including the Golang verification commands. The underlying script ./scripts/kafka.sh offers the same operations with environment overrides (KAFKA_IMAGE, KAFKA_PORT, KAFKA_CONTAINER, KAFKA_DATA_DIR, CLUSTER_ID) — no need to edit the file:
KAFKA_PORT=19092 KAFKA_DATA_DIR=$HOME/kafka-test/data ./scripts/kafka.sh startThe result matches make kafka-up, only the container name, port and data directory are custom.
Verification
Three checks, from "the container runs" to "it can read and write":
# 1. the container is running and healthy
docker ps --filter name=kafka-demo
docker inspect -f '{{.State.Health.Status}}' kafka-demo # expect healthy
# 2. the broker answers metadata requests
docker exec kafka-demo /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --list
# 3. smoke-test create, produce and consume with the bundled CLI (command-line interface)
docker exec kafka-demo /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --create --topic quickstart --partitions 3
printf 'hello\nkafka\n' | docker exec -i kafka-demo /opt/kafka/bin/kafka-console-producer.sh \
--bootstrap-server localhost:9092 --topic quickstart
docker exec kafka-demo /opt/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 --topic quickstart --from-beginning \
--max-messages 2 --timeout-ms 10000
docker exec kafka-demo /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --delete --topic quickstartReading back the two lines you just wrote proves that the create topic → produce → consume path works on this machine. Consumer groups, offsets and partitions can then be used step by step following Connecting and Using Kafka with Golang.
Data persistence and container lifecycle
Data lives in the host directory ~/kafka-demo/data (KAFKA_DATA_DIR overrides it); the container only reads and writes that directory:
| Operation | Data | Notes |
|---|---|---|
make kafka-down / make kafka-up | kept | the container stops, the directory stays |
docker rm then recreate | kept | the logs stay as long as the data directory is unchanged |
make kafka-reset | wiped | removes container and data dir; the next start is a fresh cluster |
| Image upgrade | kept | the same directory works with a newer version; downgrade across majors is not advised |
Backing up means copying that directory:
cp -a ~/kafka-demo/data ~/kafka-demo/data-backupTo migrate data from the old named volume (kafka-demo-data) into the host directory, copy it once:
docker run --rm -v kafka-demo-data:/from -v "$HOME/kafka-demo/data":/to alpine cp -a /from/. /to/
docker volume rm kafka-demo-dataCommon issues
| Symptom | Likely cause | How to check |
|---|---|---|
port is already allocated | something else uses 9092 | lsof -i :9092, or change KAFKA_PORT |
Container stays unhealthy | internal topics not created, disk full, not enough memory | ./scripts/kafka.sh logs |
| Connects but requests always time out | ADVERTISED_LISTENERS is not localhost:9092 | docker inspect and read the environment |
Client reports NOT_LEADER_FOR_PARTITION | stale metadata, common right after topic creation | retry, or run --describe once |
| Slow image pull | network or registry mirror | configure a Docker mirror or change network |
| Fails to start on Apple Silicon | wrong architecture pulled | confirm you use the multi-arch apache/kafka:3.9.1 |
Permission denied on Linux | the image runs as uid 1000, data dir ownership mismatch | sudo chown -R 1000:1000 ~/kafka-demo/data and retry |
Differences from production
| Item | This local demo | Production advice |
|---|---|---|
| Nodes | 1 (broker and controller in one process) | at least 3 brokers + 3 controllers |
| Replication factor | 1 | 3 (min.insync.replicas=2) |
| Topic auto-creation | true | false, created centrally by the platform |
| Security | PLAINTEXT (no auth, no encryption) | SASL_SSL (SASL auth + TLS) or mTLS (mutual TLS) |
| Monitoring | none | lag, ISR shrink, UnderReplicatedPartitions, disk watermark |
| Retention | 7 days by default | value and capacity driven, tiered storage if needed |
This local setup exists for functional verification and debugging only; do not run real data on it.
With the cluster ready, connect and use production, consumption, consumer groups and offsets by following Connecting and Using Kafka with Golang.

