Hacker, Concerned Citizen and Avid Reader. Interested in politics, economy and history. Founder & CEO of Melluli Technologies. Bengaluru, India

Image

Setup XDebug with VSCode and Docker

This post describes steps to setup PHP debugging in VSCode for a docker application when using XDebug v3.x.x with caveats for MacOS.

To begin with

Assuming that you have a dockerised PHP application running with apache http server and xdebug 3.x.x installed.

Set XDebug options in docker config

The XDebug is installed and configured along with PHP in docker image. This should not be confused with any XDebug and PHP installed on your local machine as that is redundant here as the php app is being run inside a docker container. Note that these instructions work with xdebug 3.x.x. For older xdebug releases the configuration is different and not covered here. The below snippet should go into the Dockerfile which builds your container image -

1
2
3
4
5
6
7
8
9
RUN echo "" >> /etc/php.ini
RUN echo "[xdebug]" >> /etc/php.ini
RUN echo "zend_extension = /usr/lib64/php/modules/xdebug.so" >> /etc/php.ini
RUN echo 'xdebug.mode=debug' >> /etc/php.ini
RUN echo 'xdebug.start_with_request=yes' >> /etc/php.ini
RUN echo 'xdebug.start_upon_error=yes' >> /etc/php.ini
RUN echo 'xdebug.client_host=host.docker.internal' >> /etc/php.ini
RUN echo 'xdebug.discover_client_host=true' >> /etc/php.ini
RUN echo 'xdebug.client_port=9000' >> /etc/php.ini

Most important above is the client_host. It is host.docker.internal for Windows users but your actual internal IP of the host in case of MacOS (usually 192.168…). Apparently using host.docker.internal works for PHPStorm IDE on MacOS but not VSCode (too bad)! I have no idea why!

Install PHP Debug extension in VSCode

The one by Felix Becker works well.

Create a debug configuration in VSCode

1
2
3
4
5
6
7
8
9
{
   "name": "Listen for Xdebug",
   "type": "php",
   "request": "launch",
   "port": 9000,
   "pathMappings": {
         "/var/www/html" : "${workspaceFolder}"
   }
}

Note the pathMappings to map the deployed php code path in docker to code path of the app in VSCode (workspaceFolder VSCode variable has this value fortunately for us). This is very important!

Run and Test

Start the docker container and add some break points in VSCode. Start the PHP debugger in VSCode and run the application in a browser to catch the break points if all goes well.

Troubleshooting

  • Make sure your docker configuration installs xdebug 3.x.x
  • Update the IP address in case of MacOS in the docker configuration and then rebuild the docker image
  • Make sure VSCode debug configuration has pathMappings set correctly.

Adios…