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.
-
Install and enable
xdebug
in thedocker/Dockerfile
:# Assuming the official php docker image RUN apt-get update \ # ... && pecl install xdebug-3.1.5 \ && docker-php-ext-enable xdebug \ # ...
-
Configure
xdebug
in a filedocker/conf.d/xdebug.ini
that will be mapped inside the containerzend_extension=xdebug [xdebug] xdebug.mode=develop,debug xdebug.client_host=host.docker.internal xdebug.start_with_request=yes
-
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
-
Install the official PHP Debug extension.
-
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 },
- Start debugging with "Listen for Xdebug" and set some breakpoint.
- Open the container url where Apache is listening and wait for the breakpoint to hit.