Laravel MySql DB Connection with SSH

In case the ssh server is just the tunnel and the db is not located there. You can use this.

ssh -i ~/path/your-key.pem -N -L 13306:your-db-hostname.com:3306 [email protected]

And set the db hostname in your laravel .env or database config file to 127.0.0.1 port 13306


I wrote a Laravel Package to handle for us. stechstudio/laravel-ssh-tunnel

composer require stechstudio/laravel-ssh-tunnel

register the TunnelerServiceProvider::class and set up the configuration in your .env.


Here's a workable solution of working with a database hosted on an EC2 instance via SSH w/ a key.

First, setup a corresponding connection in your database config:

'mysql_EC2' => array(
        'driver'    => 'mysql',
        'host'      => '127.0.0.1:13306',
        'database' => 'EC2_website',
        'username' => 'root',
        'password' => 'xxxxxxxxxxxxxxxx',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

Second, establish a tunnel:

ssh -i ~/dev/awskey.pem -N -L 13306:127.0.0.1:3306 [email protected]

(we pass in the SSH key to the i parameter and establish an SSH connection, binding to port 13306)

Third, use the DB how you normally would in a Laravel App:

$users = DB::connection('mysql_EC2')
        ->table('users')
        ->get();

var_dump($users);