[Home](https://codefionn.eu/) · [About](https://codefionn.eu/about/) · [GitHub](https://github.com/codefionn)

---

# PHP and MySQL Server with docker-compose

> Create an apache server with php and mysql with docker-compose.yml

*Published on 2023-04-16 · [View as HTML](https://codefionn.eu/php-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`:

```yaml
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
<?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`.

---

[Impressum](https://codefionn.eu/impressum/) · [Datenschutzerklärung](https://codefionn.eu/datenschutz/) · [Mastodon](https://c.im/@codefionn)

© Copyright 2022-2026 Fionn Langhans
