September 27, 2016

Running PHPUnit Tests in Docker

Recently I came across the situation where I needed to run the PHPUnit tests for the project I was working on in PHP 5.6 as they were failing in Travis. The project was a Laravel project and so was running in a Homestead box using PHP 7. For development of other sites I use Laravel Valet which is also PHP 7 and not easy to switch to another version of PHP (that I know of).

I decided that this is exactly the kind of situation that Docker is well suited for. I could spin up a container running PHP 5.6 without having to install anything extra on my system, and throw it away when I was finished. The only downside is that, as Docker encourages one process per container, I couldn’t find any containers that had PHP 5.6 and MySQL (as my projects needs a database for the tests to run). I didn’t want to venture into using Docker Compose for something as simple as this.

So I decided to make my own Docker image which is now available on Docker Hub. The image runs PHP 5.6 and MySQL on Ubuntu 16.04 (without Apache or anything like that) making it ideal for running PHPUnit tests. To use the container simply add a file to the root of your project (see the example and then run the container attaching your project as a volume to /app:

docker run -v /path/to/your/app:/app gilbitron/php5.6-mysql

I might consider expanding this container to be able to handle multiple versions of PHP/MySQL that could be configured using environment variables. Until then, enjoy.

Looking for more?

Subscribe to my newsletter to get infrequent updates in your inbox. Or follow me on Twitter.