Visual Studio Code中使用Docker中的Xdebug

开发环境说明

IDE:Visual Studio Code

DNMP:https://github.com/yeszao/dnmp

项目:laravel

开启xdebug

修改dnmp/php/php72/Dockerfile,添加以下两行(插在带\的任一一行后面即可,查看dockerfile编写规范):

&& pecl install xdebug \
&& docker-php-ext-enable xdebug \
修改dnmp/config/php.ini,在文件末尾添加以下内容:
[xdebug]
zend_extension=xdebug.so
xdebug.remote_port=9000
xdebug.remote_enable=1
xdebug.remote_host=192.168.0.102
xdebug.remote_autostart=1
xdebug.remote_log="/var/log/dnmp/xdebug.log"

其中192.168.0.102就是你的电脑的IP,也就是docker宿主机的IP,docker的端口都挂到宿主机IP上。xdebug默认是localhost,不改就访问不到了。也不要打开

xdebug.remote_connect_back=1,这会使得remote_host配置失效。
在vscode中安装PHP Debug插件,在调试选项卡中打开齿轮配置,即当前项目的.vscode/launch.json,对照以下内容配置:

{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9000,
"pathMappings":{
"/var/www/html": "${workspaceRoot}"
}
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9000
}
]
}
其中,/var/www/html是你在dnmp/www中的site的位置,如果有子目录则填到子目录级别,这里的pathMappings是最新的写法。
在dnmp目录启动:docker-compose up
在vscode按F5启动调试,记得打上断点,祝你成功。
如果已经生成过容器,则需要删除容器,删除镜像。重新生成dnmp-php命令如下:
docker rm dnmp-php
docker rmi dnmp_php
docker-compose up
详情可参考:http://yaxin-cn.github.io/Docker/how-to-delete-a-docker-image.html

评论

《 “Visual Studio Code中使用Docker中的Xdebug” 》 有 3 条评论

  1. rt995

    您好,首先我用的也是这款dnmp项目。我按照您的方法试了一下,仍然无法进行xdebug调试。
    我没有文中dnmp/php/php72/Dockerfile这个目录,是不是dnmp/Dockerfile这个文件呢?
    希望您看到能提些意见。

    1. dnmp官方有更新,文件跟我写的版本不一样了。新的步骤是
      (1)在.env的PHP72_EXTENSIONS=pdo_mysql,mysqli,mbstring,gd,curl,opcache,redis,amqp,swoole,xdebug,mongodb中添加xdebug,给php开启xdebug,然后docker-compose build php72使其生效。
      (2)在conf/php.ini中设置
      [XDebug]
      xdebug.remote_enable = 1
      xdebug.remote_autostart=1
      xdebug.remote_handler = “dbgp”
      ; Set to host.docker.internal on Mac and Windows, otherwise, set to host real ip
      xdebug.remote_host = host.docker.internal
      xdebug.remote_port = 9000
      xdebug.remote_log = /var/log/php/xdebug.log
      其中指定remote_host使用了host.docker.internal,这样就不用担心自己的机器IP变了不能用。
      (3)host.docker.internal这个IP是docker的容器网络IP,但不一定跟当前宿主机IP在一个网络,所以还需要打开docker的设置docker subnet,将其设置到跟宿主机一个网段,如192.168.3.0,重启dokcer服务。这时候可能需要docker-compose down,然后docker-compose up -d

  2. dnmp中的php80按说应该匹配的是xdebug3了,但是配置中https://github.com/yeszao/dnmp/blob/master/services/php80/php.ini还是xdebug2的写法,造成xdebug3取的是默认值,无法开启调试,需要自己在配置中加上:
    ; xdebug3 config
    xdebug.mode = debug
    xdebug.client_host = host.docker.internal
    xdebug.start_with_request = yes

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理