Php mysql environment with docker commands

Create a run.sh file with the following content:

#!/usr/bin/env bash

docker stop $(docker ps -aq --filter "name=demo*")

docker network create kisphp

docker run \
    --rm \
    -d \
    --network=kisphp \
    --name=demo-mysql \
    -e MYSQL_ROOT_PASSWORD=admin \
    -e MYSQL_DATABASE=demo \
    -e MYSQL_USERNAME=demo \
    -e MYSQL_PASSWORD=demo \
    -v `pwd`/_data/mysql:/var/lib/mysql \
    -p :3306 \
    -t mysql:5.6

docker run \
    --rm \
    -d \
    --network=kisphp \
    --name=demo-php \
    -v `pwd`:/project \
    -w /project \
    -p :9000 \
    -t demo-php

docker run \
    --rm \
    -d \
    --network=kisphp \
    --name=demo-nginx \
    -v `pwd`:/project \
    -v `pwd`/_data/nginx:/etc/nginx/conf.d \
    -w /project \
    -p 80:80 \
    -t nginx

Then add execution permissions for the current user to be able to run the script:

chmod u+x run.sh

Next, you need to create nginx configuration for the project. Create the file _data/nginx/default.conf with the following content:

server {
    listen 80;
    server_name _;

    index index.php;
    root /project/public;

    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;

    location ~ \.php$ {
        try_files $uri $uri/ =404;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass demo-php:9000;

        fastcgi_index index.php;

        include fastcgi_params;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Before we run this setup, we need to create the php docker image, since the default one doesn't have pdo extensions available. To do this, create Dockerfile-php in the project root directory and add this content:

FROM php:7.1-fpm

RUN docker-php-ext-install pdo pdo_mysql

Now, let's build the docker image by running the following command:

docker build -f Dockerfile-php -t demo-php .

Now, let's create the public/index.php file that will serve our application:

<?php

$con = new PDO('mysql:host=demo-mysql;port=3306;dbname=demo', 'root', 'admin');

$stmt = $con->prepare("SHOW DATABASES");
$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($rows);

And, as a final step we need to run the bash script to create the containers:

./run.sh

To see the result, open the following url http://localhost in your browser

The project structure should look like this:

.
├── Dockerfile-php
├── _data
│   ├── mysql
│   └── nginx
│       └── default.conf
├── public
│   └── index.php
└── run.sh