Trouble Connecting to MySQL via SSH

痴心易碎 提交于 2019-12-06 01:05:06

This can actually be simplified if all you need to do is tunnel MySQL connections from inside your application. The mysql2 module has (better) support for passing a custom stream to use as the database connection, this means you do not have to start a local TCP server and listen for connections to tunnel through.

Here's an example using mysql2 and ssh2:

var mysql2 = require('mysql2');
var SSH2Client = require('ssh2').Client;

var sshConf = {
  host: 'ourCloudServerName.net',
  port: 22,
  username: 'myusername',
  password: 'mypassword',
};
var sqlConf = {
  user: 'root',
  password: 'rootPassword',
  database: 'SomeDatabaseName',
  timeout: 100000
};

var ssh = new SSH2Client();
ssh.on('ready', function() {
  ssh.forwardOut(
    // source IP the connection would have came from. this can be anything since we
    // are connecting in-process
    '127.0.0.1',
    // source port. again this can be randomized and technically should be unique
    24000,
    // destination IP on the remote server
    '127.0.0.1',
    // destination port at the destination IP
    3306,
    function(err, stream) {
      // you will probably want to handle this better,
      // in case the tunnel couldn't be created due to server restrictions
      if (err) throw err;

      // if you use `sqlConf` elsewhere, be aware that the following will
      // mutate that object by adding the stream object for simplification purposes
      sqlConf.stream = stream;
      var db = mysql2.createConnection(sqlConf);

      // now use `db` to make your queries
    }
  );
});
ssh.connect(sshConf);

You will want to expand upon this example of course, to add error handling at the ssh and mysql level in case either go away for some reason (TCP connection gets severed or the ssh/mysql services get stopped for example). Typically you can just add error event handlers for ssh and db to handle most cases, although you may want to listen for end events too to know when you need to re-establish either/both the ssh and db connections.

Additionally it may be wise to configure keepalive at both the ssh and mysql level. ssh2 has a couple of keepalive options that behave just like the OpenSSH client's keepalive options. For mysql2, typically what I've done is just call db.ping() on some interval. You can pass in a callback that will get called when the server responds to the ping, so you could use an additional timer that gets cleared when the callback executes. That way if the callback doesn't execute, you could try to reconnect.

This is SELinux problem and your httpd / webserver is not allowed to connect over network, answer to your problem is following command:

setsebool -P httpd_can_network_connect 1

It should work fine then. I believe you are using apache?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!