Deploying NodeJS Application On AWS Lambda

Posted By : Vishal Yadav | 09-Apr-2020

AWS Lambda is a serverless computing service that is used to run code on events and manages the computing tasks required by the code. Lambda is a Function as a Service that is used to build the serverless application that is triggered by events. An application can be deployed on Lambda by creating zip and upload directly to s3 or by setting the serverless framework which can be used to directly upload from the system. In this blog, we are using the serverless framework to deploy on AWS Lambda.

 

Pricing is a crucial factor in AWS development services. AWS Lambda costs $0.20 per 1Million requests and $0.0000166667 for every GB-second which is much less than the standard Amazon EC2 pricing and you don't have to pay for the idle time.

 

Prerequisites

  • AWS IAM account with access to lambda
  • NodeJS
  • NPM

 

1. Install the Serverless Framework and configure it.

//Open Terminal and run these commands
//Install Serverless

npm install -g serverless

//Configure serverless with AWS access key and Secret key.

serverless config credentials --provider aws --secret AWS_SECRET_KEY --key AWS_ACCESS_KEY 

 

2. Install serverless-http in the working directory and update app.js/server.js code.

//Open working directory in terminal and run command
npm install serverless-http

//Update main app/server.js code and remove default create the server code and add the following code.

const serverless = require('serverless-http');
const express = require('express');
let app = express();
module.exports.app = serverless(app);

 

3. Create handler.js and serverless.yml in the root folder of the working directory.

//serverless.yml code

# `service` block defines the name of the service
service: servicename

# `provider` block defines service environment
provider:
  name: aws
  runtime: nodejs10.x

# `functions` block defines functions to be deployed
functions:
  app:
    handler: handler.app
    events: 
      - http: 
          path: /
          method: ANY
          cors: true
      - http: 
          path: /{proxy+}
          method: ANY
          cors: true


//handler.js code

module.exports.app = require('./server/app').app;

 

4. Deploy code on AWS lambda.

// Open working directory in terminal and run command
sudo serverless deploy

 

Conclusion

The above code mention how NodeJS/Express application can be deployed on AWS Lambda using a serverless framework. By using the serverless framework you don't create zip and upload on s3 for each change only one command is required to deploy on AWS Lambda/s3.

About Author

Author Image
Vishal Yadav

Vishal has good knowledge of MEAN stack, JavaScript,HTML,CSS. He has worked on both front-end and back-end. He likes to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..