如何将本地nodeJS服务器与在AWS上运行的MySQL连接?

时间:2018-08-17 03:28:50

标签: mysql node.js amazon-ec2 mysql-error-1064

这是我的代码,可与MYSQL连接,出现connection timeout错误:

这是我与MYSQL连接的连接文件:

/*
* @sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/

var mysql = require('mysql');
var sqlConnection = function sqlConnection(sql, values, next) {

    // It means that the values hasnt been passed
    if (arguments.length === 2) {
        next = values;
        values = null;
    }
    var connection = mysql.createConnection({
        "host": process.env.dbHost,
        "user": process.env.dbUser,
        "password": process.env.dbPass,
        "database": process.env.dbName,
        "port":process.env.dbPort
    });
    connection.connect(function (err) {
        if (err !== null) {
            console.log("[MYSQL] Error connecting to mysql:" + err + '\n');
        }
        else {
            console.log("Connection is available");
        }
    });

    connection.query(sql, values, function (err) {
        connection.end(); // close the connection

        if (err) {
            throw err;
        }

        // Execute the callback
        next.apply(this, arguments);
    });
};

module.exports = sqlConnection;

这是我得到的错误:

Error: connect ETIMEDOUT
    at Connection._handleConnectTimeout (/home/himanshu/node_modules/mysql/lib/Connection.js:411:13)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:106:13)
    at Socket.emit (events.js:208:7)
    at Socket._onTimeout (net.js:420:8)
    at ontimeout (timers.js:482:11)
    at tryOnTimeout (timers.js:317:5)
    at Timer.listOnTimeout (timers.js:277:5)
    --------------------

我认为我在配置文件中做错了一些事情,看起来好像,我不知道在db主机中提供什么,或者我实际上如何与aws mysql db连接:

dbHost=00.00.000.000 // aws instance ip
dbName=HIMANSHU
dbUser=ROOT
dbPass=PASSWORD
dbPort=3360

1 个答案:

答案 0 :(得分:0)

@Himanshu只需检查实例的入站规则。 根据您的代码,看起来您在EC2计算机上正在运行MySQL。

因此,请确保在入站规则和出站规则中都允许3306端口