This article is updated for xdebug v3, if you are using xdebug v2, head to the old one.
All code examples can be found in a demo repository on github: https://github.com/strayobject/php-xdebug-docker
For some projects, developing with Xdebug running on every request is an acceptable solution — especially on Linux, where there are little to no performance penalties for running Docker. In most cases though it is better to be able to enable Xdebug selectively.
In a typical Docker PHP setup we would have 1 Nginx/Apache container
and 1 PHP container (with Xdebug).
In our setup we are still running 1 Nginx container, but instead of 1 PHP container we are going to split it into 2:
— one PHP container without Xdebug
— one PHP container with Xdebug
To facilitate the app container selection we are using Nginx map.
Code available at https://github.com/strayobject/php-xdebug-docker/blob/master/docker/nginx/nginx.conf#L5
What this does is it makes nginx read the cookie with a name of XDEBUG_SESSION
and assign the matching value to $fastcgi_pass
variable.
If the cookie value is pxd, variable will hold app_xdebug
otherwise it will be app
. This variable is used further down in configuration:
fastcgi_pass $fastcgi_pass:9000;
https://github.com/strayobject/php-xdebug-docker/blob/master/docker/nginx/nginx.conf#L67
Our xdebug.ini is populated via env vars
PhpStorm setup is fairly straightforward. To get the demo repo working please make sure the setup is matching what’s on the screenshots:
Now, all that is left is to add a browser extension to your browser and set it up.
There is a list of available xdebug browser extensions on a page from JetBrains:
https://www.jetbrains.com/help/phpstorm/browser-debugging-extensions.html
In the example below I’m using Xdebug Helper for Firefox.
And that’s it folks. You can now enjoy a fast application when not debugging and a wealth of info when required.
If you do not want to run two containers or add extensions to your browser, there is an alternative way of of turning xdebug on when needed. It involves restarting your containers and you can find more info about here:
https://twitter.com/HerndlMartin/status/1335215232000684032