Docker和VS Code远程容器:如何将远程Python开发容器与Kafka容器连接

时间:2020-10-24 10:10:34

标签: python docker visual-studio-code apache-kafka remote-access

我将VS Code与remote-containers扩展一起使用。

我有2个项目文件夹,每个文件夹都有自己的docker-compose文件。

  1. zookeeper / kafka(侦听端口9092)
  2. python开发容器(作为远程容器运行)

在python容器中,我有一个将消息发送到kafka容器的生产者。不幸的是,我无法从python容器中到达kafka容器。我收到以下错误:
kafka.errors.NoBrokersAvailable: NoBrokersAvailable
(如果我直接从主机运行生产者,那么它就像一个魅力!)

如何从python远程容器连接到kafka容器?

我尝试在devcontainer.json中进行端口转发和发布,但没有成功:
“ forwardPorts”:[9092]
“ appPort”:[9092] 我什至尝试了临时端口转发 转发端口>> 9092

我是docker初学者,所以我想我在这里有一个误解,如果有人可以帮助我,我将不胜感激。

谢谢!
卡洛

devcontainer.json

{
  "name": "python",
  "dockerComposeFile": ["../docker-compose.yml"],
  "service": "python",
  "workspaceFolder": "/workspace",
  "settings": {
    "terminal.integrated.shell.linux": "/bin/bash",
    "python.pythonPath": "/usr/local/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "/usr/local/bin/pylint",
    "python.formatting.autopep8Path": "/usr/local/bin/autopep8",
    "python.formatting.blackPath": "/usr/local/bin/black"
  },
  "extensions": [
    "ms-python.python",
    "coenraads.bracket-pair-colorizer",
    "wayou.vscode-todo-highlight"
  ],
  // forward ports
  "forwardPorts": [9092],
  // publish ports to the host
  "appPort": [9092]
}

producer.py

from kafka import KafkaProducer
import json
from data import get_registered_user
import time

def json_serializer(data):
    return json.dumps(data).encode('utf-8')

producer = KafkaProducer(
    bootstrap_servers=['localhost:9092'],
    value_serializer=json_serializer,
)

if __name__ == "__main__":
    while True:
        registered_user = get_registered_user()
        producer.send('registered_user', registered_user)
        print(registered_user)
        time.sleep(3)

0 个答案:

没有答案