简体   繁体   中英

How can I query a MySQL database that is outside AWS, using AWS Lambda (nodeJS)?

I haven't been able to access to an external database from AWS Lambda, is it actually possible? Am I doing something wrong?

(I have already install mysql through npm locally and imported the .zip with the modules into the console)

Thanks!

var mysql = require('mysql');
var config = require('./config.json');

var pool = mysql.createPool({
    host: config.dbHost,
    user: config.dbUser,
    password: config.dbPassword,
    database: config.dbName
})

exports.handler = (event,context,callback) => {
    context.callbackWaitsForEmptyEventLoop = false;
    pool.getConnection(function(error,connection){
        connection.query(`SELECT * from dot LIMIT 10`,function (error,results,fields){
            connection.release();
            if (error) callback(error);
            else callback(null,results);
        });
    });
};

I get the following response:

{
  "errorType": "TypeError",
  "errorMessage": "Cannot read property 'query' of undefined",
  "trace": [
    "TypeError: Cannot read property 'query' of undefined",
    "    at /var/task/index.js:18:21",
    "    at Handshake.onConnect (/var/task/node_modules/mysql/lib/Pool.js:58:9)",
    "    at Handshake.<anonymous> (/var/task/node_modules/mysql/lib/Connection.js:526:10)",
    "    at Handshake._callback (/var/task/node_modules/mysql/lib/Connection.js:488:16)",
    "    at Handshake.Sequence.end (/var/task/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)",
    "    at Protocol.handleNetworkError (/var/task/node_modules/mysql/lib/protocol/Protocol.js:369:14)",
    "    at PoolConnection.Connection._handleNetworkError (/var/task/node_modules/mysql/lib/Connection.js:418:18)",
    "    at Socket.emit (events.js:376:20)",
    "    at emitErrorNT (internal/streams/destroy.js:106:8)",
    "    at emitErrorCloseNT (internal/streams/destroy.js:74:3)"
  ]
}

Is this endpoint somewhere in your AWS account? If so, and your MYSQL db is in a VPC, then if you configure your Lambda to run in the same VPC, then you will be able to access it.

Otherwise, the endpoint would have to be accessible through the internet. I would try to ping your DB endpoint from inside Lambda and see if that works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM