2016年10月5日

PHP - 使用 Atom 與 Xdebug 替容器化 PHP 應用除錯 ( Debug PHP application in Docker using Xdebug with Atom )

許多 PHP 開發者已經開始使用 Docker 開發與部署應用程式,與以前相較之下 Debug 的環境、方式變得比較複雜。因此,本篇將介紹如何使用 Atom 與 Xdebug 替容器化 PHP 應用除錯。( If you want to read this article in English, you can visit here )



在 Docker 容器中安裝與設定 Xdebug:
首先,在安裝與設定 Xdebug 前,先把 Xdebug 需要使用的 Port 打開,指令如下:
# 假設 Xdebug 需要 port 9000,則加入 -p 9000:9000
docker run -d \
           -p 80:80 \
           -p 9000:9000 \
           ...
接著我們在 Docker 容器中安裝 Xdebug,指令如下:
# 進入 Docker 容器
docker exec -it <your-container-name> bash

# 安裝 Xdebug
pecl install xdebug
接著在 php.ini (如:/usr/local/etc/php/php.ini) 檔案最後加入 Xdebug 相關設定,範例如下:
# 省略部份內容 ...

zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20131226/xdebug.so
xdebug.remote_enable=1
# 將你的 Docker 容器 IP 加入,如下:
xdebug.remote_host=192.168.99.100
xdebug.remote_connect_back=1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=true
為了確保 Xdebug 會正常運作,請重啟此容器:
docker restart <your-container-name>


設定 Atom:
首先在 Atom 中透過 apm 安裝 php-debug 套件:
# 安裝 php-debug
apm install php-debug

# 啟用 php-debug
apm enable php-debug
或者,你也可以直接在 Atom 的 Settings 中來安裝此套件。安裝 php-debug 後,接著打開 Atom 的設定檔 (config.cson),加入 php-debug 相關設定:
"*":
  "php-debug":
    PathMaps: [
      "/path/to/app/in/docker;/path/to/app/in/local"
    ]
    ServerPort: 9000
  welcome:
    showOnStartup: false


在 Atom 中使用 php-debug:
設定好後,打開你想要加入中斷點的檔案,然後選擇某一段程式碼,點擊右鍵 > PHP Debug > Toggle Breakpoint,即可以加入中斷點。接著,看到 Atom 最下方有 PHP Debug 的頁籤,打開之後你可以看到有訊息顯示 Listen on port 9000,表示它正在等待你要載入的頁面或程式碼。重新載入頁面後,就可以看到該頁籤顯示所有相關資料、參數。


Environment :
  ・ Mac OS X
Reference :
  ・ php-debug
  ・ Xdebug


熱門文章