PHP can not resolve mysql container name under certain circumstances

后端 未结 2 2100
遇见更好的自我
遇见更好的自我 2020-12-22 06:55

I have legacy PHP application. It used mysqli to make mysql things. So in config I have DSN string to connect to mysql service. Like that

mysql://username:pass

相关标签:
2条回答
  • 2020-12-22 07:12

    As you missing linking you db container with php. When you link db with PHP it will be accessible from localhost of PHP.

    Here is I modified your docker-compose file as I like alpine everywhere ;). And I use adminer and link with db to verfiy connection instead of code level checking. As i dont have you php docker file so i am creating php:alpine which contain php7.

    version: "3"
    services:
      nginx:
        image: nginx:1.13-alpine
        container_name: nginx
        ports:
          - "8081:80"
        command: nginx -g "daemon off;"
      db:
        image: mysql:5.5
        environment:
          MYSQL_ROOT_PASSWORD: example
    
      php:
        image: php:alpine
        container_name: php
        tty: true
        links:
         - db 
      adminer:
        image: adminer
        container_name: adminer
        ports:
          - 8080:8080
        links:
         - db 
    

    Then i installed mysqli in php container

    docker exec -it php ash
    

    and run below command

    docker-php-ext-install mysqli;
    

    Then create test.php

    here server name is db. Note that your server name will be what is db container name which is link to php. if you ping db in php container it will ping db container.

        <?php
    $servername = "db";
    $username = "root";
    $password = "example";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    echo "Connected successfully";
    ?>
    

    Now run this file in php container. You can mount and run your php code but this is what I did for testing. And I tried as a root user.

    php -f test.php
    

    And here is adminer which also link with db

    0 讨论(0)
  • 2020-12-22 07:33

    docker-compose rm -v use and delete MySQL volume.

    Volumes:

    • ./docker/mysql:/var/lib/mysql -> pathmysql
    • /etc/timezone:/etc/timezone:ro
    • /etc/localtime:/etc/localtime:ro
    0 讨论(0)
提交回复
热议问题