V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Rebron1900
V2EX  ›  问与答

请问在 wsl2 里创建的 docker 容器怎么访问宿主机?

  •  
  •   Rebron1900 · 2022-11-03 13:59:18 +08:00 · 1682 次点击
    这是一个创建于 512 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大佬们好。

    我在宿主机 8000 端口上拉了个服务, 然后 wsl2 里拉个 docker 容器,网络模式为 --net=host ,但是目前在容器里使用 python 请求宿主机会提示错误。

    嵌套为:宿主机 win11 》 wsl2 》 docker 内

    测试脚本为:

    import requests
    html = requests.get('http://host.docker.internal:8000')
    print(html.text)
    

    提示的错误信息为:

    
    Traceback (most recent call last):
      File "/usr/local/lib/python3.11/site-packages/urllib3/connection.py", line 174, in _new_conn
    
        conn = connection.create_connection(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/local/lib/python3.11/site-packages/urllib3/util/connection.py", line 72, in create_connection
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/local/lib/python3.11/socket.py", line 961, in getaddrinfo
        for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    socket.gaierror: [Errno -2] Name does not resolve
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 703, in urlopen
        httplib_response = self._make_request(
                        
        r = adapter.send(request, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/local/lib/python3.11/site-packages/requests/adapters.py", line 565, in send
        raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPConnectionPool(host='host.docker.internal', port=8000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f874bbd4490>: Failed to establish a new connection: [Errno -2] Name does not resolve'))
    
    

    试过再 wsl2 里访问宿主网络,也无法访问。

    请问要用什么姿势操作才能让宿主机、wsl2 、wsl2 里的 docker 正常网络互通呢?

    2 条回复    2022-11-03 14:47:59 +08:00
    swulling
        1
    swulling  
       2022-11-03 14:06:11 +08:00
    Rebron1900
        2
    Rebron1900  
    OP
       2022-11-03 14:47:59 +08:00
    @swulling 感谢您的回复,我宿主机的服务发布在 127.0.0.1 上,所以导致容器无法访问。后来改成发到本地局域网 ip 上后能正常访问了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3058 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:00 · PVG 19:00 · LAX 04:00 · JFK 07:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.