27 Feb, 2018 · 10 minutes read
This article will show you how to quickly create a AWS ServerlessWeb Application and deploy it. If you don’t know what a Serverless application is, read my articlethat talks about the history of web development and how Serverless application are the future.
The application in this example is just a Hello World REST API.
Alrighty, let’s get started.
The first thing we need to do is Sign Up for Serverless. I signed up with my GitHub account. It asks for some basic permissions:-
Personal user data
Email addresses (read-only)
This application will be able to read your private email addresses.
Hit Authorize serverless. That redirects you to the Getting Startedpage with the fancy looking console that shows the basic steps.
Just following along their steps here.
cd C:\Projects
.
Create a new folder for your Serverless project.
mkdir hello-world
Go to the newly created project directory.
cd hello-world
Verify that you have NodeJS installed with the minimum version. node --version
Mine’s v6.10.3. Quite old considering 8.9.4 is their LTS release at the point of writing this article. But, this should work considering v6.5.0 or later is their pre-requisite.
If you do not have NodeJS installed and get an error. Go to Node’s websiteand install the latest stable version.
The next step is to globally install the npm package Serverlesson your system.
npm install serverless -g
This takes a while so you might want to grab a coffee in the meantime.
Now, lets login to our serverlessaccount.
serverless login
This opens up your browser from where you can login using the method you chose to create your account with. Since, I used GitHub, I’ll sign in using it.
If this is the first time you used serverless you might get an EULA. Read it ( always do it, unless you agree to handover your first born to them for deployment on the Cloud!!) and click on I accept.
After this, you are asked to close the browser window and go back to the terminal. You will see logs such as this in the terminal:-
Serverless: The Serverless login will open in your default browser...
Serverless: Opening browser...
Serverless: Waiting for a successful authentication in the browser.
Serverless: Waiting for a successful authentication in the browser.
Serverless: Waiting for a successful authentication in the browser.
Serverless: Waiting for a successful authentication in the browser.
Serverless: Waiting for a successful authentication in the browser.
Serverless: You are now logged in
serverless create --template hello-world
You get an output like this:-
Serverless: Generating boilerplate...
_______ __
| _ .-----.----.--.--.-----.----| .-----.-----.-----.
| |___| -__| _| | | -__| _| | -__|__ --|__ --|
|____ |_____|__| \___/|_____|__| |__|_____|_____|_____|
| | | The Serverless Application Framework
| | serverless.com, v1.26.0
-------'
Serverless: Successfully generated boilerplate for template: "hello-world"
Serverless: NOTE: Please update the "service" property in serverless.yml with your service name
Let us look at what files were generated. So, open this up in your favourite IDE. I prefer Visual Studio Code.
code .
Here’s the structure of the generated files:-
If I try to deploy the application now using the following command:-
serverless deploy
I get the following error:-
$ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless Error ---------------------------------------
ServerlessError: AWS provider credentials not found. Learn how to set up AWS provider credentials in our docs here: http://bit.ly/aws-creds-setup.
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Forums: forum.serverless.com
Chat: gitter.im/serverless/serverless
Your Environment Information -----------------------------
OS: win32
Node Version: 6.10.3
Serverless Version: 1.26.0
Basically, Serverless does not have access to my AWS account and cannot create resources on my behalf. I followed along their guide and came up with these steps:-
serverless config credentials --provider aws --key
You will get an output like this:-
Serverless: Setting up AWS...
Serverless: Saving your AWS profile in "~/.aws/credentials"...
Serverless: Success! Your AWS access keys were stored under the "default" profile.
On Windows the profile is saved at the following path:-
C:\Users\
[default]
aws_access_key_id = ABCDEFGHIJKLM
aws_secret_access_key = ABCDEFGHIJKLMNOPQRSTUV
Now we have an AWS user setup with the proper permissions set and the credentials are saved in our local configuration. Let us try to deploy our application again.
serverless deploy
This step takes a while as the AWS stack is being created. You can go inside AWS’s Cloud Formationand then take a look at your Stack.
You will see new files in your project folder now under the directory .serverless
If everything goes properly you will get a log such as this:-
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 .zip file to S3 (404 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.................................
Serverless: Stack update finished...
Service Information
service: serverless-hello-world
stage: dev
region: us-east-1
stack: serverless-hello-world-dev
api keys:
None
endpoints:
GET - https://2rsm3t4w53.execute-api.us-east-1.amazonaws.com/dev/hello-world
functions:
helloWorld: serverless-hello-world-dev-helloWorld
Serverless: Publish service to Serverless Platform...
Service successfully published! Your service details are available at:
https://platform.serverless.com/services/maxotek/serverless-hello-world
So, our service is deployed at: https://2rsm3t4w53.execute-api.us-east-1.amazonaws.com/dev/hello-world
Also, there seems to be a nice dashboard at Serverless which shows the service details:
You can goto the newly created AWS stack to take a look at the resources that were created for your Serverless application.
This is the core of the scaling aspect of a serverless application. You can read more about Lambda by going to AWS’s documentation page.
But, basically it allows you to run code without worrying where it is deployed. The deployment can scale up and down automatically to meet the incoming requests.
Lambda supports a lot of programming languages. In this case it is NodeJS which is also their preferred language because it has very fast startup times and is currently the fastest rising language/platform.
Our Lambda function is basically defined inside the handler.jsfunction.
'use strict';
module.exports.helloWorld = (event, context, callback) => {
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*', // Required for CORS support to work
},
body: JSON.stringify({
message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
}),
};
callback(null, response);
};
There isn’t a lot going on in here. But, basically we are defining a handler for our helloWorld Lambda function. It recives an eventobject which contains the details of the request.
The context parameter contains various information regarding the incoming request. You can read up more on it by going here.
The callbackparameter is optional and it depends on whether you want to return something back to the caller of our lambda function.
In this case we are returning a JavaScript object called response which is just an HTTP response. In it, we set the status code of 200 to say that the request succeeded. We are allowing Cross Origin Requests on this request by adding a Access-Control-Allow-Origin
header. Finally, in the body of the response we are sending a JSON object with a Hello Worldish message and passing along the eventparameter received in our handler.
In order for our Lambda function to be accessible over HTTP an API was created. Thus, hosting our web application on the cloud and making it accessible for everybody.
The API gateway itself defines which endpoint in the URL calls which Lambda function. Passing over any input parameters to our Lambda function’s eventparameter.
Next a CloudWatch log group was created so that all incoming requests and any console.log messages our Lambda function emits is automatically saved as a Log Stream.
Appropriate roles are also created so that logs can be written by our Lambda Function onto CloudWatch.
Finally, all of these were defined in a cloud formation template and published on S3 so that our stack can be created.
The most important aspect of the output is the final endpoint through which our URL can be publicly accessed.
To remove your stack and all the resources Serverless created on AWS for you just run the following command :-
serverless remove
You will get an output like this:-
Serverless: Getting all objects in S3 bucket...
Serverless: Removing objects in S3 bucket...
Serverless: Removing Stack...
Serverless: Checking Stack removal progress...
...........
Serverless: Stack removal finished...
Serverless: Successfully archived your service on the Serverless Platform
Now, if I go back to the Endpoint URL:-
https://2rsm3t4w53.execute-api.us-east-1.amazonaws.com/dev/hello-world
I get a Bad requesterror.
The stack on AWS Cloud Formation is also no more.
However, the application service page is still available on the Service Page of Serverless.com.
To delete this I went to the Settingspage and from there clicked on the Delete serverless-hello-worldbutton at the bottom. This is followed by a confirmation page after which the application is no more.