无法解析 'kafka:9092': 名称或服务未知 - docker / php-rdkafka

2022-08-30 22:07:37

我试图让php连接到kafka,所有这些都在一个docker容器中。

kafka php lib - https://github.com/arnaud-lb/php-rdkafka/

kafka docker container - https://hub.docker.com/r/wurstmeister/kafka/

一切都在构建和运行正常,但是当我尝试与PHP生产者连接时,我得到了以下内容:

httpd_1   | %3|1490816385.542|FAIL|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: kafka:9092/bootstrap: Failed to resolve 'kafka:9092': Name or service not known
httpd_1   | %3|1490816385.543|ERROR|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: kafka:9092/bootstrap: Failed to resolve 'kafka:9092': Name or service not known
httpd_1   | %3|1490816385.543|ERROR|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: 1/1 brokers are down

我在 PHP 中使用以下内容

    $rk = new RdKafka\Producer();
    $rk->setLogLevel(LOG_DEBUG);
    $rk->addBrokers("kafka");

    $topicConf = new RdKafka\TopicConf();
    $topicConf->set("message.timeout.ms", 1000);
    $topic = $rk->newTopic("DEV", $topicConf);

    $topic->produce(RD_KAFKA_PARTITION_UA, 0, "Message");

    $rk->poll(1000);
    $kafkaConf = new RdKafka\Conf();
    $kafkaConf->setErrorCb(function ($rk, $err, $reason) {
        printf("Kafka error: %s (reason: %s)\n", rd_kafka_err2str($err), $reason);
    });
    $kafkaConf->setDrMsgCb(function ($rk, $message) {
        if ($message->err) {
            print_r($message);
        } else {
            print_r("ok");
        }
    });

我玩过,试图在docker-compose.yml和PHP代码中设置主机IP,但没有乐趣。我也有,但我不知道这是好是坏?connection refused

如果它有帮助,我的docker-compose.yml

httpd:
  build: .
  ports:
  - 8180:80
  volumes:
  - ~/www:/var/www/html
zookeeper:
  image: wurstmeister/zookeeper
  ports:
  - "2181:2181"
kafka:
  build: ~/kafka-docker/.
  links:
  - zookeeper
  ports:
  - "9092:9092"
  environment:
    KAFKA_ADVERTISED_HOST_NAME: kafka
    KAFKA_ADVERTISED_PORT: 9092
    KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
  volumes:
  - /var/run/docker.sock:/var/run/docker.sock
  • PHP 版本: 7.0.17

  • librdkafka 版本: 0.9.5.0

  • php-rdkafka version: 2.0.1

我的问题:任何想法,我怎么能成功地从php连接到kafka?


答案 1

代理将使用 advertised.listeners(它似乎在该 docker 映像中用KAFKA_ADVERTISED_HOST_NAME抽象出来)来公布自己,客户端将因此尝试连接到这些播发的主机和端口。

因此,您需要确保客户端可以解析并访问此播发的主机名,例如,通过将“kafka”添加到客户端主机上的/etc/hosts。


答案 2

如果容器的主机 IP 是 ,可以在 docker 容器 env 中设置它:192.168.1.110

KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://192.168.1.110:{{ kafka_port }}"

推荐