简体   繁体   中英

docker mysql connection via php

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM