PHP Development Environment using Docker and Docker Compose

This post will demonstrate how to create a PHP Development Environment using Docker and Docker Compose. The environment will consist of a php Apache server, an instance of mysql and and instance of phpMyAdmin for database administration.

Prerequisites

Before getting started, you will need to have docker and docker-compose installed.

sudo apt-get update
sudo apt install docker.io
sudo apt install docker-compose

Creating the Dockerfile and Docker Compose file

Inside your project root, create a file called Dockerfile and put the following content into it:

FROM php:8.1-apache 
RUN docker-php-ext-install mysqli pdo pdo_mysql

Create another file called docker-compose.yml and put the following content into it:

version: "2"
services:
    www:
        build: .
        ports: 
            - "8080:80"
        volumes:
            - .:/var/www/html/
        links:
            - db
        networks:
            - default
    db:
        image: mysql
        ports: 
            - "3306:3306"
        environment:
            MYSQL_DATABASE: demo
            MYSQL_USER: user
            MYSQL_PASSWORD: test
            MYSQL_ROOT_PASSWORD: test
        volumes:
            - persistent:/var/lib/mysql
        networks:
            - default
    phpmyadmin:
        image: phpmyadmin/phpmyadmin
        links: 
            - db:db
        ports:
            - 8000:80
        environment:
            MYSQL_USER: user
            MYSQL_PASSWORD: test
            MYSQL_ROOT_PASSWORD: test
volumes:
    persistent:

Next, create a file called index.php and put any content you like into it:

<?php 
echo "Working Environment!!";
?>

Bulding and Running the Project

Once you have the required files, you can now build and run your project. From your project root type the following:

sudo docker-compose build
sudo docker-compose up

Navigate to localhost:8080 to view your index.php file:

image.png

Navigate to localhost:8000 to access your instance of phpMyAdmin. Login with the database credentials used in the docker-compose file:

image.png

Accessing Database

To access your databases using the terminal, you need to find the name of the container and bash into it:

# FInd the name of the container with the mysql image
docker ps | grep mysql
docker exec -ti demo_db_1 bash

Now that you are in the container in bash mode, you can access the database using mysql -u user -p and enter password when prompted.

Did you find this article valuable?

Support Damien Cahill by becoming a sponsor. Any amount is appreciated!