1.创建 docker-compose.yml
创建一个名为 docker-compose.yml 的文件,并添加以下内容:
bash
version: '3.6'
services:
zookeeper:
image: zookeeper:3.6
container_name: zookeeper
ports:
- "2181:2181"
networks:
- kafka-network
environment:
ZOO_STANDALONE_ENABLED: "true"
kafka:
image: bitnami/kafka:3.6
container_name: kafka
depends_on:
- zookeeper
ports:
- "9092:9092"
environment:
KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9092,OUTSIDE://localhost:9092
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT
KAFKA_LISTENERS: INSIDE://0.0.0.0:9092,OUTSIDE://0.0.0.0:9093
KAFKA_LISTENER_NAME: INSIDE
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE
networks:
- kafka-network
networks:
kafka-network:
driver: bridge
2.启动服务
运行以下命令来启动 Zookeeper 和 Kafka 服务:
bash
docker compose -f docker-compose.yml up -d
此处会拉取镜像 耐心等待...
3.验证
3.1检查 Zookeeper 和 Kafka 容器是否正常运行:
bash
docker ps
3.2通过 docker-compose logs 查看服务的日志,确保没有错误:
bash
docker compose logs
3.3使用 docker exec 进入容器,并测试它们之间的连接:
bash
docker exec -it kafka bash
curl http://zookeeper:2181
bash
docker exec -it zookeeper bash
curl http://kafka:9092
4.测试数据
bash
docker exec -it kafka bash
在Kafka容器创建主题:
bash
kafka-topics.sh --create --topic test --partitions 1 --replication-factor 1 --bootstrap-server kafka:9092
执行创建生产者命令:
bash
kafka-console-producer.sh --broker-list localhost:9092 --topic test
在新的终端窗口中 再次进入Kafka容器 执行创建消费者命令:
bash
docker exec -it kafka bash
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
如看到消息 代表成功