Dockerfile

在原来镜像的 Dockerfile 中添加如下定义

RUN pecl install xdebug-3.0.2
RUN docker-php-ext-enable xdebug

RUN { \
        echo 'zend_extension=xdebug.so'; \
        echo 'xdebug.mode=profile'; \
        echo 'xdebug.start_with_request=trigger'; \
        echo 'xdebug.output_dir=/tmp/xdebug'; \
    } > /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini;

重新打包镜像就能得到一个包含了 xdebug 扩展的 php 镜像了,如果不确定是否添加成功,可以在容器运行起来之后,执行docker exec -i container_name php -m | grep xdebug 检查 xdebug 扩展是否安装成功

配置解析

这里我们采用的是 xdebug3,配置与 xdebug2 不太一样,具体区别可以看这里,网上能搜到的大部分都是 xdebug2 的配置。

为了不影响其他请求的性能,也为了减少日志数量,我们采用 start_with_request=trigger,手动触发 xdebug profile

xdebug.mode=profile 表示使用 xdebug 的 profile 模式
xdebug.start_with_request=trigger 表示默认不开启 xdebug profile,需要通过 http 请求中,添加 > XDEBUG_PROFILE=1 参数来开启,GET/POST 均可
xdebug.output_dir 指定 xdebug 日志的存放位置,如果指定的文件夹不存在,是无法生成日志的

由于我们是在 docker 中使用 xdebug,xdebug.output_dir 对应的目录最好从宿主机挂载进去,方便查看

开始分析

构造一个请求,例如:http://127.0.0.1:8080/xdebug?XDEBUG_PROFILE=1

之后可以在上述配置的文件夹中找到文件名类似cachegrind.out.20的文件,就是我们要的 profile 文件了。

Mac 用户可以下载 qcachegrind 来查看 profile 文件 brew install qcachegrind

下载完之后打开文件就能看到图形化的分析结果了。

参考文献

标签: none

添加新评论