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

1
  • Change localhost by your VM IP. here Commented Jul 28, 2016 at 8:06

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.