In the past year, I have seen the word ServerLess appear in many places. There are many concepts introduced, but few of them are actually put into practice. Also out of curiosity for new technology, I plan to have a further understanding of ServerLess. To experience what ServerLess can do for us, the best example is to start with a Hello World.

About the author: May Jun, Nodejs Developer, moOCnet certified author, love technology, love to share the post-90s youth, welcome to pay attention to Nodejs technology stack and Github open source project www.nodejs.red

About the ServerLess Functions provides

Serverless means “Serverless architecture”, but this does not mean that servers are not really needed, the management of these servers is provided by the cloud computing platform, for the user side does not need to pay attention to server configuration, monitoring, resource status, etc., can focus on the business logic.

In the figure below, Microservices are further subdivided into Function as a Service (FaaS), which is less granular than Microservices.

Photo credit: Stackify

Learn more about ServeLess

What is ServerLess? There’s a lot of information about this online, and maybe you can refer to it. Here are some of the previous ones:

  • Serverless Basic knowledge

  • Serverless For Frontend

  • Node FaaS technology outlook in the cloud era at the end of 2019

  • 2019 JSConf China For Tradition, The Path of Serverless Evolution

Cloud vendor support

So far, there are many cloud vendors that support ServerLess:

  • Alibaba function calculation

  • Tencent cloud function SCF

  • AWS Lambda Functions

  • Azure Functions

  • Google Cloud Functions

  • IBM Cloud Functions

. More and more

AWS Lambda function

Aws Lambda will be used in the examples in this section. You can choose from any of the other service providers listed above. Aws offers a one-year free trial, but you need to have a valid credit card to bind to Aws before using the service.

The following steps need to be completed first:

  • To create an AWS account, visit console.aws.amazon.com/

  • To set up your Provider Credentials, a detailed document is available at github.com/serverless/… Or check out the video www.youtube.com/watch?v=HSd…

ServerLess framework installation and configuration

The ServerLess framework is a CLI tool written in Node.js that allows developers to deploy a complete and usable ServerLess application architecture without paying attention to the underlying resources. Before installing node.js, you need to have a node.js running environment. If you have not installed Node.js, please refer to this article “3N Brothers” to help you build a Node.js environment. There are various ways to install Node.js.

Install the server ess framework


$ npm i serveless -g

Copy the code

Check whether Serverless is installed successfully


$ serverless --version

Framework Core: 1.60.0

Plugin: 3.2.6

SDK: 2.2.1

Components Core: 1.1.2

Components CLI: 1.4.0

Copy the code

Set the AWS Credentials

If the credentials are set, they may fail. Add -o to the serverless Config credentials.


$ serverless config credentials --provider aws --key <your_access_key_id> --secret <your_access_key_secret>

Serverless: Setting up AWS...

Copy the code

Create the first Nodejs ServerLess project

You can quickly create a project using the Serverless CLI tool. — Template is the template supported by this scaffold. More templates can be found at github.com/serverless/…


$ serverless create --template hello-world --path aws-hello-nodejs-function

  

Serverless: Generating boilerplate...

