【问题标题】:Example to connect from container to host service从容器连接到主机服务的示例
【发布时间】:2019-11-27 14:21:59
【问题描述】:

我是 Docker 和无人机编程的新手。我能够在我的 Windows 10 上将 python 脚本(包含dronekit 代码)部署到 docker 容器。要运行脚本,我需要连接到主机上的服务。我在下面提供了一个 sn-p,Windows 有一个正在运行的程序(Mavproxy SITL),它暴露了 127.0.0.1:14550,它是 UDP。我的图片应该连接到这个地址。

mydronectrlscript.py:

from dronekit import connect

# Connect to UDP endpoint.
vehicle = connect(‘udp:127.0.0.1:14550’, wait_ready=True)
# Use returned Vehicle object to query device state - e.g. to get the mode:
print(“Mode: %s” % vehicle.mode.name)

我阅读了有关 host.docker.internal 的文档和回复: https://docs.docker.com/docker-for-windows/networking/ How to access host port from docker container

对类似问题的回复表明在 Windows/Mac 上使用 host.docker.internal 版本 18.03+。

我的问题是“如何使用”host.docker.internal?它是在 docker run 命令中传递的吗?你能分享一下它是如何使用的例子吗? 使用host.docker.internal会允许py脚本访问host的UDP 127.0.0.1:14550地址吗?

【问题讨论】:

  • 因此与localhost 连接会将您连接到容器的 localhost,而不是主机,假设我已经了解此脚本位于容器和其他服务中正在其他地方运行
  • This article 和回答 here 可能会有所帮助
  • "与 localhost 连接会将您连接到容器的 localhost,而不是主机" -> 我不是想实现这一点。来自容器的脚本连接语句 connect(‘127.0.0.1:14550’) 应该与主机的 ‘127.0.0.1:14550’ 连接。你不理解“我知道这个脚本在容器内,而其他服务在其他地方运行”是正确的,“在其他地方运行”被称为“在主机上运行”。
  • 感谢您的链接。我确实读过它们,我的问题更多的是如何做到这一点:“只需使用主机 host.docker.internal 连接到您的 mysql 服务。”

标签: python docker drone telemetry dronekit


【解决方案1】:

简单来说,对我的问题的回答是:

mydronectrlscript.py:

from dronekit import connect
# Connect to UDP endpoint.
vehicle = connect(‘udp:host.docker.internal:14550’, wait_ready=True)
# Use returned Vehicle object to query device state - e.g. to get the mode:
print(“Mode: %s” % vehicle.mode.name)

此外,如果您使用的是 Windows 10 家庭版或需要虚拟框的操作系统版本,则从我的尝试来看,这不起作用。这适用于 Windows 10 Professional 和 Mac OS。

由于这个问题与无人机编程有关: 如果您最终尝试访问 COM 端口(用于遥测),目前无法使用 Windows 操作系统中托管的 Docker 映像:https://github.com/docker/for-win/issues/1018

根据我阅读的内容,可以从 Linux 中获得:Docker - a way to give access to a host USB or serial device?

【讨论】:

    【解决方案2】:

    您要查找的端点是'http://host.docker.internal'

    在 MacO 上运行。我将在我的 macbook 上运行一个服务,只在一个 python:3.6 容器上使用基本的烧瓶,根目录中有 app.py:

    docker run -it -p 5000:5000 python:3.6 bash
    
    pip install flask
    
    python app.py
    
    # app.py
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/', methods=["GET"])
    def main():
        return {'a': 1, 'b': 2}
    
    if __name__ == "__main__":
        app.run(host='0.0.0.0', port=5000, debug=True)
    

    然后在另一个容器中运行

    import requests
    
    r = requests.get('http://host.docker.internal:5000')
    
    r.json()
    {'a': 1, 'b': 2}
    

    【讨论】:

    • 知道了,把ip地址换成host.docker.internal就好了。这就是我一直在寻找的。今晚会尝试更新。
    • 是的,就像我说的,容器中的127.0.0.1 不会映射回主机,这就是你这样做的原因。其文档为here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2023-03-23
    • 1970-01-01
    • 2021-12-20
    • 2016-01-25
    • 2018-01-09
    相关资源
    最近更新 更多