在 VSCode 中调试在 Docker 中运行的 PHP 代码

1、PHP 容器中安装 xdebug 依赖

php 容器基于 php:8.1.12-fpm

# 查看 xdebug 是否已安装
php -m | grep xdebug
# 安装
pecl install xdebug
# 开启 xdebug
docker-php-ext-enable xdebug
# 重启容器
docker restart <your-php-container-name>

开启后 phpinfo() 中有单独的模块

2、修改 xdebug 配置

容器内 /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini

zend_extension=xdebug
xdebug.mode = debug
xdebug.start_with_request = yes
xdebug.client_port = 9003
xdebug.discover_client_host = true
xdebug.client_host = host.docker.internal
xdebug.remote_host = host.docker.internal

修改后重启容器

3、VSCode 配置 .vscode/launch.json

先安装 PHP Debug(xdebug) 插件

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003,
"pathMappings": {
// 容器映射本地
"/data/project/material/": "${workspaceFolder}" // /data/project/material/ 路径是自己 PHP Docker 的 WorkingDir
}
}
]
}

4、 调试效果

评论默认使用 ,你也可以切换到 来留言。