How to build and Dockerize a simple PHP Application
In this article, you will get to see how to Dockerize a PHP application. We will go over creating a simple PHP application that uses MySQL database and set it up for containerization using Docker.
1. Prerequisites
- Have Docker installed locally on your computer
- Preferably have a Crane Cloud account because we will be using a remote MySQL database from Crane Cloud
2. After prerequisites
To begin, let us start by creating an index.php
file in our parent folder directory. In this file, we will use a basic HTML form that collects input from a user.
<head>
<title>PHP MYSQL APP</title>
</head>
<link rel=”stylesheet” href=”index.css”><body>
<form method=”post” action=”api.php”>
<h1>Add Name</h1>
<input class=”input” type=”text” name=”name” placeholder=”Enter name”>
<button class=”button” type=”submit”>ADD</button>
</form>
</body></html>
Looking at the index.php
file above, you notice a simple form that will perform a POST request of submitting a name once the ADD button is clicked.
Before we continue to add logic to our application, let us first style our form a bit to make it look cool. We shall do the by adding an index.css
file and give it all relevant styles as shown below:
body {
background-color: whitesmoke;
}form {
padding: 10px 20px;
}.input {
border: 2px solid black;
padding: 5px;
}.button {
color: white;
background-color: black;
border: 2px solid black;
padding: 5px 10px;
}
In the end you should have something like this:
Simple, right? Feel free to go ahead and add your custom styling.
Moving on, let us create a file to handle the logic of our application. As you might have noticed in our HTML form, the submitted form data is sent to the api.php
file.
In this file, we will add code to receive our input and POST it to a MySQL database.
<?php
echo (‘ÁPI is running baby!’);// database server connection variables
$servername = ‘196.43.134.154’;
$username = ‘wkhxemzncrhznsgd’;
$password = ‘^O!:kxY)C[)O5uA3{zw+JKiVfk^Td}m-’;
$dbname = ‘tylsylbagosyrnewxxuwhchj’;
$port = ‘32765’;// receive input from html form
$name = $_POST[‘name’];// validate input
if($name == “”){
die(“Please enter the name!”);
}// connect to mysql
$conn = new mysqli($servername, $username, $password, $dbname, $port);// Check if its connected, if not connected stop execution
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}// if mysql connected, insert
// the ‘.’ operator is for string concatenation in php!
$sql = “insert into names_table(name) values(‘“.$name.”’)”;// validate the query execution
if ($conn->query($sql) === TRUE) {
echo “New name entered successfully!”;
} else {
echo “Error: “ . $sql . “<br>” . $conn->error;
}?>
The very first statement of our api.php
prints a statement to confirm that our api is running. In the next step, we add variables for our database connection. You might be wondering where these came from… Well, for this tutorial, we are using a remote MySQL database from Crane Cloud. Follow this link to create one on Crane Cloud.
The file then receives input from the HTML form and validates it to make sure it’s not an empty string.
If there are no pending errors from the validation, a connection string is passed to a variable $conn
that will be used in connecting to our database. We will be using PHP’s MySQLi extension to interface with our database.
To connect to the database, we create a new mysqli
object and pass our database variables as arguments.
After a successful connection to the database, an insert query statement is made to add our form input to the database and lastly the query is validated to ensure the data is inserted swimmingly. 🏊♂️
Dockerization of our application
Anyone can create a docker image and share it on Docker Hub. To create an image, we write what is called a Dockerfile. We are going to see how to configure our own Dockerfile.
Start by creating a file called Dockerfile in your parent code directory and open it in your text editor and add the following:
First, we will use the FROM
clause to use the official php apache images as our base image.
#Dockerfile
FROM php 7.4-apache
To install our application’s dependencies we use the RUN
command and specify the dependency packages.
RUN apt-get update
RUN apt-get install -y apache2
RUN docker-php-ext-install pdo pdo_mysql mysqli
Next, we use the COPY
command to get the source files from our current directory (source) to the container’s directory (destination).
COPY . /var/www/html
Now we expose the port value to our container.
EXPOSE 80
The last thing we need to do is to run the Apache server in the background. The CMD
command should be used only one time in a Dockerfile, and it needs to have the following form:
CMD [“apache2ctl”, “-D”, “FOREGROUND”]
After completing these steps, our final Dockerfile should look like this:
FROM php:7.2-apacheRUN apt-get update
RUN apt-get install -y apache2
RUN docker-php-ext-install mysqliCOPY . /var/www/htmlEXPOSE 80CMD [“apache2ctl”, “-D”, “FOREGROUND”]
That’s it!! Together, we have seen how to setup a basic PHP application, connect it to a remote MySQL database, and create a Docker image of our application. HOOORAAY!
Now that we have the image, if we needed to host our PHP application online, you can go ahead to build the image and push it to Docker Hub. Once it is on Docker Hub, you can follow this guide on how to deploy your PHP application on Crane Cloud.