Shiphp The PHP Developer's Guide

Running a PHP Web App in a Docker Container

If you’re familiar with the process for creating a simple website using PHP, then adding Docker to the mix should be relatively easy. The great thing about using Docker is that you have better portability over your code. Let’s look at a simple Docker command that will host a webpage written in PHP.

Our PHP Script


Create a file called index.php and add some HTML like this:

<!doctype html>

<html lang="en">
  <meta charset="utf-8">
  <title>My PHP Website</title>

  <h1>My PHP Website</h1>
  <p>Here is some static content.</p>
  <p><?php echo "Here is some dynamic content"; ?></p>

As you can see, there’s one single line of PHP in the script just to make sure our server is actually working.

Let’s serve that website using the official PHP Apache image:

docker run --rm -p 8000:80 -v $(pwd):/var/www/html php:apache

Docker should download the latest version of the image and start up a webpage at localhost:8000.

What’s going on with that Docker command?

Let’s break down the docker run command piece by piece:

In just one line we were able to serve a PHP based website on our machine, and if we pass that same Docker command to other developers, they will be able to do the same thing without installing any new software. Unlike a traditional VM, this command takes a few seconds to get up and running, and it’s very lightweight.

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!