Debug a PHP application running in Docker with VS Code and Xdebug
I don’t have much experience with PHP. Working on a pet project, I used Docker to do the heavy lifting of setting up a development environment for me. But I struggled to find a good resource on how to setup up step by step debugging. So where is how I ended up doing it, hope it helps someone!
Setup your container
Xdebug is a PHP extension that needs to be installed on your container. We need install and set it up inside our Docker container so that it can connect to a debug client running on the host machine.
Configure PHP to use Xdebug and enable remote debugging
Create a config file named xdebug.ini
that we will copy into Docker’s /usr/local/etc/php/conf.d
.
Here is a sample one:
1 | zend_extension=xdebug |
For more details see docs here.
Notice that we are setting host.docker.internal
as host of our debug client. We will define this host when we run our container.
Error reporting config
Create a error reporting config file error_reporting.ini
with following content:
1 | error_reporting=E_ALL |
We will also copy this into Docker’s /usr/local/etc/php/conf.d
.
Install and enable Xdebug
Create or update your Dockerfile
to install Xdebug and copy over the files created above.
Depending on your image, you might need to change how you install Xdebug.
Example:
1 | # syntax=docker/dockerfile:1 |
Notice that we are enabling Xdebug with docker-php-ext-enable
. You might need to restart your webserver to reload the settings.
Start your container
We need to make sure our container can communicate with the host via host.docker.internal
. This won’t work automatically, we need to provide the following run flag:
1 | --add-host=host.docker.internal:host-gateway |
Alternatively we can do so using docker-compose
and extra_hosts
.
For example:
1 | version: '3.1' |
Install an Extension (PHP Debug Adapter) in VS Code
Now we need a debug adapter between VS Code and Xdebug.
We will use PHP Debug. To install in VS Code: Press F1, type ext install php-debug
and hit enter key.
Configure VS Code to map files on host
To make VS Code map the files on the Docker container to the right files on our host, we have to set the pathMappings
settings in our .vscode/launch.json
.
A sample one:
1 | { |
See the docs to learn more about the launch settings.
Now go debug!
Now go set up some break points in you code (mapped above in pathMappings
) and start the “Launch” from VS Code’s debugger and hit the green play button!
Debug a PHP application running in Docker with VS Code and Xdebug
https://mehamasum.github.io/blog/2021/9/xdebug-vscode-docker/