Docker - 为PHP + Nginx安装PDO驱动程序

时间:2016-12-03 16:08:44

标签: php docker pdo docker-compose dockerfile

我有一个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

然后我在docker-compose.yml文件中:

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

然后在我的PHP代码中我有:

<?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();
        }
    ?>

当我连接到我的数据库时,我得到了:

  

连接失败:找不到驱动程序

如何使用此docker设置下载PDO驱动程序?

1 个答案:

答案 0 :(得分:1)

有两个问题:

1。)Dockerfile应该像这样来安装pdo驱动程序:

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.。)要从php连接到mysql,你需要使用dockerfile(mysql)中的名称而不是localhost,如下所示:

$conn = new PDO("mysql:host=mysql;dbname=example", root, password);