Search code examples
phpmysqldockerdocker-compose

Docker - Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in var/www/html


Using Docker, PHP, MySQL & Apache, I'm receiving the following error while trying to connect any page requiring "database-connection.php".

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in /var/www/html/database-connection.php:22 Stack trace: #0 /var/www/html/index.php(3): require() #1 {main} thrown in /var/www/html/database-connection.php on line 22

Line 22 throw new PDOException($e->getMessage(), $e->getCode()); is causing the issue as anytime I comment out this line, it works. When I remove the comments, it goes back to giving me errors. I tried most of the solutions pertaining to this error but it's not working. What am I missing?

docker-compose.yml

version: "3.9"
services:
  php-apache:
    ports:
      - "80:80"
    build: './build/php'
    volumes:
      - ./app/public:/var/www/html
  mysql:
    image: mysql:latest
    ports:
      - "3306:3306"
    build: './build/mysql'
    environment:
      MYSQL_ROOT_PASSWORD: "password"
      MYSQL_DATABASE: "commune"
    volumes:
      - dbData:/var/lib/mysql
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    restart: always
    ports:
      - 8080:80
volumes:
  app:
  dbData:

database-connection.php

<?php //database-connection.php

$type       = 'mysql';
$server     = 'localhost'; // Must be the service name of the database in `docker-compose.yml`
$db         = 'commune';
$port       = '3306';
$charset    = 'utf8mb4';

$username   = 'root';
$password   = 'password';

$options     = [
    PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE    => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES      => false,
];

$dsn = "$type:host=$server;dbname=$db;port=$port;charset=$charset";
try {
    $pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    throw new PDOException($e->getMessage(), $e->getCode());
}

?>

index.php

<?php //index.php
    declare(strict_types = 1);
    require 'database-connection.php';

    echo "Hello, World!";

?>

Dockerfile

FROM mysql:latest
USER root
RUN chmod 755 /var/lib/mysql
FROM php:8.1-apache

RUN apt-get update && \
    docker-php-ext-install mysqli pdo pdo_mysql

Solution

  • In your PHP code, you should have $server = 'mysql';

    as is written in the code comment // Must be the service name of the database in docker-compose.yml

    If this doesn't fix the issue, you would need to share the contents of the Dockerfile which is being build for the php-apache service.

    Also, it doesn't make much sense to catch a PDOException, only to throw another PDOException. You can achieve the same thing without try/catch