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:
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' => '', ),
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.
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.
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)
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With