在Mac和Windows上,可以在容器内部使用host.docker.internal (Docker 18.03+)。

Linux上是否有一种不需要传递env变量或使用各种CLI命令提取它就能开箱即用的方法?


当前回答

tldr;通过静态IP 172.17.0.1访问主机

对主机进行HTTP请求:

IP addr show | grep "\binet\b.执行以下命令获取静态IP地址。* \ bdocker0 \ b”| awk的{打印$ 2}| 1 - d ' / ' - f 添加新的IP到允许的主机 使用刚刚在请求中找到的IP地址:req = requests.get('http://172.17.0.1:8000/api/YOUR_ENDPOINT')

其他回答

host.docker.internal exists only in Windows WSL because Docker Desktop for Windows runs Docker daemon inside the special WSL VM Docker-Desktop. It has its own localhost and its own WSL2 interface to communicate with Windows. This VM has no static IP. The IP is generated every time when VM is created and passed via host.docker.internal in the generated /etc/hosts to every distro. Although there is no bridge or real v-switch all ports opened on eth0 of VM internal network are mapped on the host Local network, BUT NOT ON THE ETH0 OF THE HOST. There is no real bridge and port mapping - nothing to configure. Inside WSL VM its Localhost is the same as the localhost of the Linux machine. 2 processes inside WSL VM can communicate via localhost. Cross-distro IPC must use host.docker.internal. It is possible to create bridge inside WSL VM -Docker does it.

一种解决方案是使用特殊的容器将流量重定向到主机。您可以在这里找到这样一个容器:https://github.com/qoomon/docker-host。其思想是从容器中获取默认路由,并将其安装为传入连接的NAT网关。

一个假想的用法:

docker-host:
  image: qoomon/docker-host
  cap_add: [ 'NET_ADMIN', 'NET_RAW' ]
  restart: on-failure
  environment:
    - PORTS=999

some-service:
  image: ...
  environment:
    SERVER_URL: "http://docker-host:999"
  command: ...
  depends_on:
    - docker-host

对于linux系统,从docker引擎的主版本20.04开始,您现在也可以通过host.docker.internal与主机通信。这不会自动工作,但你需要提供以下运行标志:

--add-host=host.docker.internal:host-gateway

请点击这里查看答案:https://stackoverflow.com/a/61424570/3757139

请参见下面的答案,添加到docker-compose文件- https://stackoverflow.com/a/67158212/243392

使用docker0接口ip(比如172.17.0.1)可能是一个很好的解决方案。

只要确保您需要访问的服务侦听外部连接即可。一个典型的例子是Mysql,默认绑定到127.0.0.1,导致无法访问,直到你允许外部连接。绑定到0.0.0.0)

https://github.com/docker/for-linux/issues/264

IP=$(ip -4 route list match 0/0 | awk '{print $3}')
echo "Host ip is $IP"
echo "$IP   host.docker.internal" | sudo tee -a /etc/hosts

它会将host.docker.internal添加到您的主机。然后可以在xdebug配置中使用它。

下面是docker-compose.yml中env变量的例子

XDEBUG_CONFIG: remote_host=host.docker.internal remote_autostart=On remote_enable=On idekey=XDEBUG remote_log=/tmp/xdebug.log remote_port=9999