未捕获的PDOException:在Docker容器内找不到驱动程序

时间:2018-11-16 14:19:32

标签: php docker ubuntu pdo docker-compose

在尝试从docker容器内部使用pdo时出现驱动程序异常。我的映像安装了php7.1并启用了pdo_mysql扩展。数据库凭据也正确,但是我不确定为什么我仍然是此驱动程序异常:PHP Fatal error: Uncaught PDOException: could not find driver in /var/www/app/test.php:9

我需要启用任何其他扩展吗?

Dockerfile

FROM ubuntu:xenial

# install dependencies
RUN apt-get update
RUN apt-get install -y software-properties-common python-software-properties
RUN apt-get install -y language-pack-en-base
RUN LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php

# setup php
RUN apt-get update && \
    apt-get install -y nginx \
    php7.1 \
    php7.1-fpm \
    php7.1-cli \
    php7.1-common \
    php7.1-json \
    php7.1-opcache \
    php7.1-mysql \
    php7.1-mbstring \
    php7.1-gd \
    php7.1-imap \
    php7.1-ldap \
    php7.1-dev \
    php7.1-intl \
    php7.1-gd \
    php7.1-curl \
    php7.1-zip \
    php7.1-xml \
    curl

RUN phpenmod pdo_mysql

EXPOSE 8000

ENTRYPOINT ["/bin/sh", "./entrypoint.sh"]

docker-compose.yml

version: "3"
services:
  app:
    image: app:latest
    command: start
    ports:
      - 8000:8000
    links:
      - db
    environment:
      DB_DATABASE: mydb
      DB_HOST: db
      DB_USER: app_user
      DB_PASSWORD: abc123

  db:
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: mydb
      MYSQL_USER: app_user
      MYSQL_PASSWORD: abc123
      MYSQL_ROOT_PASSWORD: abc123
    ports:
      - 3306:3306

test.php

<?php

require_once('vendor/autoload.php');

use PDO;

$dns = ":host=".getenv('DB_HOST')."; dbname=".getenv('DB_DATABASE');

echo new PDO($dns, getenv('DB_USER'), getenv('DB_PASSWORD'));

1 个答案:

答案 0 :(得分:1)

我认为您的问题出在 $ dns 变量上,您必须定义数据库驱动程序(在您的情况下为mysql)。

$dns = "mysql:host=".getenv('DB_HOST')."; dbname=".getenv('DB_DATABASE');