Enable VSCode Step Debugging with Xdebug on PHP running in Docker


I am using https://github.com/a2way-com/drop-in-docker-php as the base for this example. But you should be able to do the same on environments configured in any other way.

Step 1: Enable Xdebug in the container

Add the following line to the Dockerfile for the container that runs PHP (app.Dockerfile files, if you are using A2Way Drop-in-Docker PHP.).

RUN apk add --no-cache $PHPIZE_DEPS linux-headers && pecl install xdebug && docker-php-ext-enable xdebug

Step 2: Enable host.docker.internal

This step should not be required if you are using Docker Desktop, as it has this enabled by default. If you use Docker on MacOS or Windows, you are using Docker Desktop, and you should already have this. Just run ping host.docker.internal to make sure.

Add the following lines to docker-compose.yml for the container that runs PHP (app service, if you are using A2Way Drop-in-Docker PHP.).

  extra_hosts:
   - host.docker.internal:host-gateway

Step 3: Create INI file for Xdebug

Create a file with the following content in your PHP container’s /usr/local/etc/php/conf.d/xdebug.ini location.

xdebug.mode = debug
xdebug.start_with_request = yes
xdebug.client_host = host.docker.internal

If you are using A2Way Drop-in-Docker PHP, create the file in <Drop-in-Docker PHP Root>/fs/app/usr/local/etc/php/conf.d/xdebug.ini and add the following line to app.Dockerfile.

COPY ./fs/app/ /

Step 4: Install VSCode Extension

https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug

Step 5: Configure VSCode Debug Runner

Create the file .vscode/launch.json with following content, or append the content appropriately if the file is already there. Change pathMappings to match how your files’ paths in container and host.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}/src",
            },
        },
    ]
}

Step 6: Debug!

Choose “Run and Debug” from VSCode sidebar, or “Run -> Start Debugging” from menu. Set some breakpoints in your code. Go to the browser and run the part of the code you are debugging. You should be hitting your breakpoints.

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *