Я развернул свое приложение в экземпляре aws ec2, правильно настроил пиринг vp c и белый список IP, и все работает нормально. Приложение запущено, и я смог получить доступ к своей базе данных атласа mongodb.
Затем я попытался развернуть свое приложение без сервера. Мне не удалось получить доступ к базе данных атласа mongodb. Я использовал ту же конфигурацию, что и на своем сервере ec2 в aws. что странно, я могу получить доступ к базе данных, когда я запускаю свое приложение локально.
Что-то мне не хватает? вот мой конфиг
# 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