debug php inside a docker container with vscode (on mac os)

To debug php code inside a Docker container using VSCode as your IDE, proceed as follows:

Install php and the relevant extensions using your Dockerfile like so:

RUN yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm \
    && yum -y install yum-utils \
    && yum-config-manager --enable remi-php72 \
    && yum -y install \
        php \
        php-fpm \
        php-cli \
        php-mysql \
        php-xdebug \
    && yum clean all \
    # Create xdebug log
    && mkdir /var/log/xdebug \
    && touch /var/log/xdebug/xdebug.log

Add the following xdebug config and copy it over to your image like so:

; Enable xdebug extension module
zend_extension=xdebug.so

xdebug.mode=debug
; This only works for Docker for Mac sadly.
; I will try to find a remote_connect_back variant in the future
xdebug.client_host=host.docker.internal
xdebug.start_with_request=yes

Please note specifically: The client_host “host.docker.internal” is a Docker for Mac specific thing. It supposedly does not exist for other Docker setups:

“The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.” (https://docs.docker.com/desktop/mac/networking/)

Add a launch config in VSCode (adjust path mapping according to your paths inside the Docker container and on your local machine):

        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "pathMappings": {
                "/var/www/<projectname>": "${workspaceFolder}/<some path>/src"
            }
        },

Build and start your Docker container.

Add a breakpoint in your PHP script in VSCode and hit F5 to start a debug session. Then call your php script on your Docker container (i.E. using your browser and going to http://localhost/index.php (or however you reach your PHP script).

Enjoy debugging!