LastSgt
LastSgt

Reputation: 417

PHP PDO : SQLSTATE[HY000] [2002] Connection refused

I ran into this Problem with the PHP Data Object.

I cannot connect to my Database. First here is my PHP Script:

<?php

$serverName = "127.0.0.1";
$port = "3306";
$dbName = "callitTime";
$userName = "root";
$password = "superstrongPassword";

try {
    $db = new PDO("mysql:host=$serverName;dbname=$dbName;port=$port;",
    $userName, $password);

} catch (PDOException $pdoE) {
    echo 'An Error occurred: ' . $pdoE->getMessage();
}
?>

I am using:

All as Docker Containers.

A phpinfo() tells me that PDO Drivers are loaded as follows:

PDO Drivers:

Driver Versions:

I get the Error:

An Error occurred: SQLSTATE[HY000] [2002] Connection refused

I can connect to the same Database via Phpstorm with the same Password and Username.

Upvotes: 3

Views: 17436

Answers (2)

Bellash
Bellash

Reputation: 8204

If you are inside container, 127.0.0.1 is not known as a service that hosts the database. You can use the mysql container name instead. For example $serverName = "mysql"; depending on the name of your container.

sample service definition

services:
    mysql:
        image: 'mysql:5.5'
        container_name: mysql
        ports:
            - '33066:3306'
   ...

Also note that the port to be used is the internal one.

Upvotes: 0

LukeFilewalker
LukeFilewalker

Reputation: 752

It seems that this is not a problem related to the PHP Configuration.

The error Connection refused shows, from my point of view, that you can't establish a connection from the php container to the mysql container.

You need to expose the 3306 Port to the Webserver Container so that the PHP Container can establish a connection to the database. If you already bridged the containers you need to use the containers IP address and not your loopback 127.0.0.1.

Please see this answer for more information how to connect both containers and how to make a connection from a php to a mysql container:
https://stackoverflow.com/a/43128428/1118905

To narrow down the problem, you can try to establish a connection from within the PHP Container via Netcat to your given DB Host.

For example you can try to establish a connection with the following commands:

  1. Get into the container from which you want to test the connection.
    docker exec -it <name_of_container> bash
  2. Test to open up a connection via netcat (If not all ready available install it via f.e. apt)
    nc -vz 127.0.0.1:3306

Upvotes: 3

Related Questions