0

I have the following settings in docker-compose.yml

mysql:
  image: mysql:latest
  ports:
    - "3306"
  volumes:
    - /var/lib/mysql
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: project
    MYSQL_USER: project
    MYSQL_PASSWORD: project

In my index.php, I want to connect to my database container, however, I'm not sure what to type in host=localhost,

the following code doesn't work

<?php
$db = new PDO('mysql:host=localhost;dbname=project;charset=utf8mb4', 'project', 'secret');

It says

Fatal error: Uncaught PDOException: could not find driver in /code/index.php:2 Stack trace: #0 /code/index.php(2): PDO->__construct('mysql:host=loca...', 'project', 'secret') #1 {main} thrown in /code/index.php on line 2

Thanks

  • Change localhost by your VM IP. [here](http://stackoverflow.com/questions/17157721/getting-a-docker-containers-ip-address-from-the-host) – t10508hn Jul 28 '16 at 08:06

1 Answers1

1

Your error message indicates that Mysql driver is unavailable.

In Ubuntu/Debian you check for the package with:

dpkg --get-selections | grep php5-mysql

Install the php5-mysql package if you do not have it.

In Ubuntu/Debian you can use:

sudo apt-get install php5-mysql

After you add that module be sure to map mysql port to any port in your host, for example

mysql:
 image: mysql:latest
 ports:
  - "3306:3306"
...

After that, you can use mysql:host=localhost:3306

Camilo Silva
  • 8,283
  • 4
  • 41
  • 61
  • 1
    You probably want to use an IP address instead of `localhost` or the mysql driver may try to use the socket connection. Alternatively, you can add a PHP container to your docker-compose and reference the service name (e.g., `mysql`) as the host value. – ldg Jul 28 '16 at 01:50