docker-用nginx php和mysql组成简单的例子

时间:2018-02-10 23:18:58

标签: docker-compose

有人可以帮助我连接我的PHP和MySQL 我确实设法启动并运行,使用MySQL Workbench连接到数据库,但是当我尝试从PHP文件进行PDO连接时,由于某种原因它会失败...

搬运工-撰写

web:
    image: nginx:latest
    ports:
        - "80:80"
    volumes:
        - ./:/var/www
        - ./site.conf:/etc/nginx/conf.d/site.conf
    links:
        - php
php:
    image: php:7-fpm
    volumes:
        - ./:/var/www
    links:
        - db

db:
    image: mysql:5.7
    volumes:
     - /var/lib/mysql
    environment:
     - MYSQL_ROOT_PASSWORD=123456
     - MYSQL_DATABASE=database
    ports:
     - "3306:3306"

site.conf

server {
    index index.php index.html;
    server_name lara.test;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

和index.php

<?php

$database = new PDO('mysql:host=localhost;dbname=database', "root", "123456");
echo "Connected to MySQL<br />";

?>

和错误消息:

  

致命错误:未捕获PDOException:找不到驱动程序   /var/www/index.php:3堆栈追踪:#0 /var/www/index.php(3):   PDO-&gt; __ construct('mysql:host = loca ...','root','123456')#1 {main}   在第3行的/var/www/index.php中引发

为了使这项工作,我想念什么?

1 个答案:

答案 0 :(得分:1)

只是改变

  

$ database = new PDO('mysql:host = localhost ; dbname = database',“ root”,   “ 123456”);

  

$ database = new PDO('mysql:host = db ; dbname = database',“ root”,“ 123456”);

host的名称必须与docker-compose文件中的数据库映像的名称相同。