PHPStorm, Docker and Xdebug

I use Docker for development; on the whole, I love it; however, getting a couple of things set up proved a little challenging, namely debugging from PHPStorm with Xdebug.

Eventually, I will update my Docker quick start project on GitHub, however for now, here are some basic instructions.

We need a couple of arguments in our .env file;

 WITH_XDEBUG=true
PHP_IDE_CONFIG=serverName=[name-of-server-in-IDE]
XDEBUG_CONFIG=remote_host=host.docker.internal

Next, we update the Dockerfile

ARG WITH_XDEBUG=false

RUN if [ $WITH_XDEBUG = "true" ] ; then \
pecl install xdebug; \
docker-php-ext-enable xdebug; \
echo "error_reporting = E_ALL" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
echo "display_startup_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
echo "display_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini; \
fi ;

Finally, on the Docker side, we need to update our docker-compose file.

 services:
yourservice:
build:
args:
- WITH_XDEBUG=${WITH_XDEBUG}
env_file: .env

Set up your server, making sure to choose your debugger, Xdebug in this case. Settings -> Languages & Frameworks -> PHP -> Servers. The name of the server should match the name you set in the .env file.

Set the debug port and enable “can accept external connections”, PHPStorm, settings -> Languages & Frameworks -> PHP -> Debug, the port defaults to 9000.

Add a run/debug configuration (Run -> Edit configurations), select your server and optionally set an IDE key. To ensure everything is set correctly, you can use the validate option to check your configuration.

Start listening, add a breakpoint and away you go, you can now debug an app running in Docker.