August 12, 2017

Docker for any PHP Version

Using Docker to get 5.3, which required a PHP version I didn't have on my local machine.

Our Goals:

  1. Use a newer verions of PHP than we have available to us
  2. Install a new Laravel 5.3 app and start hacking on it

First Try:

We first started trying out installing Laravel on a machine with PHP 5.5 (Laravel 5.3 requires PHP 5.6+).

cd ~/Sites/docker
composer create project laravel/laravel my-app dev-develop

This gave us an error, as we'd expect. Rather than spin up a whole VM, I chose to try using Docker.

With Docker

# This doesn't work, composer is not in the container!
docker run --rm -it php:7.0-cli composer --version

# This does work, we use my local machine's composer
# and make it available to the container
docker run --rm -it \
    -v $(which composer):/usr/bin/composer \
    php:7.0-cli \
    composer --version

If we go straight from there, however, we'll still get errors, as composer requires git and/or zip/unzip to be available to get dependencies from GitHub.

So, we create a new Dockerfile, which will help us add the tools we need to a base PHP image that already had PHP 7 in it.

FROM php:7.0-cli


RUN apt-get update
RUN apt-get install -y zip unzip curl git
RUN php -r "copy('', 'composer-setup.php');"
RUN php composer-setup.php --install-dir=/usr/bin --filename=composer
RUN php -r "unlink('composer-setup.php');"

And then we can get Laravel!:

# This doesn't work, composer is not in the container!
docker run --rm -it php:7.0-cli composer --version

# From dir ~/Sites/docker
docker run --rm -it \
    -v $(pwd):/opt
    composer:latest \
    composer create-project laravel/laravel /opt/my-app dev-develop

This installs a new Laravel application into the ~/Sites/docker/my-app directory!

Run It!

The last step is to keep using PHP 7 to run Laravel, so we can start hacking on this new project.

We can re-use our composer container, or use the php:7.0-cli container - they both have PHP 7 on it.

# From dir ~/Sites/docker/my-app
# Note that we're inside of the "my-app" directory!
docker run --rm -it \
    -p 80:8888
    -v $(pwd):/opt
    composer:latest \
    php -S -t /opt/public

If we head to our browser and go to localhost, we'll see the Laravel 5.3 splash screen - success!

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