Serverless computing has revolutionized how developers build and deploy applications. With the Serverless Framework, deploying AWS Lambda functions becomes a breeze, abstracting away infrastructure management and letting you focus on code. In this post, we’ll walk through deploying a Lambda function using the Serverless Framework, complete with code examples.
AWS Lambda allows you to run code without provisioning servers, but managing its infrastructure manually can be tedious. The Serverless Framework simplifies this by providing a CLI and configuration model to define and deploy Lambda functions, API Gateway triggers, and more. This article covers the end-to-end process of setting up and deploying a Lambda function, perfect for beginners and seasoned developers alike.
The Serverless Framework is an open-source tool that streamlines the development and deployment of serverless applications. It supports AWS Lambda and other providers, automating tasks like packaging code, creating IAM roles, and setting up API Gateway. Key features include:
Before starting, ensure you have:
aws configure).npm install -g serverless
Create a new project and initialize a Serverless service:
mkdir my-lambda-app
cd my-lambda-app
serverless create --template aws-nodejs
This generates serverless.yml and handler.js.
Edit serverless.yml to define your Lambda function and API Gateway trigger:
service: my-lambda-app
frameworkVersion: '3'
provider:
name: aws
runtime: nodejs18.x
region: us-east-1
memorySize: 128
functions:
hello:
handler: handler.hello
events:
- httpApi:
path: /hello
method: get
Update handler.js with your function logic:
'use strict';
module.exports.hello = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'Hello from Lambda!',
input: event,
}),
};
};
Deploy to AWS with:
serverless deploy
This packages your code, creates a CloudFormation stack, and provisions the Lambda function and API Gateway. The CLI outputs the API endpoint.
Test the API endpoint using curl or a browser:
curl https://[id].execute-api.us-east-1.amazonaws.com/hello
This link can be found from your CLI or AWS console
Expected output:
{"message":"Hello from Lambda!","input":{...}}
serverless.yml for sensitive data.serverless-offline plugin for local testing.To remove the whole stack from AWS, run this code. It will remove Lambda, gateway, and other things related to what was deployed before from AWS
serverless remove
The Serverless Framework makes deploying AWS Lambda functions straightforward and efficient. By following the steps outlined, you can set up, deploy, and test a Lambda function with minimal effort.
For more serverless adventures, explore integrating other AWS services or scaling your application with multiple functions.
Happy coding!
If you found this post helpful, share it on social media. For more on serverless and web development, follow my Medium, Stack Overflow, or check out my GitHub repositories.