david alfonso

Debugging PHP in a Docker container

I'm migrating a local development setup from Vagrant to Docker and I've had to setup debugging to deal with some problems.

I've used xdebug, PHP's debugger, which supports remote debugging. This is needed because VS Code runs in the host machine and PHP in a Docker container.

Build Docker container with xdebug support

Note: I'm assuming a repository with a docker/ subfolder where all the Docker-related files reside.

  1. Install and enable xdebug in the docker/Dockerfile:

    # Assuming the official php docker image
    RUN apt-get update \
    # ...
    && pecl install xdebug-3.1.5 \
    && docker-php-ext-enable xdebug \
    # ...
    
  2. Configure xdebug in a file docker/conf.d/xdebug.ini that will be mapped inside the container

    zend_extension=xdebug
    
    [xdebug]
    xdebug.mode=develop,debug
    xdebug.client_host=host.docker.internal
    xdebug.start_with_request=yes
    

  3. Add alias for docker host in docker-compose.yaml because I'm on Linux.

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

Configure VS Code

  1. Install the official PHP Debug extension.

  2. Create a launch.json with the default PHP config and include a path mapping from server to host paths:

     "configurations": [
      {
       "name": "Listen for Xdebug",
       "type": "php",
       "request": "launch",
       "pathMappings": {
        "/var/www/html": "/home/username/project/html"
       },
       "port": 9003
      },
    

  3. Start debugging with "Listen for Xdebug" and set some breakpoint.
  4. Open the container url where Apache is listening and wait for the breakpoint to hit.