Search code examples
phpdockerphpstormxdebug

PhpStorm multi-docker hostname resolution


I have a fully set up docker environment furnished with Xdebug, properly set up with PhpStorm. My environment has multiple containers running for different functions. All appears to work great. CLI/Web interaction both stop at breakpoints as they should, no problems. However ...

I have a code snippet as follows:

// test.php
$host = gethostbyname('db'); //'db' is the name of the other docker box, created with docker-compose
echo $host;

If I run this through bash in the 'web' docker instance:

php test.php
172.21.0.2

If I run it through the browser:

172.21.0.2

If I run it via the PhpStorm run/debug button (Shift+F9):

docker://docker_web:latest/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=172.17.0.1 /opt/project/test.php
db

It doesn't resolve! Why would that be, and how can I fix it?


Solution

  • As it happens, my docker environment is built with docker-compose, and all the relevant containers are on the same network, and have a proper depends_on hierarchy.

    However. PHPStorm was actually set up to use plain docker, rather than docker-compose. It was connecting fine to the docker daemon, but because the container wasn't being build composer-aware, it wasn't leveraging the network layout that was defined in my docker-compose.yml. Once I told PHPStorm to use docker-compose, it worked fine.

    As an aside, I noticed that after I run an in-IDE debug session after already loading my container, and causes the container to exit when the script ends. To get around this, I had to create a mirror debug container for PHPStorm to use on demand. My config is as follows:

    version: '3'
    
    services:
      web: &web
        build: ./web
        container_name: dev_web
        ports:
          - "80:80"
        volumes:
          - ${PROJECTS_DIR}/project:/srv/project
          - ./web/logs/httpd:/var/log/httpd
        depends_on:
          - "db"
        networks:
          - backend
    
      web-debug:
        << : *web
        container_name: dev_web_debug
        ports:
          - "8181:80"
        command: php -v
    
      db:
        image: mysql
        container_name: dev_db
        ports:
          - "3306:3306"
        volumes:
          - ./db/conf.d:/etc/mysql/conf.d
          - ./db/data:/var/lib/mysql
        environment:
          MYSQL_ROOT_PASSWORD: root
        networks:
          - backend
    
    networks:
      backend:
        driver: bridge
    

    This allows me to be able to do in-IDE spot debuging on the fly without killing my main web container.