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

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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码
  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗
  • ¥15 用matlab写代码
  • ¥30 motoradmin系统的多对多配置
  • ¥15 求组态王串口自定义通信配置方法或代码?
  • ¥15 实验 :UML2.0 结构建模
  • ¥20 用vivado写数字逻辑实验报告撰写,FPGA实验