Laravel Connect Remote Database using SSH Tunnel Example

By Hardik Savani January 8, 2022 Category : Laravel


This tutorial will give you example of laravel ssh tunnel mysql. you will learn laravel connect database using ssh tunnel. I’m going to show you about laravel php connect to database through ssh tunnel. This article goes in detailed on laravel database connection through ssh. Alright, let’s dive into the steps.

In this tutorial, i will show you how to connect server database using ssh tunnel in laravel 6, laravel 7 and laravel 8 version. you need to just follow bellow step and you can connect to remote database.

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. so let's follow bellow steps:

Step 1: Open SSH Tunnel

you can open ssh tunnel using ssh command as bellow:


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


ssh -N -L 13306: root@111.111.111

Example with SSH Key:

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

now, it will open ssh tunnel, but if you want to keep alive open that ssh tunnel then you can follow bellow tutorial:

How to Reliably Keep an SSH Tunnel Open in Server?

Step 2: Add MySQL Configuration

next, we need to add another mysql configure in database.php file. so let's add server mysql database username and password on .env file and use it in database.php file:













'server_mysql' => [

'driver' => 'mysql',

'host' => env('SERVER_DB_HOST', ''),

'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

Here, we will create simple route and get server database table records and print it. so let's add following route:


Route::get('/server-db', function () {

$records = \DB::connection('server_mysql')









[0] => stdClass Object


[id] => 1

[name] => ItSolutionStuff

[detail] => demo

[created_at] => 2022-01-05 03:30:51

[updated_at] => 2022-01-05 03:31:07



Now, you can check your own.

i hope it can help you...

Tags :