简体   繁体   中英

aws lambda function timed out when querying data from MySQL database

I have an index.js file which contains code like the following:

const dbConfig = require('./config/dbConfig')
const mysql = require('mysql')

var con = mysql.createConnection({
  host: dbConfig.host,
  user: dbConfig.username,
  password: dbConfig.password,
  database: dbConfig.database
})

function readMessages (event, context, callback) {
  console.log('function triggered')
  con.connect((err) => {
    if (err) {
      console.error(err)
      callback(err)
    } else {
      console.log('Connected!')
      con.query('SELECT * FROM Messages WHERE isDeleted = 0;', (err, result, fields) => {
        if (err) {
          console.error(err)
          callback(err)
        } else {
          console.log(result)
          con.end()
          callback(null, result)
        }
      })
    }
  })
}

exports.handler = readMessages

The code correctly gets data from the mysql database and displays them on the screen when I run it on my local machine.

However, I got Task timed out after 7.01 seconds error when it is run on aws-lambda.

The code and its dependencies are packaged in a file named app.zip , then uploaded to aws-lambda.

app.zip
├── config
│   └── dbConfig.js
├── index.js
└── node_modules

The only log message being printed by my function is function triggered . I cannot find other log messages generated by my function in the cloud watch log.

Why does the function timed out on aws-lambda?

If I had to guess it is a permissions issue, when you run locally it is going to grab credentials from your local machine/environment - when you run this in lambda you need to assign a role to the lambda that has the permissions it needs to access the mysql database.

Also, make sure that the mysql database is accessible to the lamba - ie your not trying to access a mysql database that is local to your machine from the lambda function (I was assuming you were using rds).

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