从容器中获取 docker 网络的私有 IP 以配置 xdebug remote_host

Geting the private ip for the docker network from within the container to configure xdebug remote_host

因此,使用 docker 和 docker-compose 我喜欢提供内置于容器中的工具,这样开发团队中的其他人就不必费力地设置零碎的东西。在这种特定情况下,我在配置 xdebug 时遇到问题。从浏览器进行调试时,使用 connect back 绝对可以正常工作。但是试图让 xdebug 通过容器内的 cli 工作绝对是一场噩梦。出于某种原因,它需要(连同 remote_autostart=1)remote_host 设置指向 docker 容器所在的网络。

这是我当前的解决方案,它在我的 ~/.bashrc 中,它可以工作,但很糟糕。它假设网络 ip 只是容器 ip 但最后一位数字被 1 替换。我希望有人有更好的方法让 xdebug 工作或更好的方法来获取网络 ip。

# If xdebug doesn't get provided a remote address then it will default to this. This is the case for cli debugging. 
# This ip should be the network this container is running on
own_private=$(hostname -i | awk '{print }')
# Replaces the final number from the containers own private ip with a 1 for the network address
network="${own_private%.*}.1"
# For some reason xdebug won't work unless you give it the network ip
export XDEBUG_CONFIG="remote_host=$network"

Xdebug 设置:

[xdebug]
zend_extension=xdebug.so
xdebug.remote_enable = 1
xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.show_local_vars = 0
xdebug.var_display_max_data = 10000
xdebug.var_display_max_depth = 20
xdebug.show_exception_trace = 0
xdebug.remote_autostart=1
xdebug.idekey = "PHPSTORM"
xdebug.remote_log = /srv/www/var/log/xdebug.log
xdebug.profiler_enable = 0;
xdebug.profiler_enable_trigger = 1;
xdebug.profiler_output_dir = /srv/www/var/profiler/

可以使用默认网关的 IP 地址(即主机上 docker0 网络接口的 IP)从容器内访问主机。使用ip获取:

ip route show default | awk '/default/ {print }'