Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

muhamadin's avatar

Connect Laravel to remote database got Connection timed out error

I deployed my Laravel app in one server and connect to MySQL database in another server. Both server has private ip address. When I run my Laravel app I always get error like this:

SQLSTATE[HY000] [2002] Connection timed out (SQL: select * from information                  
    _schema.tables where table_schema = mydb and table_name = migrations a                  
    nd table_type = 'BASE TABLE')  

I have clear all cache but it still not work. I've also tested to connect to mysql server using simple php with same database settings and it working just fine:

<?php
$servername = "DB-IP-ADDRESS";
$username = "DB-USERNAME";
$password = 'DB-PASSWORD';

try {
    $conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password, [
        PDO::MYSQL_ATTR_SSL_CA => "path-to-certificate",
        PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false
    ]);
    
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    $q = $conn->prepare("select * from users");
    $q->execute();
    $res = $q->fetchAll();
    var_dump($res);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

?>

Please help me solve this problem.

0 likes
2 replies
fideloper's avatar
Level 11

If you're able to connect to the remote server using PHP outside of Laravel, then I suspect this is an issue of your .env file on the server.

Laravel is likely attempting to a hostname that is not accepting connections due to incorrect DB_HOST or similar settings.

A timeout generally means a firewall is blocking you, or the address being connected to cannot be reached, so I suspect the hostname that Laravel is using is (was?) incorrect.

muhamadin's avatar

Hi @fideloper

You're right. I made mistake in setting the DB_HOST. It seems that I set it with IP address of my webserver, not my database server.

1 like

Please or to participate in this conversation.