I deployed my application in aws ec2 instance and I setup the vpc peering and ip whitelist correctly and everything works fine. The app is running and I was able to access my mongodb atlas database.
Then I tried to deploy my app in serverless I wasn't able to access my mongodb atlas database. I used the same configuration I used in my ec2 server in aws. what's weird is I can access the database when I ran my app locally.
Is there any thing I'm missing? here is my config
# index.js
const serverless = require('serverless-http');
const express = require('express')
const app = express()
const MongoClient = require('mongodb').MongoClient
app.get('/users', async (req, res) => {
const url = 'mongodb+srv://<username>:<password>@<cluster>/<dbname>?retryWrites=true'
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
console.log(err)
var dbo = db.db("<dbName>");
dbo.collection("users").find({}).toArray((err, data) => {
if (err) throw err
res.send(data)
})
});
})
module.exports.handler = serverless(app)
#serverless.yml
service: gmt-api
custom:
serverless-offline:
port: 3000
provider:
name: aws
runtime: nodejs12.x
stage: ${opt:stage, 'development'}
region: ap-southeast-1
stackName: ${self:service}-${self:provider.stage}-api
endpointType: regional
environment:
NODE_ENV: ${self:provider.stage}
iamRoleStatements:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- ec2:CreateNetworkInterface
- ec2:DeleteNetworkInterface
- ec2:DescribeNetworkInterfaces
Resource: "*"
- Effect: Allow
Action:
- elasticache:*
Resource: "*"
- Effect: Allow
Action:
- s3:*
Resource: "*"
vpc:
securityGroupIds:
- <security group id>
subnetIds:
- <subnet 1>
- <subnet 2>
- <subnet 3>
functions:
app:
wampup: true
handler: index.handler
name: ${self:service}-${opt:stage, self:provider.stage}-serverless
events:
- http: ANY /
- http: 'ANY {proxy+}'
cors:
origin: '*'
maxAge: 86400
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: false
cacheControl: 'max-age=600, s-maxage=600, proxy-revalidate'
plugins:
- serverless-offline
- serverless-plugin-warmup