How to xdebug when your PHPStorm runs with xserver inside WSL2, but you use Docker Desktop on windows 10
Once you know whats happening, its not that scary.
the hard part (networking)
a) Your container will run in the (bridged) docker network on the windows host. You just call docker commands on the docker daemon from within the WSL2. So WSL2 is a client to the docker daemon on the windows host
b) when your IDE is within the WSL2, then its opening a port on the WSL2 machine that is connected via the vEthernet connection on the host. You get this machine with (run this command on the windows host):
wsl hostname -I
e.g. 172.26.153.65.
Now, when you configure xdebug in your php container, that runs on docker desktop and you reference host.docker.internal as the xdebug.client_host (and lets say xdebug.client_port = 9000), then the php-cli/fpm within the container tries to connect to the windows host….
But there is no IDE listening on port 9000, right?
Easiest thing I found is to portforward that to the WSL2 instance (your windows host becomes a nat-router from the traffic from the docker network to the wsl2-network)
netsh interface portproxy set v4tov4 listenport=9000 listenaddress=0.0.0.0 connectport=9000 connectaddress=172.26.153.65
(execute this in an elevated power shell)
Now try if it works. Enable your debug log, if things do not work too well. I could use this without any other firewall rules.
The easy part
Is to install and configure xdebug on the official docker php image:
exec into your container as root (or do this in a derived image):
pecl install xdebug && docker-php-ext-enable xdebug
lets see, where we need to go:
php --ini
With your favorite editor: zile /usr/local/etc/php/conf.d/xdebug.ini
[xdebug]
xdebug.mode=debug
xdebug.client_host=host.docker.internal
xdebug.client_port=9000
xdebug.start_with_request=yes
(note that docker-php-ext-enable xdebug did already enable xdebug in docker-php-ext-xdebug.ini)
Path mappings
When you run in docker, the directory of your project might not map exactly, to the directory within the docker image. Lets’ assume your docker directory is /app and your local path is something like /home/psc/yay/web
in phpstorm go to settings —PHP — servers:
And then set in your environment for the running container (e.g. with docker compose)
myservice:
image: xxx
environment:
PHP_IDE_CONFIG: "serverName=web"
or set it with export. That way phpstorm knows which Server under PHP -> Servers to lookup for you and map the paths.