AWS Lambda RDS connection timeout

前端 未结 8 1622
栀梦
栀梦 2020-12-14 02:10

I\'m trying to write a Lambda function using Node.js which connects to my RDS database. The database is working and accessible from my Elastic Beanstalk environment. When I

相关标签:
8条回答
  • 2020-12-14 02:45

    When you originally setup the DB, it will automatically create a security group. defaulting to the IP that you set the DB up with. When you run from lambda this rule blocks traffic. Check out your db error logs and you can confirm it is refusing the connection.

    ***** could not be resolved: Name or service not known
    

    You need to create a rule in the security group to allow lambda traffic. Go to your RDS instance console and click on the security group, select inbound. There you will see the rules. Then make the call to open up to the world, find the AWS lambda IPs or create a VPC.

    0 讨论(0)
  • 2020-12-14 02:46

    the connection.end() should be after callback:

    so working code:

        'use strict';
    var mysql = require('mysql');
    
    var connection = mysql.createConnection({
        host     : 'xxxxxx.amazonaws.com',
        user     : 'testuser',
        password : 'testPWD',
        port     : 3306,
        database: 'testDB',
        debug    : false        
    });
    
    module.exports.handler = (event, context, callback) => {
        // **Connection to database**      
        connection.connect(function(err) {
            if (err) {
                console.error('Database connection failed: ' + err.stack);
                context.fail();
                return;
            }
          else{ 
                console.log('Connected to database.');
            }
        });
    
        connection.query('show tables from testDB', function (error, results, fields) {
            if (error) {
                console.log("error: connection failed with db!");
                connection.destroy();
                throw error;
            } else {
                // connected!
                console.log("info: connection ok with db!");
                console.log(results);
                context.succeed("done");
                callback(error, results);
            }
        });
    
        //Send API Response
        callback(null, {
            statusCode: '200',
            body: 'succeed',
            headers: {
              'Content-Type': 'application/json',
            },
        });
    
        //Close Connection
        connection.end(); // Missing this section will result in timeout***
    
    };
    
    0 讨论(0)
提交回复
热议问题