PHP and MySQL Server with docker-compose

This post shows how to create a docker-compose.yml file, which hosts an apache server (with PHP) and MySQL database and connect them correctly together.

The directory of your project should look like this:

project-directory
|
+--docker-compose.yml
+-+php
  |
  +-Dockerfile
  +-index.php

The docker-compose.yml:

version: '3.8'
services:
php-apache-environment:
container_name: php-apache
build:
context: ./php
dockerfile: Dockerfile
depends_on:
- db
volumes:
- ./php:/var/www/html/
- mysql-sock-volume:/var/run/mysqld
ports:
- 8000:80
db:
container_name: db
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: exampledb
MYSQL_USER: exampleuser
MYSQL_PASSWORD: exampleuser
volumes:
- mysql-sock-volume:/var/run/mysqld
volumes:
mysql-sock-volume:

The Dockerfile in the php directory:

FROM php:8.1-apache

RUN docker-php-ext-install mysqli pdo pdo_mysql

Connect to the database in the index.php:

<?php
$pdo = new \PDO(
'mysql:dbname=exampledb;unix_socket=/var/run/mysqld/mysqld.sock',
'exampleuser',
'examplepassword'
);
var_dump($pdo->query('SELECT now()')->fetchAll());

The webserver will be served on http://localhost:8000.