I have a NodeJS/Serverless Framework API up and running on AWS Lambda. It is connected to an AWS RDS which was working fine, however all of a sudden, it can't connect to the RDS Instance only on my office internet. The API and database connection works fine on my home internet and even on mobile data.
Database Connection Error
SequelizeConnectionError: connect ETIMEDOUT
The API works fine when deployed on AWS Lambda & EC2 Instance (successful database connections). Security Group has inbound traffic access open for PORT 3306
Database Connection File
const Sequelize = require('sequelize')
const sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USERNAME,
process.env.DB_PASSWORD,
{
ssl: true,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: process.env.DB_DIALECT,
dialectOptions: {
ssl: 'Amazon RDS'
}
}
)
// Models
const User = require('./models/User')(sequelize, Sequelize)
const Post = require('./models/Post')(sequelize, Sequelize)
const Comment = require('./models/Comment')(sequelize, Sequelize)
let connection= {}
let Models = {
User,
Post,
Comment
}
/**
* Creating Associations
*/
Object.keys(Models).forEach(function(modelName) {
if (Models[modelName].associate) {
Models[modelName].associate(Models);
}
})
module.exports = async () => {
if(connection.isConnected){
console.log("use existing connection")
return Models
}
try {
// await sequelize.sync()
await sequelize.authenticate()
connection.isConnected = true
console.log("use new connection")
return Models
} catch (error) {
console.log(`Connection Error: ${error}`)
}
}
Solutions Tried
- Setup a dummy database at remotemysql.com. API connects to database on my office internet.
- Ran code as a simple NodeJS script. Did not work on office internet from local machine. Tried on multiple local machines.
- Deployed simple NodeJS code to a new EC2 instance. It connected to database API working fine.
- Removed Sequelize and connected to RDS Instance using npm mysql package. Connected to RDS from local machine using office internet.
- Connected to the RDS Instance from Laravel (PHP) repository on local machine using office internet. Worked!!
- Changed database connection config settings. 1) Increased acquire time to 1000000. 2) Added ssl:true & dialectOptions{ ssl: "Amazon RDS" }.
- Added subnet IDs & Security Group IDs in serverless.yml file. So lambda and RDS instance are in the same VPC.
- Tried multiple RDS instances. Connection fails on developement & staging instances.
- Created new RDS instance for testing. It connects to database (sometimes) from local machine on office internet.
You can find the repo here.