Debug PHP container using Xdebug and PhpStorm
Docker Instruction # 9: xdebug
I will create a very simple php page and run it with xdebug and PhpStorm.
Source files can be found here:
github.com/ikknd/docker-study in recipe-09 folder
1. Create a “Dockerfile” in the “docker” folder:
FROM php:7.2-fpm
#Install xdebug
RUN pecl install xdebug-2.6.1 && docker-php-ext-enable xdebug
CMD ["php-fpm"]
Run this command from the docker folder to create the image:
docker build -t php-xdebug-custom -f Dockerfile .
2. Create the docker-compose.yml file in the docker folder:
version: "3.7"
services:
web:
image: nginx:1.17
ports:
- 80:80
volumes:
- /var/www/docker-study.loc/recipe-09/php:/var/www/myapp
- /var/www/docker-study.loc/recipe-09/docker/site.conf:/etc/nginx/conf.d/site.conf
depends_on:
- php
php:
image: php-xdebug-custom
volumes:
- /var/www/docker-study.loc/recipe-09/php:/var/www/myapp
- /var/www/docker-study.loc/recipe-09/docker/php.ini:/usr/local/etc/php/php.ini
Here I use the php-xdebug-custom image instead of php: 7.2-fpm
3. Make the following settings in the php.ini file:
[xdebug]
zend_extension=xdebug.so
xdebug.profiler_enable=1
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=host.docker.internal
xdebug.remote_port=9000
xdebug.remote_autostart=1
xdebug.remote_connect_back=1
xdebug.idekey=PHPSTORM
4. Configure the server in PhpStorm:
File -> Settings -> Languages and Frameworks -> PHP -> Servers
Add a new server using the + icon and configure it as shown in the following screenshot:
Make sure you check “Use path mappings” and map the php folder to /var/www/myapp
.
5. Configure the remote PHP debugger in PhpStorm:
Run -> Edit configurations -> PHP Remote Debug
Add a new configuration and assign values to it, as in the following screenshot:
6. Select debug configuration in the phpStorm debug panel
7. Go to /var/www/docker-study.loc/recipe-09/docker/
and execute:
docker-compose up -d
If I introduce now myapp.loc/
in the browser, I will see the results from the file index.php
.
I can set a breakpoint, start listening for connections in the PhpStorm debug panel and reload the page.
Have a good debug!
More on the topic
- Serverless php
- PHP and regular expressions: the basics for beginners
- Deploying APIs with AWS Elastic Beanstalk