Debug PHP with XDebug and VSCode (docker edition)

If you are using Docker you will want to add this to your Dockerfile (runs when container being created).

RUN pecl install -f xdebug-2.9.8 \
&& rm -rf /tmp/pear \
&& echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" > /usr/local/etc/php/conf.d/xdebug.ini;

Xdebug configuration

You can tweak the Xdebug configuration on file docker-compose.yml:

The laravel container definition has an environment variable for this purpose

- XDEBUG_CONFIG=remote_host=mysite.docker.laravel remote_port=9000 remote_enable=1 remote_autostart=1 default_enable=1 idekey=VSCODE remote_connect_back=1

Adjust it, in particular the idekey should match the key set in your IDE.

VSCode setup

On VS Code we can use the PHP Debug plugin, once installed we can go to the Debug panel (Ctrl+Shift+D).

  • Select Add configuration in the the dropdown at the top-right of the panel.
  • In VSCode open the menu Run/Add Configuration, it opens launch.json. launch.json should looks like this:

Note that in the example below I am using port 9003 because I use portainer for docker which uses port 9000. You can see how I mapped xDegug to port 9003 here

{
    "version": "0.2.0",
    "configurations": [
        
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "pathMappings": {
                "/var/www/my-website": "${workspaceFolder}"
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9003
        }
    ]
}

Note that in some cases port 9000 may be blocked within Docker by portainer so you may need to set the internal port for xDebug to something else. In my case I use port 9003.