Shiphp The PHP Developer's Guide

Using Docker to Run a PHP and MySQL Application

One of the most common operations for any application is to connect to a database, but installing multiple databases locally can be a tricky process. You have to make sure everyone on your team has the right version and that they’re connecting the same way. Fortunately, Docker makes this really simple and more transferrable.

1. Write a PHP Script that Connects to a MySQL Database

Let’s start by writing a simple PHP script that will connect to a MySQL database. All the script is going to do is connect and let us know that the connection was successful. This isn’t very exciting, but it’s a starting point for any complex PHP and MySQL app.


<?php $mysqli = new mysqli("database", "admin", "12dlql*41");
echo $mysqli->server_info . 

This file connects to a MySQL database using mysqli and then shows the database’s version number in the terminal. Good enough to test things out.

2. Start a MySQL Database Container

Next, we need to start up a MySQL container. When using Docker, you want to think about each service or application as its own unique entity, so we need to start each container separately. Here’s the Docker command to run a MySQL container:

docker run -d --name database -e 
=admin -e 
=12dlql*41 -e MYSQL_RANDOM_ROOT_PASSWORD=true mysql:5

What’s going on here?

3. Run the PHP Script Within a Container

In a previous demo, we covered running a PHP script in a Docker container. You’ll notice that this Docker run command is different, but after you run it, you should see the MySQL version in your command line (something like 5.7.18).

docker run --rm -v $(pwd):/app -w /app --link database tommylau/php php index.php

What does this script do?

While Docker may seem like a new way of thinking about your applications, once you learn it, I’ve found that it can be a great asset for writing and testing PHP code. Using modifications of the above example you could connect to a Postgres database, MariaDB, or pretty much anything else.

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!