There are multiple ways to do this. But before we look into it there are two problems in your approach that you need to understand
zookeper
host is not reachable when you use docker run
as each of the containers is running in a different network isolation
kafka
may start and try to connect to zookeeper
but zookeeper
is not ready yet
Solving the network issue
You can do a lot of things to fix things
use --net=host
to run both on the host network
use docker network create <name>
and then use --net=<name>
while launching both the containers
Or you can run your kafka container on the zookeeper
containers network.
use --net=container:zookeeper
when launching kafka
container. This will make sure zookeeper
host is accessible. This is not recommended as such, until unless you have some strong reason to do so. Because as soon as zookeeper
container goes down, so will be the network of your kafka
container. But for the sake of understanding, I have put this option here
Solving the startup race issue
Either you can keep a gap between starting zookeeper
and kafka
, to make sure that when kafka
starts zookeeper
is up and running
Another option is to use --restart=on-failure
flag with docker run. This will make sure the container is restarted on failure and will try to reconnect to zookeeper
and hopefully that time zookeeper
will be up.
Instead of using docker run
I would always prefer the docker-compose
to get such linked containers to be run. You can do that by creating a simple docker-compose.yml
file and then running it with docker-compsoe up
version: "3.4"
services:
zookeeper:
image: confluent/zookeeper
environment:
- ZOOKEEPER_CLIENT_PORT=2181
kafka:
image: confluent/kafka
environment:
- KAFKA_ADVERTISED_HOST_NAME=kafka
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
- KAFKA_CREATE_TOPICS=testtopic:1:1
depends_on:
- zookeeper
restart: on-failure
confluentinc/kafka
and Zookeeper . Also, please use Docker compose and read this blog rmoff.net/2018/08/02/kafka-listeners-explained – Theresaconfluentinc/kafka
andconfluentinc/zookeeper
– Panlogism