Docker - Mysql + PHP error when connecting to mysql

2

I'm learning a little about Docker, but I had some problems connecting to Mysql.

Follow the file docker-compose.yml

php:
  build: .
  ports:
   - "8082:80"
  volumes:
   - ./www:/var/www/html
  links:
   - db
db:
  image: mysql:5.7
  ports:
   - "3306:3306"
  volumes:
   - ./var/lib/mysql:/var/lib/mysql
  environment:
   - MYSQL_ROOT_PASSWORD=phprs
   - MYSQL_DATABASE=phprs

And the Dockerfile file

FROM php:5.6-apache
RUN docker-php-ext-install mysqli pdo_mysql mysql pdo

Here is the error message:

SQLSTATE[HY000] [2002] Connection refused

And the index.php code

<?php

define( 'MYSQL_HOST', '127.0.0.1' );
define( 'MYSQL_USER', 'root' );
define( 'MYSQL_PASSWORD', 'phprs' );
define( 'MYSQL_DB_NAME', 'phprs' );

try
{
    $PDO = new PDO( 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB_NAME . ';port=3306', MYSQL_USER, MYSQL_PASSWORD );


}
catch ( PDOException $e )
{
    echo 'Erro ao conectar com o MySQL: ' . $e->getMessage();
}

How do I view the mysql and apache error logs?

Thank you guys :)

    
asked by anonymous 24.10.2017 / 18:56

1 answer

2

Your mysql will not be accessible via localhost (127.0.0.1) because it is in another container , this container works as a stand-alone isolation of services, environment and network.

There are 2 ways to do it since you are using docker-compose : you can try to access using db (name of your mysql container) as hostname by changing in docker-compose.yml

links:
       - mysql:mysql

And in PHP:

define( 'MYSQL_HOST', 'mysql' );

Or define an ip so that the containers converts without using the previously defined ips:

version: "3.0"

networks:
  mynet:
    driver: bridge
    ipam:
     config:
       - subnet: 10.2.0.0/16

services:
    php:
      build: .
      ports:
       - "8082:80"
      volumes:
       - ./www:/var/www/html
      links:
       - mysql:mysql
      networks:
        mynet:
            ipv4_address: 10.2.0.2
    mysql:
      image: mysql:5.7
      ports:
       - "3306:3306"
      volumes:
       - ./var/lib/mysql:/var/lib/mysql
      environment:
       - MYSQL_ROOT_PASSWORD=phprs
       - MYSQL_DATABASE=phprs
      networks:
        mynet:
            ipv4_address: 10.2.0.3

Within the networks group, a network called "mynet" was created. It uses the bridge drive, which means that the network is visible to the host and will use the same network to connect to networks outside the host. In the service group the network property was added and an ipv4 was defined for each service.

    
24.10.2017 / 19:12