节点应用程序无法连接到远程MySQL数据库

时间:2018-02-24 16:44:06

标签: mysql node.js

节点应用程序在SERVER1上,MySQL在SERVER2上

节点应用连接代码:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "REMOTE_IP",
  port: "3306",
  database: "REMOTE_DATABASE",
  user: "REMOTE_USER",
  password: "PASSWORD"
});


con.connect(function(err) {
  if (err) {
        console.log("MySQL connection error: " + err.stack);
        process.exit(1);
  }

  console.log("Connected to MySQL...");

错误讯息:

MySQL connection error: Error: connect ECONNREFUSED REMOTE_IP:3306
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
--------------------
at Protocol._enqueue (/home/process/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/home/process/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/home/process/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/home/process/process.js:27:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:504:3

MySQL在SERVER2上的端口3306上运行:

$ sudo netstat -plunt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      4893/mysqld   

UFW在SERVER2上允许端口3306:

$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
3306                       ALLOW       Anywhere                  
3306 (v6)                  ALLOW       Anywhere (v6)   

MySQL用户对SERVER2具有远程访问权限:

mysql> SELECT * from information_schema.user_privileges where grantee like "'REMOTE_USER'%";
+-----------------------------+---------------+----------------+--------------+
| GRANTEE                     | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |
+-----------------------------+---------------+----------------+--------------+
| 'REMOTE_USER'@'localhost'     | def           | USAGE          | NO           |
| 'REMOTE_USER'@'SERVER1_PUBLIC_IP' | def           | USAGE          | NO           |
| 'REMOTE_USER'@'SERVER1_PRIVATE_IP'  | def           | USAGE          | NO           |
+-----------------------------+---------------+----------------+--------------+  

通过SERVER2上的命令行连接MySQL工作正常:

$ mysql -u REMOTE_USER -pPASSWORD REMOTE_DATABASE

MySQL或UFW日志中没有任何内容。

我不确定还有什么要检查...

你能想到任何可能导致这种情况的事吗?

感谢。

1 个答案:

答案 0 :(得分:2)

MySQL只监听本地连接。请注意你的netstat命令:

127.0.0.1:3306

请参阅this answer以获取绑定到0.0.0.0。基本上,您只是想确保在bind-address文件中注释掉my.cnf,它应该开始在所有接口上进行监听。