찾다

 >  Q&A  >  본문

使用docker-compose编写常规的lnmp容器,pdo连接mysql失败,错误号为2002。

使用docker-compose编写lnmp容器,pdo连接mysql失败,错误号为2002
index.php代码如下

<?php
try{
    $pdo = new PDO('mysql:dbname=test;host=127.0.0.1;charset=utf8mb4;port=3306','root','root');
}catch(PDOException $pe){
    die($pe->getMessage());
}

如果host为127.0.0.1,报错为:SQLSTATE[HY000] [2002] Connection refused
如果host为localhost,报错为:SQLSTATE[HY000] [2002] No such file or directory

目录如下:

122.png

docker-compose.yml文件如下:

version: '2'
services:
    nginx:
        image: nginx:latest
        ports:
            - "80:80"
        volumes:
            - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
            - ./site:/usr/share/nginx/html:ro
        links:
            - "php"
    php:
        build: ./php
        ports:
            - "9000:9000"
        volumes:
            # - ./php/php.conf:/usr/local/etc/php/conf.d/php.conf:ro
            - ./site:/usr/share/nginx/html:ro
            - ./php/php.ini:/usr/local/etc/php/php.ini:ro
        links:
            - "mysql"
            - "redis"
    mysql:
        build: ./mysql
        volumes:
            - ./data/mysql:/var/lib/mysql
        ports:
            - "3306:3306"
        environment:
            MYSQL_DATABASE: test
            MYSQL_USER: root
            MYSQL_PASSWORD: root
            MYSQL_ROOT_PASSWORD: root
    redis:
        image: redis:3.0
        ports:
            - "6379:6379"

在容器外面,使用mysql客户端连接mysql -uroot -h127.0.0.1 -P3306 -proot,连接成功。
这就很困惑了,希望大神指点一二。

我的猜测:找不到文件,这个文件估计指的是mysqld.sock,但是我不知道php容器如何和mysql的sock通讯。再说了,两个容器之间已经link了,还要这么搞吗


高洛峰高洛峰2950일 전1036

모든 응답(1)나는 대답할 것이다

  • 三叔

    三叔2016-11-04 10:26:49

    首先还是感谢sun_iit的回答,虽然没有成功。今天百般尝试,终于试出了答案,关键还是pdo与mysql之间的socket通讯,具体思路分三步:

    修改mysql配置文件,socket = /var/run/mysqld/mysqld.sock

    修改php配置文件(我在Dockerfile里面修改)

    RUN echo "pdo_mysql.default_socket=/var/run/mysqld/mysqld.sock" >> /usr/local/etc/php/conf.d/docker-php-ext-mysqli.ini \
        && echo "mysql.default_socket=/var/run/mysqld/mysqld.sock" >> /usr/local/etc/php/conf.d/docker-php-ext-mysqli.ini \
        && echo "mysqli.default_socket=/var/run/mysqld/mysqld.sock" >> /usr/local/etc/php/conf.d/docker-php-ext-mysqli.ini

    将socket文件的目录挂载到项目目录

    php:
            build: ./php
            ports:
                - "9000:9000"
            volumes:
                # - ./php/php.conf:/usr/local/etc/php/conf.d/php.conf:ro
                - ./site:/usr/share/nginx/html:ro
                - ./php/php.ini:/usr/local/etc/php/php.ini:ro
                - ./data/mysql/mysql_sock:/var/run/mysqld
            links:
                - mysql:mysql
                - redis:redis
        mysql:
            build: ./mysql
            volumes:
                - ./data/mysql:/var/lib/mysql
                - ./data/mysql/mysql_sock:/var/run/mysqld
            ports:
                - "3306:3306"

    最后别忘了修改权限。

    회신하다
    0
  • 취소회신하다