Error connecting to Amazon RDS (MySQL) from node-m

2020-07-26 03:10发布

问题:

I am trying to connect to my Amazon RDS (MySQL) instance from a nodejs code hosted in Lambda using the "felixge/node-mysql" package. I need help to find out what I am doing wrong. I am getting "connect ETIMEDOUT" error. My code is hosted in Lambda and both Lamda and RDS are of the same account and region. I have also attached the RDSFullAccess Policy to the IAM role. RDS instance is also accessible from all IPs(no whitelist/blacklisted IPs).

At the same time, I am able to connect from my local MySQL Workbench with same credentials.

Here is my code:

var connection = mysql.createConnection({
        host     : 'xxxxxxxx.crhmtrscnbgt.us-east-1.rds.amazonaws.com',
        user     : 'my_user',
        password : 'my_passowrd',
        database : 'my_db',
        port     : '3306',
        debug    : true
});  

connection.connect(function(err) {
        if (err) {
                console.error('error connecting: ' + err.stack);
                return;
        }
        console.log('connected as id ' + connection.threadId);
});

var query = "SELECT * FROM users";            

connection.query(query, function(err, rows) {                
        if (err) throw err;                
        console.log(rows);
});

Output is:

2016-04-12T13:32:34.367Z    fa04401a-00b2-11e6-9a23-2dd70e33cc5d    error connecting: Error: connect ETIMEDOUT 
at Connection._handleConnectTimeout (/var/task/node_modules/mysql/lib/Connection.js:412:13) 
at Socket.g (events.js:180:16) 
at Socket.emit (events.js:92:17) 
at Socket._onTimeout (net.js:327:8) 
at _makeTimerTimeout (timers.js:438:11) 
at Timer.unrefTimeout [as ontimeout] (timers.js:502:5) 
-------------------- 
at Protocol._enqueue (/var/task/node_modules/mysql/lib/protocol/Protocol.js:141:48) 
at Protocol.handshake (/var/task/node_modules/mysql/lib/protocol/Protocol.js:52:41) 
at Connection.connect (/var/task/node_modules/mysql/lib/Connection.js:123:18) 
at Object.Workout.save (/var/task/storage.js:32:24) 
at Object.storage.saveWorkout (/var/task/storage.js:62:28) 
at intentHandlers.NewExcerciseIntent (/var/task/intentHandlers.js:19:17) 
at AlexaSkill.eventHandlers.onIntent (/var/task/AlexaSkill.js:65:27) 
at AlexaSkill.requestHandlers.IntentRequest (/var/task/AlexaSkill.js:28:37) 
at AlexaSkill.execute (/var/task/AlexaSkill.js:105:24) 
at exports.handler (/var/task/index.js:9:19)

回答1:

I fixed it. The issue was with the timeout setting in Lambda function configuration. It was set to 3 sec, but my script needed more than 10 seconds to execute. That's the reason I got the ETIMEDOUT error. I changed the setting to 30 seconds. Now no issues, everything works fine.