Docker Compose with PHP, MySQL, nginx connection issue

I have problem to connect to MySQL container.

docker-compose.yml

  • Docker ubuntu 16.04 container 64-bit run 32-bit applications
  • Docker, CoreOS and fleet based deployments
  • Issue running Gulp on Docker
  • How to get docker container name in java code
  • how to run any exe application on docker
  • How to alter the mount point of PostgreSQL through Docker?
  • version: '2'
    
    services:
        mysql:
            image: mysql:latest
            environment:
                MYSQL_ROOT_PASSWORD: JoeyW#1999
                MYSQL_DATABASE: wiput
                MYSQL_USER: web
                MYSQL_PASSWORD: Web#1234
            volumes:
                - ./mysql:/var/lib/mysql
            networks:
                - code-network
        php:
            image: wiput1999/php:latest
            volumes:
                - ./code:/code
            networks:
                - code-network
        nginx:
            image: nginx:latest
            ports:
                - "80:80"
                - "443:443"
            volumes:
                - ./code:/code
                - ./site.conf:/etc/nginx/conf.d/default.conf
                - /etc/letsencrypt:/etc/letsencrypt
            networks:
                - code-network
    networks:
        code-network:
            driver: bridge
    

    PHP test script:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "JoeyW#1999";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=wiput", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    ?>
    

    This script reponse me :

    Connection failed: SQLSTATE[HY000] [2002] No such file or directory
    

    What’s wrong with my code? because I think It’s should be fine

    If anyone have a better solution Thank you for your help.

  • Start a service within docker container
  • Is there a way to stop a command in a docker container
  • Error when Building GPU docker image for caffe: Unsupported gpu architecture 'compute_60'
  • Mounting private GitHub repository into a pod's volume
  • REPLICAS remains 0 after running `docker stack deploy` command in manager machine
  • How do I add a container user to a user group in the Docker host?
  • One Solution collect form web for “Docker Compose with PHP, MySQL, nginx connection issue”

    Change $servername = "localhost"; to $servername = "mysql";. Your mysql service isn’t on the localhost of your webserver container. You should use the name of the service instead

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.