Question

Connection failed: SQLSTATE[HY000] [2003] Can't connect to MySQL server on '161.xxx.xxx.xxx' (13)

Hi guys ,

I have a problem connecting the database from a database VPS server to another VPS server. My problem is that I am writing a web page that has a connection to a database. When I practice connecting the database from XAMPP ,on my local computer, to the database server VPS, it works fine, and there are no problems. But when I install Apache + PHP on another VPS and then connect to the database VPS server, it throws an error like below:

Connection failed: SQLSTATE[HY000] [2003] Can't connect to MySQL server on '161.xxx.xxx.xxx' (13)

'161.xxx.xxx.xxx this is the database server IP that I want to access. I tried to set up mysql remote access, and tried to check if it can control from web VPS to database VPS, it works normally.

Here is the config.php file I used PDO to connect to the database:

<?php
$host = "161.xxx.xxx.xxx";
$username = "username";
$password = "my_pass";
$dbName = "my_db";

try{
    $conn = new PDO("mysql:host=$host; dbname=$dbName", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
}catch(PDOException $e){
    echo "Connection failed: " . $e->getMessage();
}
    
$conn = null;
?>

Can you help me how to connect the database on the website from 1 VPS to a VPS containing the database. And these 2 VPSs are from the digital Ocean.

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there @vin2164382,

In order to be able to access your MySQL service remotely, you would need to do a couple of things:

  • If you have a firewall, first make sure to open the incoming connections to port 3306 on your MySQL server from the remote server
  • Then change the bind address for your MySQL service from 127.0.01 to bind-address = 0.0.0.0 so that MySQL could accept connections from remote servers and not only localhost.
  • Finally alter the MySQL user to allow connections from your remote server IP:
ALTER USER 'sammy'@'remote_server_ip' IDENTIFIED WITH mysql_native_password BY 'password';

Let me know how this goes! Regards, Bobby