VSCode + 虚拟机 + Docker 配置使用 Xdebug 3
开始之前先说明在下的开发环境
在下使用 Windows 10,在 Hyper-V 虚拟机中安装了 Debian,并在 Debian 中搭建 Docker 的 PHP 开发环境,VSCode 连接 Debian 写代码。 别问为什么弄这么复杂,我们的重点在 Xdebug。
Docker 中安装与开启 Xdebug#
FROM php:8.1.6-fpm-bullseye
RUN apt-get update
&& apt-get install -y --no-install-recommends
libmagickwand-dev
libzip-dev
curl
&& docker-php-ext-configure gd
--prefix=/usr
--with-jpeg
--with-webp
--with-freetype
&& pecl install xdebug-3.2.1
&& docker-php-ext-enable xdebug
上面是精简过的在下的 PHP Dockerfile,重点在最后两行。
pecl install xdebug-3.2.1
安装 Xdebug 扩展
docker-php-ext-enable xdebug
开启 Xdebug
Docker Compose 配置#
version: "3.2"
services:
php-fpm:
build: ./php-fpm
container_name: php-fpm
working_dir: /var/www
volumes:
- ./www/:/var/www/:rw
networks:
lnmp:
ipv4_address: 172.20.0.8
extra_hosts:
- "host.docker.internal:host-gateway"
networks:
lnmp: #自定义网络
ipam: #IP 地址管理(IP Address Management,简称 IPAM)
config:
- subnet: 172.20.0.0/16 #指定子网的 CIDR
重点在 php-fpm
的 extra_hosts
配置,networks
部分是为了方便理解网关地址。
host.docker.internal:host-gateway
其中 host-gateway
是 docker
中容器网络使用的网关地址。
extra_hosts
选项相当于配置 hosts
,此配置会在容器启动时在 /etc/hosts
中添加一行 172.20.0.1 host.docker.internal
。效果如下:
root@2062f0529f04:~# cat /etc/hosts
127.0.0.1 localhost
172.17.0.1 host.docker.internal
172.20.0.8 2062f0529f04
php.ini 中的 Xdebug 配置#
[xdebug]
zend_extension=xdebug
xdebug.mode=debug
xdebug.idekey=VSCODE
xdebug.start_with_request=yes
xdebug.client_port=9003
xdebug.client_host=host.docker.internal
zend_extension=xdebug
启用 xdebug
扩展xdebug.client_host=host.docker.internal
与 Docker Compose 中 extra_hosts
配置的一致
VSCode Xdebug 配置#
安装 PHP Debug 插件
配置 VSCode Xdebug
完整配置如下:
{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003,
"pathMappings": {
"/var/www/xxx": "${workspaceRoot}"
}
}
]
}
注意:
port 要与 php.ini 中 xdebug.client_port 配置的一致
pathMappings 配置项中的 /var/www/xxx
填写你自己 VSCode 当前需要 debug 的项目在 docker 中的路径
一切就绪后就可以愉快的 debug 了
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: