Skip to content

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 ​

ItemRequirementNotes
DockerDocker Desktop / EngineDocker Desktop is recommended on macOS
MemoryAt least 2 GB for DockerThe broker uses about 1 GB of heap, the rest is page cache
PortHost port 9092 free9093 is the controller port inside the container and is not published
JavaNot neededBundled in the image
Disk5 GB+ recommendedData lives in ~/kafka-demo/data; the default retention is 7 days, so logs keep growing

Install Docker ​

On macOS install Docker Desktop with Homebrew:

bash
brew install --cask docker-desktop
open -a Docker

# wait for Docker Desktop to finish its first start and authorization
docker info

On Linux install Docker Engine:

bash
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:

bash
docker info

Option 1: one docker run ​

Create the data directory first, then start the container:

bash
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.1

The important settings, one by one:

SettingValuePurpose
--name / --restartkafka-demo / unless-stoppedfixed container name, restarted with Docker
-p9092:9092host clients connect on 9092
-v~/kafka-demo/data:/var/lib/kafka/datadata in a host directory, survives container recreation and is easy to back up
CLUSTER_IDfixed stringKRaft cluster id, used to format the storage directories
KAFKA_NODE_ID1node id
KAFKA_PROCESS_ROLESbroker,controllerone node plays both roles, no ZooKeeper needed
KAFKA_CONTROLLER_QUORUM_VOTERS1@localhost:9093single-node quorum has only itself
KAFKA_LISTENERSPLAINTEXT://:9092, CONTROLLER://:9093clients on 9092, controller on 9093
KAFKA_ADVERTISED_LISTENERSPLAINTEXT://localhost:9092the address clients get back; wrong value means no connection
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR1must be 1 on a single node
KAFKA_TRANSACTION_STATE_LOG_*1 / 1replication factor and min ISR for transaction topics, same reason
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS0skips the initial consumer-group rebalance wait for faster local runs
KAFKA_NUM_PARTITIONS3default partition count for auto-created topics
KAFKA_AUTO_CREATE_TOPICS_ENABLEtrueconvenient for demos, disable in production
KAFKA_LOG_DIRS/var/lib/kafka/dataexactly 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:

bash
git clone https://github.com/zq-xu/zq-xu.github.io.git
cd zq-xu.github.io/docs/public/demos/kafka

Start, stop and restart with make targets; each target maps to one operation of scripts/kafka.sh:

bash
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
TargetBehaviorData
make kafka-upcreate the container if missing, start and wait for healthyreads/writes ~/kafka-demo/data
make kafka-downstop the containerkept
make kafka-restartstop then startkept
make kafka-resetremove the container and the data dirwiped

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:

bash
KAFKA_PORT=19092 KAFKA_DATA_DIR=$HOME/kafka-test/data ./scripts/kafka.sh start

The 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":

bash
# 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 quickstart

Reading 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:

OperationDataNotes
make kafka-down / make kafka-upkeptthe container stops, the directory stays
docker rm then recreatekeptthe logs stay as long as the data directory is unchanged
make kafka-resetwipedremoves container and data dir; the next start is a fresh cluster
Image upgradekeptthe same directory works with a newer version; downgrade across majors is not advised

Backing up means copying that directory:

bash
cp -a ~/kafka-demo/data ~/kafka-demo/data-backup

To migrate data from the old named volume (kafka-demo-data) into the host directory, copy it once:

bash
docker run --rm -v kafka-demo-data:/from -v "$HOME/kafka-demo/data":/to alpine cp -a /from/. /to/
docker volume rm kafka-demo-data

Common issues ​

SymptomLikely causeHow to check
port is already allocatedsomething else uses 9092lsof -i :9092, or change KAFKA_PORT
Container stays unhealthyinternal topics not created, disk full, not enough memory./scripts/kafka.sh logs
Connects but requests always time outADVERTISED_LISTENERS is not localhost:9092docker inspect and read the environment
Client reports NOT_LEADER_FOR_PARTITIONstale metadata, common right after topic creationretry, or run --describe once
Slow image pullnetwork or registry mirrorconfigure a Docker mirror or change network
Fails to start on Apple Siliconwrong architecture pulledconfirm you use the multi-arch apache/kafka:3.9.1
Permission denied on Linuxthe image runs as uid 1000, data dir ownership mismatchsudo chown -R 1000:1000 ~/kafka-demo/data and retry

Differences from production ​

ItemThis local demoProduction advice
Nodes1 (broker and controller in one process)at least 3 brokers + 3 controllers
Replication factor13 (min.insync.replicas=2)
Topic auto-creationtruefalse, created centrally by the platform
SecurityPLAINTEXT (no auth, no encryption)SASL_SSL (SASL auth + TLS) or mTLS (mutual TLS)
Monitoringnonelag, ISR shrink, UnderReplicatedPartitions, disk watermark
Retention7 days by defaultvalue 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.

~~~ That is the end ~~~