xDebug with Docker and PHPStorm

In order to understand how to configure xdebug with Docker in PHPStorm we should first understand how xdebug works.

If you enable xdebug in your server every time we run a script in PHP is going to send the information to the listener, the Listener in our case is PHPStorm.

Docker Image Configuration

So first we are going to prepare the Docker image installing all the Xdebug dependencies.

ENV XDEBUGINI_PATH=/usr/local/etc/php/conf.d/xdebug.ini
RUN echo "zend_extension="`find /usr/local/lib/php/extensions/ -iname 'xdebug.so'` > $XDEBUGINI_PATH
COPY xdebug.ini /tmp/xdebug.ini
RUN cat /tmp/xdebug.ini >> $XDEBUGINI_PATH
RUN echo "xdebug.remote_host="`/sbin/ip route|awk '/default/ { print $3 }'` >> $XDEBUGINI_PATH

You can change the configuration depending on your linux distribution in my case was Debian:Jessy

Now we need to create a new file xdebug-ini:

xdebug.remote_enable=on
xdebug.remote_autostart=on
xdebug.remote_connect_back=off
xdebug.remote_handler=dbgp
xdebug.profiler_enable=0
xdebug.profiler_output_dir="/var/www/html"
xdebug.remote_port=9000

The only thing which deserves an explanation here is the profiler_ouput_dir, which is the path to your code is inside the container.

Now we can build the image with:

docker build -t IMAGE_NAME .

PHPStorm

In PHPStorm we have different aspect to configure, we should start enabling XDebug.

Pressing “⌘ ,” we go to the Preference menu, in the search area we look for “xdebug” and we should configure as in the picture as follow.

In order to allow connection we need to configure the server where our code is, with “⌘ ,” again, and searching for “server”, we need to add a new one with the symbol “+”, set the name we prefer, configure the domain, and the port where our docker container is listen. Then we need to click in the option “Use path mapping …”, automatically PHPStorm is going to show the tree directory of our project, in the column “Absolute path on the server” we need to add the path of our project in the container, in my case is /var/www/html

Lastly step in the PHPStorm configuration is start listen, we just need to click in the botton “Start Listen for PHP Debug connection” in the upper part of the IDE

Docker-compose

Our composer file need to set 2 environment variables, XDEBUG_CONFIG with remote_host with our local ip address, on mac you can get it easily with this

$ cat ~/Library/Containers/com.docker.docker/Data/database/com.docker.driver.amd64-linux/slirp/host
192.168.65.1

The other variable is PHP_IDE_CONFIG, this need to be set with the server name we create in PHPStorm. Will we end up with something like this.

environment:
XDEBUG_CONFIG: "remote_host=192.168.65.1"
PHP_IDE_CONFIG: "serverName=Test"

Lastly we just run docker composer

docker-compose up -d

And this is all, now we should be able to use xdebug with PHPStorm