LoginSignup
2
3

More than 1 year has passed since last update.

Vagrant上のDockerでvscode+xdebugを使いたい

Last updated at Posted at 2021-08-27

気持ち

vagrant上に構築したDockerでLaravel環境の構築はできた。さあ次はデバッグ環境を整えるだけだ。アレ、どう設定したらええんや。

やりたいこと

vscodeを使ってvagrant環境に接続し、dockerコンテナで実装したlaravel環境のデバッグをxdebugを使って実現する。

事前準備

  • vscodeからvagrant環境に接続する為の「Remote-SSH」拡張機能をインストールしておく
  • vscodeでxdebugを使用する為の「PHP Xdebug」拡張機能をインストールしておく
  • vagrant上でdockerをインストールしておく
  • dockerでlaravel環境を構築しておく
  • コンテナのlaravelのプロジェクトをdockerホストと共有しておく

流れ

  1. Vagrantfileに仮想マシンのIPアドレスの設定を記入する。
  2. phpコンテナ※に接続し、xdebugのインストールを行う。
  3. php.iniにxdebugの設定を記入する。
  4. vscodeのlaunch.jsonの設定を編集する。

※php:7.4-apacheというイメージから作成したコンテナを使用しています。

vscode上でvagrant環境にSSH接続する

Windowsであれば/Users/ユーザ名/.ssh/configを開いて、Vagarntの作業ディレクトリ上で$ vagrant ssh-configを実行し出力結果を記入する。

$ vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile ###ここには<VirtualBoxの鍵ファイルのパス>が出力される###
  IdentitiesOnly yes
  LogLevel FATAL

Hostは任意の名前でOKです。

/Users/ユーザ名/.ssh/config
Host vagrant_env
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile ###<VirtualBoxの鍵ファイルのパス>を記入する###
  IdentitiesOnly yes
  LogLevel FATAL

あとはvscodeの左側にあるメニューバーから「Remote Explorer」のアイコンをクリックして接続を進めればよい。

Vagrantfileに仮想マシンのIPアドレスの設定を記入する。

仮想マシンにIPアドレスを割り当てましょう。
以下の内容を追記します。

Vagrantfile
config.vm.network "private_network", ip: "192.168.33.66"

上記IPアドレスは適当でOKです。

phpコンテナに接続し、xdebugのインストールを行う

以下のコマンドを実行し、xdebugのインストールをします。

$ pecl install xdebug
$ docker-php-ext-enable xdebug # このコマンドを実行することでphp.iniファイル内にzend_extension=<xdebug.soのパス>を記載しなくて済む

私の環境ではxdebugのバージョンは3.0.4がインストールできました。

php.iniにxdebugの設定を記入する

php.iniのパスは「/usr/local/etc/php/php.ini」になります。
ファイルを開いて以下の内容を追記します。

[xdebug]
xdebug.mode=debug
xdebug.remote_enable=1
xdebug.remote_autostart=1
xdebug.remote_connect_back=1
xdebug.start_with_request=yes
xdebug.client_host=192.168.33.66 # Vagrantfileで設定した仮想マシンのIPアドレス
xdebug.clent_prot=9003
xdebug.discover_client_host=1
xdebug.idekey="vscode"

vscodeのlaunch.jsonの設定を編集する

まずはdockerホストのlaravelプロジェクトのディレクトリをvscodeで開く。
そして左のメニューバーから「Run And Debug」アイコンをクリックして、「create a launch.json file」をクリックしてlaunch.jsonを作成する。

launch.jsonの内容を以下に書き換える。

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "stopOnEntry": true,
            "serverSourceRoot": "<コンテナのlaravelプロジェクトのパス>",
            "localSourceRoot": "${workspaceRoot}" # laravelのコンテナと共有しているdockerホスト側のパス。
        },
    ]
}

あとはvscodeのデバッグを実行すればよい。

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3