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-fpmextra_hosts 配置,networks 部分是为了方便理解网关地址。

host.docker.internal:host-gateway 其中 host-gatewaydocker 中容器网络使用的网关地址。

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 配置#

  1. 安装 PHP Debug 插件
    安装PHP Debug插件

  2. 配置 VSCode Xdebug

配置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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

极限套娃

1年前 评论
GTIANX (楼主) 1年前
Dash007 (作者) 1年前