2

I have a Dockerfile:

FROM php:7-fpm

RUN apt-get update \
  && apt-get install -y --no-install-recommends libpq-dev \
  && docker-php-ext-install mysqli pdo_pgsql pdo_mysql

Then I have in my docker-compose.yml file:

web:
  image: nginx:latest
  ports:
    - "80:80"
  volumes:
    - ./frontend:/var/www/html
    - ./api:/var/www/html/api
    - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
  links:
    - php
mysql:
  image: mariadb
  ports:
    - "3306:3306"
  environment:
    - MYSQL_ROOT_PASSWORD=password
    - MYSQL_DATABASE=example
  volumes:
    - ./database:/var/lib/mysql
php:
  image: php:7-fpm
  volumes:
    - ./frontend:/var/www/html
    - ./api:/var/www/html/api
  links:
    - mysql

Then In my PHP Code I have:

<?php
$servername = "localhost";
$username = "root";
$password = "password";

try {
        $conn = new PDO("mysql:host=$servername;dbname=example", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    ?>

Which when I go to connect to my database I get:

Connection failed: could not find driver

How would I download the PDO driver using this docker setup?

ClickThisNick
  • 5,110
  • 9
  • 44
  • 69
  • Is it actually trying to connect to localhost via the code? If so, I don't see any of the containers attaching to the host net. Just wanted to clarify before I hazard a guess. Is the code supposed to be executed in PHP FPM? – Dockstar Dec 03 '16 at 16:17
  • I have php linked from the web image. Right now I can go to localhost and it serves up php pages just fine, but attempting to use PDO to connect to my database will not work because of the missing driver. – ClickThisNick Dec 03 '16 at 16:20

1 Answers1

1

There were two problems:

1.) The Dockerfile should be like this to install pdo driver:

RUN apt-get update && apt-get install -y libpng12-dev libjpeg-dev libpq-dev \
&& rm -rf /var/lib/apt/lists/* \
&& docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \
&& docker-php-ext-install gd mbstring pdo pdo_mysql pdo_pgsql

2.) To connect to mysql from php you need to use the name from the dockerfile (mysql) not localhost, like this:

$conn = new PDO("mysql:host=mysql;dbname=example", root, password);
ClickThisNick
  • 5,110
  • 9
  • 44
  • 69