dpu66046
2016-12-03 16:08
采纳率: 0%
浏览 233

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

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutiaoku4495 2016-12-04 05:56
    已采纳

    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);
    
    点赞 评论

相关推荐 更多相似问题