Connecting to a MySQL database from a Lambda function (Node)

I was unable to connect to the MySQL database using Node from the Lambda function. The error I get is Task timed out after 4.00 seconds.

Does anyone have any solutions?

Here is an overview of my condition:

  • The AWS RDS Database is a MySQL database. It is not limited to VPC (I can connect using the host / user / password from MySQLWorkbench).
  • In the execution role of my Lambda function, Lambda is set as a trusted object and set to AdministratorAccess.
  • On my local machine, I installed the mysql module, pinned the index.js and node_modules folder, and loaded it into my Lambda function.
  • I tried putting the createConnection and connect function inside the handler. I tried to put my request inside the callback function of the connection function. I tried to increase the wait time to 10 seconds.
  • My code is:

    var mysql = require('mysql');
    
    var connection = mysql.createConnection({
        host     : 'amazon-string.rds.amazonaws.com',
        user     : 'myusername',
        password : 'mypassword'
    });
    
    connection.connect();
    
    exports.handler = (event, context, callback) => {
    
        connection.query("SELECT * FROM table", function(err, rows, fields) {
            console.log("rows: " + rows);
            callback(null);
        });
    
    };
    
+4
source share
2 answers

Increase the waiting time to one minute. This may be due to the cold start of the lambda function.

Only your first call takes time, consecutive calls should be very fast since you are reusing the same connection.

In addition, having a higher timeout does not mean that you will pay for this timeout, you will only pay for the time that the lambda works.

, , webpack ,

http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/webpack.html

,

var mysql = require('mysql');

var connection = mysql.createConnection({
    host     : 'amazon-string.rds.amazonaws.com',
    user     : 'myusername',
    password : 'mypassword'
});

connection.connect();

exports.handler = (event, context) => {

    connection.query("SELECT * FROM table", function(err, rows, fields) {
        console.log("rows: " + rows);
        context.succeed('Success');
    });

};

, .

+1

RDS, . RDS IP- VPC . Lambda VPC, RDS.

RDS, IP-, Lambda VPC, RDS, .

0
source

Source: https://habr.com/ru/post/1687669/


All Articles