[英]Accessing IP address of a docker container in a custom network
I am using docker compose to start kafka and zookeeper 我正在使用docker compose启动kafka和zookeeper
my docker-compose is as follows: 我的码头工人组成如下:
version: '3'
services:
zookeeper:
image: zookeeper:3.4
networks:
- pipeline
kafka:
image: ches/kafka
networks:
- pipeline
environment:
- ZOOKEEPER_IP=zookeeper
ports:
- "9092:9092"
links:
- zookeeper:zookeeper
depends_on:
- zookeeper
networks:
pipeline:
So this starts a container running zookeeper and starts a container running kafka server which successfully connects to zookeeper. 因此,这将启动运行Zookeeper的容器并启动运行Kafka服务器的容器,该服务器成功连接到Zookeeper。
Additionally I can successfully create a kafka producer and a kafka consumer to communicate between each other by the following commands: 另外,我可以成功创建kafka生产者和kafka使用者,以通过以下命令相互通信:
Producer: 制片人:
docker run --rm -it --network pipeline_pipeline ches/kafka \
kafka-console-producer.sh --topic pipeline-dev \
--broker-list kafka:9092
Consumer: 消费者:
docker run --rm --network pipeline_pipeline ches/kafka \
kafka-console-consumer.sh --topic pipeline-dev \
--from-beginning \
--bootstrap-server kafka:9092
Now the problem I am facing is that in the config the ADVERTISED HOST on the kafka server is set to kafka
, which prevents me from connecting to the kafka server from local. 现在我面临的问题是,在配置中,kafka服务器上的ADVERTISED HOST设置为
kafka
,这阻止了我从本地连接到kafka服务器。
I am using the kafka-python library to connect to kafka in the following way: 我正在使用kafka-python库以以下方式连接到kafka:
from kafka import KafkaConsumer
consumer = KafkaConsumer('pipeline-dev', bootstrap_servers='localhost:9092')
print 'starting to listen'
for msg in consumer:
print msg
But here I get the error that Brokers are not available! 但是在这里,我得到一个错误,即经纪人不可用! That is because I have set the bootstrap servers as
localhost:9092
. 那是因为我将引导服务器设置为
localhost:9092
。 Even though I have forwarded the ports, I am unable to connect to the kafka server because the advertised host name is kafka
and not localhost
. 即使转发了端口,我也无法连接到kafka服务器,因为公布的主机名是
kafka
而不是localhost
。
Setting bootstrap servers as kafka:9092
does not work because the code is running in local and not in the docker network. 将引导程序服务器设置为
kafka:9092
不起作用,因为代码在本地而不是在docker网络中运行。
I am not sure how to solve this problem. 我不确定如何解决这个问题。
Make a host entry in your /etc/hosts
like below 如下所示在
/etc/hosts
创建主机条目
127.0.0.1 kafka
Above will work when you want to use your code on the docker host machine. 当您想在Docker主机上使用代码时,以上方法将起作用。 If you want to use it on some other machine then you should use
如果要在其他计算机上使用它,则应使用
<DockerHostIP> kafka
Basically you want to have the name resolved when the advertised name returns kafka
基本上,您希望在广告名称返回
kafka
时解析名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.