AWS: Running Express on Serverless lambda
Generally we deploy the node.js/express app directly in EC2. This is costlier than lambda since EC2 charges for the whole duration whereas lambda charges only for the duration when it ran
We need to install
1. express
2. ejs
3. serverless-http
Here we use the regular express server in local/environment other than AWS.
Note: We need to set ENVIRONMENT "lambda" in lambda once created
Since we have "ejs" view engine, make sure to create "views" folder with some html code (ex: home.ejs)
Creating Lambda function in AWS
1. Navigate to lambda in AWS
2. It gives a boiler code by default. We dont need it as we have the handler written in express app
We have some boilderplate code which we can ignore. Essentially this is when we "dont" have any express server, then API gateway will proxy the request (forward the request) to the lambda. That info will be inside this event object:
Creating API Gateway
API gateway: will take our response and sent it to lambda functionTo create an API gateway
2. You can keep the authentication "Open" and accept all the defaults and save
3. We have the below API gateway created. But we have to setup the "default" and "express-server"
because the URL: https://lzmpft5r6k.execute-api.us-east-2.amazonaws.com/default/express-server
is giving the boilderplate o/p:
1. Click on "express-server-API"
2. Go to "Routes"
3. Currently has
4. Note: API gateway has a special key called "proxy+". What it does is, it doesnt matter what comes after "/", it will forward this request to the express server
Also create a $default route.
Also create a "/" forward slash route
CREATING INTEGRATION
We need to create integration with our lambda function in proxy+ route and $default route
Detach the integration from "express-server":
Create integrations for all 3 routes. If you dont know which is your lambda, create new integration
instead of selecting from the list
Create a .zip file of all the files in express app (including node_modules. Except package.json and package-lock) Automate this step later.
Upload this. And run the URL mentioned in the API gateway trigger
Comments
Post a Comment