使用 SSH 连接 Laravel MySql 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25495364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:59:20  来源:igfitidea点击:

Laravel MySql DB Connection with SSH

mysqlsshlaravel-4

提问by egekhter

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.

我有几个我想访问的远程数据库,但它们位于只能通过 SSH 使用密钥访问的服务器上。

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

在 Sequel Pro 中,我像这样连接到这个远程数据库: 在此处输入图片说明

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

我将如何配置我的 Laravel 应用程序以连接到这样的数据库?

'mysql_EC2' => array(
        'driver'    => 'mysql',
        'host'      => '54.111.222.333',
        'database' => 'remote_db',
        'username' => 'ubuntu',
        'password' => 'xxxxxxxxxxxxxxxxxxxx',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

回答by egekhter

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

这是通过带密钥的 SSH 使用托管在 EC2 实例上的数据库的可行解决方案。

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)

(我们将SSH密钥传入i参数,建立SSH连接,绑定13306端口)

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

第三,像通常在 Laravel 应用程序中一样使用数据库:

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

var_dump($users);

回答by bubba

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

我写了一个 Laravel 包来为我们处理。 stechstudio/laravel-ssh-tunnel

composer require stechstudio/laravel-ssh-tunnel

composer require stechstudio/laravel-ssh-tunnel

register the TunnelerServiceProvider::classand set up the configuration in your .env.

注册TunnelerServiceProvider::class并在您的.env.