Siv Scripts

Solving Problems Using Code

Mon 26 February 2018

PHP + MySQL using Docker Compose

Posted by Aly Sivji in Quick Hits   

Being a Software Engineer isn't just about being effective in a specific programming language, it's about being able to solve any given problem using the tools at hand.

This week at work I have to extend the functionality of a WordPress plug-in so it can fit into our microservices-based backend architecture. This means learning enough PHP to write some production-grade code.

I don't want to install PHP on my local machine so this is the perfect use case for Docker! In this Quick Hit, I will describe how to create a containerized PHP + MySQL development environment using Docker Compose.

The LAMP Stack is back!

[2018-08-10 Update: I gave a detailed introduction to the Docker ecosystem at a Chicago Python meetup back in October 2017].


Instructions

  • We'll start by creating a folder for this project: mkdir lamp-stack && cd lamp-stack

  • Create another subdirectory, /php which contains the following index.php file:

<!-- ./php/index.php -->

<html>
    <head>
        <title>Hello World</title>
    </head>

    <body>
        <?php
            echo "Hello, World!";
        ?>
    </body>
</html>
  • Populate docker-compose.yml with the following configuration:
# ./docker-compose.yml

version: '3'

services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: my_secret_pw_shh
      MYSQL_DATABASE: test_db
      MYSQL_USER: devuser
      MYSQL_PASSWORD: devpass
    ports:
      - "9906:3306"
  web:
    image: php:7.2.2-apache
    container_name: php_web
    depends_on:
      - db
    volumes:
      - ./php/:/var/www/html/
    ports:
      - "8100:80"
    stdin_open: true
    tty: true
  • Our directory structure should look as follows:
$ tree
.
├── docker-compose.yml
└── php
    └── index.php

Time to learn some PHP!

Notes
  • We use port-forwarding to connect to the inside of containers from our local machine.
    • webserver: http://localhost:8100
    • db: mysql://devuser:devpass@localhost:9906/test_db
  • Our local directory, ./php, is mounted inside of the webserver container as /var/www/html/
    • The files within in our local folder will be served when we access the website inside of the container

 
    
 
 

Comments