Docker - Mysql + PHP error when connecting with mysql

Asked

Viewed 1,568 times

2

I’m learning a little about Docker, but I had some problems connecting with 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

Follow the error message:

SQLSTATE[HY000] [2002] Connection refused

And the code of index.php

<?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 :)

1 answer

2


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

There are 2 ways to do it since you are using the Docker-Compose: you can try to access using db (mysql container name) as hostname changing in Docker-Compose.yml

links:
       - mysql:mysql

And in PHP:

define( 'MYSQL_HOST', 'mysql' );

Or else set an ip so that the containers converge-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" has been created that uses the drive bridge, which means that this network is visible to the host and will use that same network to connect to external networks to the host. In the service group the network property was added and an ipv4 was set for each service.

  • 1

    Thank you very much Leonancarvalho worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.