Laravel Connect Remote Database using SSH Tunnel
Laravel 10-Jan-2022

Laravel Connect Remote Database using SSH Tunnel

To connect remote database using ssh tunnel in laravel; Through this tutorial, we will learn how to connect remote database using ssh tunnel in laravel applications.

Sometime we need to connect server database in another server or in local environment at that time we can use ssh tunnel to connect remote server database. ssh tunnel will allows to connect database using port.

Laravel Connect Remote Database using SSH Tunnel

Use the following steps to connect remote database using ssh tunnel in laravel applications; as follows:

  • Step 1: Open SSH Tunnel
  • Step 2: Configure MySQL Database
  • Step 3: Connect to Remote Server Database
  • Step 4: Start Development Server

Step 1: Open SSH Tunnel

Open ssh tunnel using the following ssh command; as follows:

ssh -N -L 13306:127.0.0.1:3306 [USER]@[SERVER_IP]

For example:

ssh -N -L 13306:127.0.0.1:3306 root@111.111.111

Example with SSH Key:

ssh -i ./path/to/id_rsa -N -L 13306:127.0.0.1:3306 root@111.111.111

The ssh tunnel will open, but if you want to keep alive open that ssh tunnel then you can follow the below given steps.

Step 2: Configure MySQL Database

Configure mysql database details in laravel applications; sot open .evn file and database.php file;

.env

...
SERVER_DB_CONNECTION=mysql
SERVER_DB_HOST=127.0.0.1
SERVER_DB_PORT=13306
SERVER_DB_DATABASE=laravel_demo
SERVER_DB_USERNAME=demo
SERVER_DB_PASSWORD=demo123456
...

config/database.php

  
...
'server_mysql' => [
    'driver' => 'mysql',
    'host' => env('SERVER_DB_HOST', '127.0.0.1'),
    'port' => env('SERVER_DB_PORT', '3306'),
    'database' => env('SERVER_DB_DATABASE', 'forge'),
    'username' => env('SERVER_DB_USERNAME', 'forge'),
    'password' => env('SERVER_DB_PASSWORD', ''),
],
...

Step 3: Connect to Remote Server Database

Create simple route and get server database table records and print it. So open web.php file and add the following routes into it; as follows:

Route::get('/server-db', function () {
  
    $records = \DB::connection('server_mysql')
            ->table('products')
            ->get()
            ->toArray();
  
    dd($records);
});

Step 4: Start Development Server

Execute the following command on terminal to start development server; as follows:

php artisan serve