There are seven easy steps to deploy your existing NodeJS ExpressJS application as an AWS Lambda Function using Serverless Framework.
Step 1
Installing Dependencies
$ npm init -y
$ npm install --save serverless-http
Step 2
Do not start the server instead export it
const serverless = require("serverless-http");
...
...
...
// app.listen(port, () => {
// console.log(`listening On PORT -> ${port} `);
// });
// Export your Express configuration wrapped into serverless function
module.exports.handler = serverless(app);
Step 3
install and Configure the Serverless Framework
$ npm install -g serverless
Prefix the command with sudo if you’re running this command on Linux.
$ sls config credentials --provider aws --key <aws_access_key_id> --secret <aws_secret_access_key>
Step 4
Add serverless.yml file in your project. Follow the link for more details.
service: example-project
provider:
name: aws
runtime: nodejs12.x
stage: dev
region: us-east-1
# you can add statements to the Lambda function's IAM Role here
iamRoleStatements:
- Effect: "Allow"
Action:
- "s3:PutObject"
Resource:
- "arn:aws:s3:::${file(config.json):S3_BUCKET_NAME}/*"
functions:
app:
handler: index.handler
events:
- http: ANY /
- http: "ANY /{proxy+}"
Step 4
Deploy the project
$ sls deploy
Step 5
We have to follow this step for production environment.
Add the NODE_ENV
in the secrets.json
.
{
"NODE_ENV": "production"
}
Step 6
Add a reference for the secrets.json
in the serverless.yml
service: example-project
custom: # add these two lines
secrets: ${file(secrets.json)} # reference the secrets.json file
provider:
name: aws
runtime: nodejs12.x
stage: dev
region: us-east-1
# you can add statements to the Lambda function's IAM Role here
iamRoleStatements:
- Effect: "Allow"
Action:
- "s3:PutObject"
Resource:
- "arn:aws:s3:::${file(config.json):S3_BUCKET_NAME}/*"
functions:
app:
handler: index.handler
events:
- http: ANY /
- http: "ANY /{proxy+}"
Step 7
That’s it! Delete the node_modules
and .serverless
folders from the service and run npm install
again, but this time with the --production
flag.
$ npm install --production
Top comments (0)