Skip to content

Instantly share code, notes, and snippets.

@kconde2
Forked from esilvajr/image_phpstorm_server.png
Created February 11, 2020 14:58
Show Gist options
  • Save kconde2/343f7c64636ef5d8da3f9cd4215e6311 to your computer and use it in GitHub Desktop.
Save kconde2/343f7c64636ef5d8da3f9cd4215e6311 to your computer and use it in GitHub Desktop.
How to use XDebug inside a docker container.

Introduction

When i heard about debugging in PHP:

  • "That's hard to do"
  • "Need to write debug code using var_dump() and die() functions"

And blá-blá-blá. But we don't need it.

So let's debug PHP code without writing any debug code like var_dump(), dd() or die() inside a Docker container.

Docker install

First of all, you need to have docker installed in your pc. To install docker go to docs (https://docs.docker.com/engine/installation/) and follow the steps.

Phpdocker.io

After that, we need to create a Docker container with php-fpm and xdebug extension installed. For this, we can use the phpdocker.io that automatically generates a container.

It's quite simple, go to https://phpdocker.io/generator and choose your options. The options are separated in Global, PHP, Database and Zero-config configurations.

In global you only need to choose the project name, you can use "xdebug-docker", for example. In application type config use the default option (Generic: Zend, Laravel, Lumen...), for base port use 80, or any other port that you want, in this project is (:8200) and for the max upload size, you can use the default (100MB).

For PHP configuration you can choose PHP 7.1, don't need to use Git and select the XDebug extension in Extensions tab.

In database and zero-config we don't need anything. Just let them, like they are by default.

Dockerfile and docker-compose.yml

Now we need to configure the docker-compose.yaml and Dockerfile, first open the /phpdocker.io/php-fpm/Dockerfile in your editor:

FROM phpdockerio/php71-fpm:latest
WORKDIR "/application"

# Install selected extensions and other stuff
RUN apt-get update \
    && apt-get -y --no-install-recommends install  php-xdebug \
    && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

We need to put the xdebug configuration in this file. So add a slash \ after doc/* and add the follow lines:

&& echo "zend_extension=/usr/lib/php/20160303/xdebug.so" > /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_enable=on" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_handler=dbgp" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_port=9000" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_autostart=on" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_connect_back=0" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.idekey=docker" >> /etc/php/7.1/mods-available/xdebug.ini 

These lines add some configurations for xdebug on PHP ini, okay thats easy to see, but what this configs really do?

  • remote_enable: if enabled, this tries to contact a client, that you can configure using remote_host and remote_port. If the connection fails, the xdebug set this to false automatically.

  • remote_handler: select the debugger output, see that in versions 2 or later this needs to be dbpg if you want to learn more about common debugger protocol see (https://xdebug.org/docs-dbgp.php).

  • remote_port: set the port for the xdebug, the default is 9000.

  • remote_autostart: If true, xdebug will attempt to start and connect to the remote host.

  • remote_connect_back: If true or 1, this will ignore the remote_host and will try to connect to client host that made the request using ($_SERVER['HTTP_X_FORWARDED_FOR'] and $_SERVER['REMOTE_ADDR']) headers.

  • idekey: Controls which IDE Key Xdebug should pass on to the DBGp debugger handler.

if you want to learn more about XDebug configuration, see https://xdebug.org/docs/all_setting.

Then build the container.

    docker-compose up --build

After building the container edit the docker-compose.yml, setting the environment for php-fpm services.

For xdebug (XDEBUG_CONFIG) we need to set the remote_host, that'll be the docker container network IP address and for PHPStorm (PHP_IDE_CONFIG) we must set an environment variable "serverName", that will be the xdebug connection that IDE will be listening.

If you have doubts about how you can take your container IP see (https://linux.die.net/man/8/ifconfig) for Linux or (https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ipconfig.mspx) for Windows.

If you don't use PHPStorm, you don't need the PHP_IDE_CONFIG.

environment:
        XDEBUG_CONFIG: remote_host=172.17.0.1 #your docker network ip.
        PHP_IDE_CONFIG: "serverName=xdebug-docker" #phpstorm need a environment var that tell who xdebug connect we must to listen.

Restart your container.

    docker-compose down
    docker-compose up -d

For this tutorial, you can use Microsoft Visual Studio Code or JetBrains PHP Storm IDE for this tutorial.

So open your favorite editor and let's work!

Visual Studio Code

In VSC, click on Debug in the menu bar or use key shortcode F5, choose PHP. The editor will create a /.vs/launch.json file. Open this file and put those configurations.

    "serverSourceRoot": "/application/public",
    "localSourceRoot": "${workspaceRoot}/public"

Create a main hello world script in /public/index.php:

<?php
$hello = "Hello World";
echo $hello;

To add a breakpoint in VSC, right click on the line and select "Add Column Breakpoint" or just click in the column before the line number.

Then click on the green play icon, in upper left corner, to start listening debug server.

alt text

Finally, execute http://127.0.0.1:8200 (or use the port that you have configured previous).

And it's done.

PHPStorm

In PHPStorm go to File -> Settings -> Languages & Frameworks -> PHP -> Server. And create a server with the same name and IP that you set in you docker-compose.yml environment and set up your path mappings.

alt text

Create the main hello world script in /public/index.php:

<?php
$hello = "Hello World";
echo $hello;

To start your debug server go to Run -> Start Listening for PHP debug connections and to add a breakpoint in PHPStorm IDE just click on the column after the line number.

Execute in browser http://127.0.0.1:8200 (or use the port that you have configured previous).

And it's done.

Conclusion

So that's it. Now we are able to use XDebug inside a Docker container.

Cya.

Introdução

Quando escuto sobre debug em PHP:

"É muito dificil de debugar" "Preciso escrever código de debug utilizando funçoes como var_dump() e die()."

Entre outras coisas. Mas não precisa ser assim.

Então vamos debugar em PHP sem a necessidade de escrever códigos como var_dump, dump, dd e die utilizando Docker.

Docker install

Antes de mais nada, precisamos ter o Docker instalado no PC. Para instalar o docker vá para a documentação em (https://docs.docker.com/engine/installation/) e siga os passos.

Phpdocker.io

Precisamos criar um conteiner do Docker com php-fpm e a extensão do xdebug instalada. Para isso podemos utilizar o phpdocker.io que cria automaticamente para nós.

Na verdade é bem simples, acesse a página do phpdocker.io ( https://phpdocker.io/generator ) e escolha as opções desejadas. As configurações são categorizadas em Global, PHP, Database e Zero-config.

Na aba global você precisa escolher apenas o nome do projeto e a porta, para o nome do projeto utilize "xdebug-docker", por exemplo, em application type, podemos utilizar o default (Generic: Zend, Laravel, Lumen...), para a porta padrão, pode-se utilizar :80, ou qualquer outra que quiser, nesse projeto é utilizada a porta :8200. E para o max upload size, você pode manter o padrão também (100MB).

Para a configuração do PHP você pode utilizar a versão 7.1, não há necessidade de instalar o Git e selecione a extensão do XDebug.

Não é necessária nenhuma configuração de database ou zero-config para esse projeto, podendo mante-los com as opções padrão.

Dockerfile and docker-compose.yml

Precisamos configurar o arquivo docker-compose.yml e o Dockerfile, por hora podemos abrir o /phpdocker.io/php-fpm/Dockerfile em qualquer editor.

FROM phpdockerio/php71-fpm:latest
WORKDIR "/application"

# Install selected extensions and other stuff
RUN apt-get update \
    && apt-get -y --no-install-recommends install  php-xdebug \
    && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

Precisamos colocar as configurações do xdebug nesse arquivo. Lembre-se de adicionar um barra invertida () após doc/* na ultima linha antes de adicionar as linhas abaixo:

&& echo "zend_extension=/usr/lib/php/20160303/xdebug.so" > /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_enable=on" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_handler=dbgp" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_port=9000" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_autostart=on" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.remote_connect_back=0" >> /etc/php/7.1/mods-available/xdebug.ini \
    && echo "xdebug.idekey=docker" >> /etc/php/7.1/mods-available/xdebug.ini 

Essas linhas adicionam algumas configurações para o XDebug no php.ini, vamos ver o que cada configuração faz?

  • remote_enable: Se ativa, tenta conectar com um Client, que você pode configurar usando remote_host e remote_port. Se a conexão falhar, essa opção é automaticamente desabilitada.

  • remote_handler: seleciona o output do debugger, após a versão 2 a opção precisa ser DBPG, caso deseje saber mais sobre o common debugger protocol veja https://xdebug.org/docs-dbgp.php().

  • remote_port: configura a porta de conexão do xdebug, o default é 9000.

  • remote_autostart: Se true, o XDebug tentará inicializar e conectar com o host remoto.

  • remote_connect_back: Se true, essa opção ignora o remote_host e vai tentar se conectar com o Client usando o IP de origem da requisição utilizando os cabeçalhos ($_SERVER['HTTP_X_FORWARDED_FOR'] e $_SERVER['REMOTE_ADDR']).

  • idekey: Controla qual IDEKey o XDebug deve passar para o handler do DBGp.

Se você quiser saber mais sobre a configuração do XDebug, veja https://xdebug.org/docs/all_setting.

Construa seu container:

    docker-compose up --build

Depois de construir o container, edite o arquivo docker-compose.yml, configurando o ambiente para o serviço php-fpm.

Configuramos o xdebug utilizando a chave (XDEBUG_CONFIG), precisamos então configurar o remote_host que vai receber como valor o endereço de IP da rede do Docker.

E para o PHPStorm utilizaremos a chave (PHP_IDE_CONFIG), precisamos configurar uma variavél de ambiente "serverName" que será a conexão que a IDE vai escutar o xdebug.

Se ainda existirem dúvidas sobre como você pode obter o IP do seu docker veja (https://linux.die.net/man/8/ifconfig) se for Linux ou (https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ipconfig.mspx) se Windows.

Se não for utilizar PHPStorm, não há necessidade de utilizar PHP_IDE_CONFIG.

environment:
        XDEBUG_CONFIG: remote_host=172.17.0.1 #docker network ip.
        PHP_IDE_CONFIG: "serverName=xdebug-docker" #phpstorm variavel de ambiente com o nome do server configurado.

Reinicie seu container.

    docker-compose down
    docker-compose up -d

Nesse tutorial, você pode usar Microsoft Visual Studio Code ou Jetbrains PHPStorm.

Escolha seu editor favorito!

Visual Studio Code

No VSC, clique em debug na barra de menu ou use a tecla de atalho F5, e escolha a opção PHP. O Editor vai criar um arquivo /.vs/launch.json, abra-o e coloque as seguintes configurações:

    "serverSourceRoot": "/application/public",
    "localSourceRoot": "${workspaceRoot}/public"

Crie um arquivo de hello world em /public/index.php:

<?php
$hello = "Hello World";
echo $hello;

Para adicionar um break point no Visual Code, clique com o botão direito e selecione a opção "Add Column Breakpoint" ou clique na coluna a esquerda antes do número da linha.

alt text

Finalmente clique no icone de play verde "Listen for XDebug, no canto superior esquerdo e acesse http://127.0.0.1:8200 no seu navegador - use a porta que você configurou anteriormente - e pronto.

PHPStorm

No PHPStorm vá para File -> Settings -> Languages & Frameworks -> PHP -> Server. E crie um servidor com o mesmo nome que você configurou no docker-compose.yml. Configure também seus path mappings.

alt text

Crie um arquivo de hello world em /public/index.php:

<?php
$hello = "Hello World";
echo $hello;

Para iniciar o debug vá até Run -> Start listening for PHP debug connections e adicione um breakpoint no PHPStorm clicando na coluna lateral antes do número da linha.

Execute no navegador http://127.0.0.1:8200 (ou utilize a porta que você escolheu anteriormente).

E pronto!

Conclusão

Isso é tudo pessoal, agora sabemos como utilizar a extensão do PHP xdebug dentro de um container do docker.

Até mais.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment