PHP: Docker and Xdebug (v3) with no performance loss

Mike
3 min readDec 11, 2020

Flip between non xdebug local dev (much fast) to xdebug local dev (not fast but much insights) at the flick of a cookie (single click via xdebug browser extension)

— by @jenko

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

Docker compose example (docker-compose.yml)

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

Nginx map and resolver example (nginx.conf)

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

(xdebug.ini)
(.env)

PhpStorm setup is fairly straightforward. To get the demo repo working please make sure the setup is matching what’s on the screenshots:

Note: Port has changed in v3 from 9000 to 9003

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.

xdebug helper for firefox, config example

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

--

--

Mike

@glasgowphp co-organizer. Winter swimming at Loch Lomond. I enjoy music | sailing | skiing & a good drive.