Serverless: Generating boilerplate in "/Users/test/aws-hello-nodejs-function"... __. | _. -- -- -- -- -- -.. - -.. -- -- -- -- -- -- |. -- -- -- -- --. -- -- -- -- --. -- -- -- -- --. | | ___ | - __ _ - | | | | - __ _ - | | | | (- - | -- - | | ____ |_____|__| \___/|_____|__| |__|_____|_____|_____| | | | The Serverless Application Framework | | serverless.com, V1.60.0 -- -- -- -- -- -- --' Serverless: Successfully generated boilerplate for template: "hello-world"Copy the code

After successful creation, you can see the following project structure

├ ─ ─ handler. Js# logical processing├ ─ ─ gitignore# ignore file└ ─ ─ serverless. Yml# ServerLess configuration file

Copy the code

handler.js

Handler. js is where the logic is handled, of course you can customize other files as well. Once you customize the files you need to respond to changes in the serverless.yml file. There will be a REST API practice implemented using ServerLess, and you can follow the public account “Nodejs Technology Stack” for the latest news.

Here are three parameters you need to know:

  • Event: Data used to parse the request

  • Context: Use context to pass run-time arguments to Lambda functions

  • Callback returns response data


'use strict';

  

module.exports.helloWorld = (event, context, callback) = > {

const  response = {

statusCode:  200.headers: {

'Access-Control-Allow-Origin':  The '*'.// Required for CORS support to work

},

body:  JSON.stringify({

message:  'Go Serverless v1.0! Your function executed successfully! '.input:  event,

}),

};

  

callback(null, response);

};

Copy the code

serverless.yml

  • Service: indicates the service name

  • Provider: Defines where your service needs to be deployed

  • Functions: Defines the code to deploy

  • Functions provides. The helloWorld: function

  • Functions provides. The helloWorld. Handler: the value of “handle. The helloWorld” defines the function file paths, handle files under the helloWorld function

  • Functions provides. The helloWorld. Events: defines how to trigger events “handler. The helloWorld application?


service: aws-hello-nodejs-function

  

provider:

name: aws

runtime: nodejs12.x

  

functions:

helloWorld:

handler: handler.helloWorld

events:

- http:

path: hello-world  Define the request path

method: get  # define the interface request mode

cors: true  # Enable cross-domain

Copy the code

The deployment of

List some ServerLess deployment related commands:

  • Deploy all: $serverless deploy

  • Single deployment: $serverless deploy function -f helloWorld

  • Locally trigger a function test: $serverless invoke local -f helloWorld

  • $serverless logs -f helloWorld -l

Isn’t it easy to execute the serverless deploy command to see the following information and a service has been successfully deployed? Server environment setup, deployment these do not need to focus on business development.

$ serverless deploy Serverless: Packaging service... Serverless: Excluding development dependencies... Serverless: Creating Stack... Serverless: Checking Stack create progress... . Serverless: Stack create finished... Serverless: Uploading CloudFormation file to S3... Serverless: Uploading artifacts... Serverless: Uploading service aws-hello-nodejs-function.zip file to S3 (404 B)... Serverless: Validating template... Serverless: Updating Stack... Serverless: Checking Stack update progress... . Serverless: Stack update finished... Service Information service: aws-hello-nodejs-function stage: dev region: us-east-1 stack: aws-hello-nodejs-function-dev resources: 12 api keys: None endpoints: GET - https://******.execute-api.us-east-1.amazonaws.com/dev/hello-worldfunctions:

helloWorld: aws-hello-nodejs-function-dev-helloWorld

layers:

None

Serverless: Run the "serverless"  command to setup monitoring, troubleshooting and testing.

Copy the code

The endpoints in the log above show the address of the interface to access. Now you can call it from the interface, or you can call it from postman or curl.


$ curl https://******.execute-api.us-east-1.amazonaws.com/dev/hello-world

Copy the code

Local test serverless-offline

Using the Serverless-Offline plug-in, you can start an HTTP server locally to emulate AWS λ and API Gateway.

Installing a plug-in

If package.json is not available locally, NPM init can generate a package.json file


$ npm install serverless-offline --save-dev

Copy the code

Modify the serverless. Yml

Add serverless-offline to the project serverless.yml as follows:


plugins:

- serverless-offline

Copy the code

Local boot

To successfully start the test locally, run the serverless offline command in the project root directory


$ serverless offline

Serverless: Starting Offline: dev/us-east-1.

  

Serverless: Routes for helloWorld:

Serverless: GET /hello-world

Serverless: POST /{apiVersion}/functions/aws-hello-nodejs-function-dev-helloWorld/invocations

  

Serverless: Offline [HTTP] listening on http://localhost:3000

Copy the code

The default address is http://localhost:3000 as shown below to easily access our example above


$ curl http://localhost:3000/hello-world

Copy the code

Serverless-offline provides a number of customizable options, such as changing the port on which the startup project listens, which can be found at github.com/dherault/se…

The Github source address is as follows:

https://github.com/Q-Angelo/project-training/tree/master/serverless/aws-hello-nodejs-function
Copy the code

conclusion

Hopefully, this tutorial will give you an idea of how to start a ServerLess application and how to deploy and debug it locally. This is just the beginning. In the next section, I will build a REST API using ServerLess, Node.js, and MongoDB Atlas Cloud on top of this. Please check out the public account “Nodejs Technology Stack” for the latest information.

Reference

  • Github.com/serverless/…

  • Stackify.com/aws-lambda-…