Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel MySql DB Connection with SSH

I have a couple of remote databases I would like to access, but they are sitting on a server accessible only through SSH with a key.

In Sequel Pro, I connect to this remote DB something like this: enter image description here

How would I configure my Laravel app to connect to such a DB?

'mysql_EC2' => array(         'driver'    => 'mysql',         'host'      => '54.111.222.333',         'database' => 'remote_db',         'username' => 'ubuntu',         'password' => 'xxxxxxxxxxxxxxxxxxxx',         'charset'   => 'utf8',         'collation' => 'utf8_unicode_ci',         'prefix'    => '',     ), 
like image 654
egekhter Avatar asked Aug 25 '14 22:08

egekhter


People also ask

How do I connect to a remote MySQL server using SSH?

Open a new terminal window. Direct your local MySQL client to 127.0. 0.1:3306 with the MySQL server username and password. Your connection to the remote MySQL server will be encrypted through SSH, allowing you to access your databases without running MySQL on a public IP.

How does laravel connect to external database?

In . env file you can set DB_CONNECTION with your database name and applicable databases are given in /config/database. php which are (SQLite, MySQL, pgSQL, SQLSRV) after that just type your username, password, and database name and you can use that database with port number.

Which DB to use with laravel?

Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the Eloquent ORM. Currently, Laravel provides first-party support for five databases: MariaDB 10.3+ (Version Policy) MySQL 5.7+ (Version Policy)


2 Answers

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); 
like image 158
egekhter Avatar answered Sep 30 '22 23:09

egekhter


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.

like image 35
bubba Avatar answered Sep 30 '22 23:09

bubba