August 12, 2017

Automating xDebug Configuration

We automate the setting of the remote_host configuration, ensuring it's correct whenever we spin up a new container.

^ Ad space to help offset hosting costs :D

Dynamic remote_host

We can improve this by having the xdebug.remote_host configuration set dynamically.

First, in our start-container script, we'll run a find and replace to set the remote_host setting based on environment variable XDEBUG_HOST.

This will find/replace that everytime we spin up a new container.

#!/usr/bin/env bash

sed -i "s/xdebug\.remote_host\=.*/xdebug\.remote_host\=$XDEBUG_HOST/g" /etc/php/7.0/mods-available/xdebug.ini

php -S -t /var/www/html

Then we just need to pass that environment variable through. We can set that up in the docker-compose.yml file.

version: '2'
      context: .
    image: xdebug-example:latest
     - ./app:/var/www/html
     - "80:80"

We can then try this out on a new container. Since docker-compose.yml expects an XDEBUG_HOST environment variable, we'll set that when we run docker-compose up.

# Turn off any running containers
docker-compose down

# Re-build it to get latest start-container in a new image
docker-compose build

# Try it out, setting the environment variable on the fly
XDEBUG_HOST=$(ipconfig getifaddr en1) docker-compose up -d

# Confirm our IP address is still correctly set in xdebug.ini
# with in the running contianer
docker-compose exec app cat /etc/php/7.0/mods-available/xdebug.ini

Helper Script

Similar to other videos, we'll make a helper script to make this easier on ourselves.

I'll call this develop again.

File develop:

#!/usr/bin/env bash

# Set environment variables for dev
export XDEBUG_HOST=$(ipconfig getifaddr en1) # Specific to Macintosh

if [ $# -gt 0 ]; then
    docker-compose "$@"
    docker-compose ps

This wil get and set our XDEBUG_HOST environment variable for us, and pass any other flags/arguments along to docker-compose.

Let's try it out:

# Make it executable
chmod +x develop

# run "ps"

# Set containers down
./develop down

# Spin containers back up, it will grab
# XDEBUG_HOST automatically
./develop up -d

# We can see it's still set
docker-compose exec app cat /etc/php/7.0/mods-available/xdebug.ini

Looking for a deeper dive into Docker?

Sign up here to get a preview of the Shipping Docker course! Learn how to integrate Docker into your applications and develop a workflow to make using Docker a breeze!

All Topics