To be able to connect to MySQL Database hosted on Amazon AWS ( AWS RDS ) from an Express JS App that is being served from an AWS Lambda function you have to run the app under the same security group of your DB VPC
// get the client
const mysql = require('mysql2');
// Create the connection pool. The pool-specific settings are the defaults
const pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.USERNAME,
database: process.env.DB_NAME,
password: process.env.PASSWORD,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
port: process.env.MYSQL_PORT,
multipleStatements:true,
});
module.exports = pool;
provider:
name: aws
region: us-east-2
runtime: nodejs14.x
lambdaHashingVersion: '20201221'
environment:
#mysql
MYSQL_HOST: ${self:custom.MYSQL.HOST}
MYSQL_PORT: ${self:custom.MYSQL.PORT}
#common
DB_NAME: ${self:custom.DB_NAME}
USERNAME: ${self:custom.USERNAME}
PASSWORD: ${self:custom.PASSWORD}
custom:
DB_NAME: YOURDBNAME
USERNAME: ADMINUSERNAME
PASSWORD: ADMINPASSWORD
MYSQL:
HOST: GRAB-THE-HOST-FROM-AWS
PORT: GRAB-THE-PORT-FROM-AWS
serverless.yml
, add your VPC config, so your lambda function runs under the same security group:provider:
name: aws
....
....
vpc:
securityGroupIds:
- sg-################
subnetIds:
- subnet-################
- subnet-################
- subnet-################