我试图在docker容器中配置PHP + MySQL设置,但我得到以下错误:
Fatal error: Uncaught PDOException: could not find driver in /var/www/html/chapter5/connection.php:29 Stack trace: #0 {main} thrown in /var/www/html/chapter5/connection.php on line 29
我的docker-compose.yml
,DockerFile
和connection.php
脚本如下:
version: "3"
services:
www:
container_name: playpen_www
build: .
restart: 'always'
ports:
- '81:80'
volumes:
- .:/var/www/html
depends_on:
- db
db:
container_name: playpen_db
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: pdo-demo
MYSQL_USER: user
MYSQL_PASSWORD: password
ports:
- '3307:3306'
adminer:
image: adminer
container_name: playpen_adminer
restart: always
ports:
- 8080:8080
FROM php:7.4.24-apache
RUN apt-get update -y && apt-get upgrade -y
RUN apt-get install tree nano -y
// $host = '127.0.0.1';
$host = 'playpen_db';
$port = 3307;
$dbname = 'pdo-demo';
$charset = 'utf8mb4';
$dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset={$charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
$pdo = new PDO($dsn, 'user', 'password', $options);
} catch (PDOException $PDOException) {
print PHP_EOL . "<br><br>" . $PDOException . "<br>";
throw new PDOException($PDOException->getMessage(), (int) $PDOException->getCode());
}
在playpen_www容器中,我执行了/usr/local/bin/docker-php-ext-enable pdo_mysql
,我确认了pdo和pdo_mysql模块都被列为启用。
尝试将此添加到您的Dockerfile:
RUN docker-php-ext-install pdo_mysql
这将确保无论何时启动镜像,模块都安装在docker引擎中。
非常恼人的是,问题出在数据库名称上。
除了安装pdo_mysql之外,我还将代码和docker- composer文件中的pdo-demo修改为pdo_demo,重新构建容器,脚本连接成功。