How to include IP of Docker host in docker-compose.yml?

Viewed 2134

I want to include support for Xdebug in a PHP Docker container, however as part of this, I need to specify the IP of the Windows machine running the Docker container via XDEBUG_CONFIG=remote_host=${HOST_IP} - Currently HOST_IP is manually specified in a .env file, but I'd like to automate this to reduce the setup steps for other users.

My problem is that I can't seem to find a way to easily determine the IP of the host machine. It also needs to work on both Windows and Linux Docker hosts, as not all users use Windows as their desktop environment. I also can't use ${HOSTNAME}, as this fails to resolve in DNS.

Does anyone have any suggestions on how to achieve this?

EDIT2: Updating this answer for the newer versions of Docker: From 18.03 onward, Docker For Windows and other Docker platforms have been updated to include a cross-platform hostname for their Docker host, host.docker.internal - which is bloody helpful.

1 Answers

You might try a formatted docker info: https://docs.docker.com/engine/reference/commandline/info/#format-the-output

docker info --format '{{json .}}'
docker info --format '{{json .path.to.ip}}'

E.g. in a (single-host) Docker Swarm you can get the host ip by:

docker info --format '{{json .Swarm.NodeAddr}}'

Via command substition stored in a variable:

docker_host_ip=$(docker info --format '{{json .Swarm.NodeAddr}}')

I could not try it on on Windows or on Docker without Swarm ... but docker info should work across platforms.

Update (according to comments below):
Not really (syntactically) "beautiful" you can use --format {{index path arrayIndex "Key"}} with docker network inspect and access the first element of an array (index 0) and then access the map inside this array via its key ("Gateway"):

docker network inspect docker_dockernet --format '{{index .IPAM.Config 0 "Gateway"}}'
Related