Shiphp The PHP Developer's Guide

Running a PHP Script in a Docker Container

If you’re used to running PHP command line applications, adding Docker could be a great way to increase the reusability and portability of your scripts. Docker allows you to run your code in isolated containers rather than on the host machine directly, meaning that even if you don’t have the same version of PHP or extensions installed, you can be sure that your script will run the same way on anyone’s Docker container anyway.

*Before we start, you should be familiar with writing command line scripts in PHP and you should have Docker installed.

Our PHP script

First, let’s look at a simple “Hello World” PHP script:

hello.php

<?php

$text = "Hello World!";

echo $text;

Now, open up a terminal and navigate to the directory where you saved . Let’s run that script within a Docker container using the latest version of PHP’s official CLI container:

$ docker run --rm -v $(pwd):/app -w /app php:cli php hello.php

When run, you should see the PHP CLI container being downloaded (the first time), then you should see the output Hello World!. You’ve just run a PHP script in Docker!

But what does it mean?

Let’s go over that Docker command (docker run...) and see what is going on:

You may think that was a long command to write just to run a PHP script, but think about what you didn’t have to do. You didn’t have to install PHP on your machine, and you could run that command in different versions of PHP by tweaking the php:cli parameter.

As you can see, it’s easy to run a PHP script within a Docker container. Docker might not be right for every project and workflow, but if portability and modularity are concerns, I’d highly recommend giving it a try.

Like this Post?

Learn to build your first Dockerized PHP application.

In this book, PHP developers will learn everything they need to know to start building their applications on Docker, including:

  • Installing dependencies using Composer.
  • Getting data from a third-party API.
  • Saving data to a MySQL database.
  • Using a web framework (SlimPHP) for routing.
  • Storing environmental variables securely.
  • And much more!

You can buy this book on Leanpub today.

Buy it Now!