Debug PHP with VS Code and Docker

Debugging PHP with Xdebug using VS Code as your IDE. These are the step-by-step instructions on how I got Xdebug working with VS Code and Docker.

This post was inspider by a specific stackoverflow comment. It was really helpful to getting this setup working as I needed it.

Install Xdebug

You need to have Xdebug installed on your machine. Official installation guide can be found on Xdebug's official website. You can install Xdebug through PECL on Linux & macOS. You can install Xdebug with PECL with:

1pecl install xdebug

Configure your php.ini file

When you have installed Xdebug, you need to configure your php.ini to use Xdebug. These are the exact settings for Xdebug in my php.ini file:

1[xdebug]
2zend_extension=/usr/local/Cellar/php/7.3.7/pecl/20180731/xdebug.so
3xdebug.default_enable=1
4xdebug.remote_enable=1
5xdebug.remote_port=9000
6xdebug.remote_handler=dbgp
7xdebug.remote_connect_back=0
8xdebug.remote_host=host.docker.internal
9xdebug.idekey=VSCODE
10xdebug.remote_autostart=1
11xdebug.remote_log=/usr/local/etc/php/xdebug.log

Most importantly you need to add the location of your xdebug.so file. Without it this will not work at all.

PHP Debug extension for VS Code

You need to install PHP Debug for VSCode. This extension is a debug adapter between VS Code and XDebug and will make debugging PHP with Xdebug possible.

VS Code debugger launch.json configurations for PHP

These are the exact settings for debuggin PHP with docker and VS Code in my launch.json file:

1{
2 "name": "Listen for XDebug",
3 "type": "php",
4 "request": "launch",
5 "port": 9000,
6 "log": true,
7 "externalConsole": false,
8 "pathMappings": {
9 "/app": "${workspaceFolder}",
10 },
11 "ignore": [
12 "**/vendor/**/*.php"
13 ]
14},

Most importantly you need to map your docker path in pathMappings.

Example: My app resides in the /app directory in the docker container. ${workspaceFolder} is the path of the folder opened in VS Code, meaning the project root path.

Browser extension: Xdebug helper

A must have for everyone thats debugging, profiling and tracing PHP code with Xdebug. This extension will help you to enable/disable debugging, profiling and tracing easily, instead of juggling around with POST/GET variables or cookies.

Chrome and Firefox versions available.

Configuring docker

I needed to add XDEBUG_ENABLE and DOCKERHOST lines under x-environment in my docker-compose.yml file. Like this:

1x-environment:
2 &default-environment
3 XDEBUG_ENABLE: "true"
4 DOCKERHOST: host.docker.internal