Part 2 in a series of Articles about how to Deploy NestJS to Production.
- Part 1: Deploy NestJS to Zeit Now.sh
- Part 2: Deploy NestJS to Azure Functions (this article)
- ... more to come ...
Serverless NestJS with Microsoft Azure
In this article we'll be looking at how to deploy serverless NestJS applications to the cloud platform Azure Functions in only a few minutes!
If you're not familiar with NestJS, it is a TypeScript Node.js framework that helps you build enterprise-grade efficient and scalable Node.js applications.
Incase you missed the announcement, the integration between NestJS & Azure was just teased at the other week!
— Asim Hussain (@jawache) July 30, 2019Serverless #NestJS anyone?
Now you can add serverless support via Azure to *any* NestJS application by just running this one command:
nest add @nestjs/azure-func-http
🔥🤯😻
Big 🙏to @kammysliwiec and @codebeast, @manekinekko, @nthonyChu pic.twitter.com/qoOYoHukS7
Before we dive further, let's take a step back to make sure we have a good understanding about Azure Functions and how they can play a role in handling our serverless NestJS applications.
What are Azure Functions ?
Azure Functions are a serverless computing execution service that enables you to run code on-demand without having to manage the allocation of machine resources, servers, etc. Write your NestJS code, deploy it - and let Azure Functions handle the rest!
Azure functions can let you create functions that execute based on events, read more in the official Azure Functions documentation here.
Azure let's you deploy a myriad of different frameworks/languages, from C# to JavaScript/TypeScript.
NestJS is a TypeScript-based Node.js framework after all - so let's take a look at how we utilize the fantastic Azure platform to deploy our serverless applications!
Getting NestJS setup
NOTE: In this demonstration, we'll be showcasing a new NestJS application generated by the CLI, but if you prefer to use an existing NestJS application - feel free - and to skip ahead to the next section about Schematics.
☁ npm i -g @nestjs/cli☁ nest new PROJECT_NAME
Now let's cd
into the newly created directory and open up our IDE. At this point we have a simple generated NestJS Application.
📯 Introducing NestJS Azure Functions Schematics
At Trilon, we've been working with some amazing individuals over on the Microsoft Azure team to create a seamless integration between NestJS + Azure Functions. Allowing you to effortlessly deploy your new/existing services to the cloud!
These NestJS schematics allow you to instantly setup your application with all the scaffolding required for the integration, with one simple command. More on this later!
Installing NestJS Azure Functions Schematics
In your terminal, make sure you're at the root directory of your project and type:
$ nest add @nestjs/azure-func-http
Example output:
✔ Installation in progress... ☕CREATE /.funcignore (66 bytes)CREATE /host.json (23 bytes)CREATE /local.settings.json (116 bytes)CREATE /proxies.json (72 bytes)CREATE /main/function.json (294 bytes)CREATE /main/index.ts (287 bytes)CREATE /main/sample.dat (23 bytes)CREATE /src/main.azure.ts (321 bytes)UPDATE /package.json (1827 bytes)
Excellent! You now have your NestJS application completely setup for Azure Functions! What's next?
Local Azure Functions development
Next, we're going to utilize the Azure-CLI to test our Azure Functions locally!
If you don't have it installed on your machine yet, make sure to:
- Install Azure Functions Core Tools
- Install the Azure CLI
Once you have everything installed, make sure it was setup right by entering func --version
in your terminal.
With the Azure-CLI all setup, let's fire up our Local Azure Functions environment and see everything in action!
IMPORTANT: Build NestJS first. Since it's written in TypeScript we need to make sure our application compiles down to JavaScript before letting Azure do the rest!
$ npm run build && func host start
This should output something similar to:
Hosting environment: ProductionContent root path: /Users/yourname/Documents/Trilon/nestjs-azure-functionsNow listening on: http://0.0.0.0:7071Application started. Press Ctrl+C to shut down.Http Functions:main: http://localhost:7071/api/{*segments}
Open up that url http://localhost:7071/api/
in your browser you should see:
It's that easy!
If you're wondering why the URL is prepended with /api/
, take a look at your main.azure.ts
file in the NestJS project. You could update it to whatever you wish, add API versioning (/api/v1/
), etc!
Eventually a real-world application would have all of the URLs all available under this globalPrefix.
# ie:GET /api/products/GET /api/products/123POST /api/products
Deploying NestJS to Azure Functions
Stay tuned for future announcements as we will be introducing nest deploy azure
and other great integrations that will simplify this process even further!
NOTE: To deploy Azure Functions, you'll need an Azure Account (new accounts get 12 months of free services).
When it comes to Deploying your NestJS app to Azure Functions, there are a few different paths you could take, and it all depends on whether you prefer doing everything in the terminal
or your IDE (ie: VSCode).
In this article we're going to showcase deploying via VSCode as it's a bit simpler! Read more about deploying via the terminal
from the official Azure documentation here.
Install the Azure Functions VSCode Extension
Head over to the Extensions Marketplace in VSCode and search for "Azure Functions"
or download it here.
More information on the extension installation and prerequisites here.
Once installed, you'll notice a new Icon on the left-hand sidebar, select it to open up the Azure Functions options.
1. Login or Signup (to Azure)
2. Hit the "Deploy to Function App" Arrow icon, and select "Create New Function App in Azure".
3. Select a unique name for your Azure Function, and press Enter.
NOTE: This step may take a few moments as it will be creating Storage Groups, and your new Function App. Future deployments will be much faster, not to worry! :)
(Video) How to create a Node.js Azure Function in the Azure Portal [7 of 12]
Deployed!
When everything is finished, check in the Output
tab (shown above) that your deployment has been finished!
# --- output similar to ---# ... etc etc ...1:54:52 PM nestjs-azure-demo: Deployment successful.1:55:08 PM nestjs-azure-demo: Waiting for long running command to finish...Deployment to "nestjs-azure-demo" completed.HTTP Trigger Urls: main: https://nestjs-azure-demo.azurewebsites.net/api/%7B*segments%7D
Serverless NestJS deployed to the ☁ !
If you've been following along, you should be able to access that URL in your output tab, just make sure to remove the last %7B*segments%7D
portion of the URL.
🐱 Navigate to the URL to see your serverless "Hello World" API in all its eternal glory! 🐱
See the "Hello World" NestJS + Azure Functions live demo:
https://nestjs-azure-demo.azurewebsites.net/apiYou can find the Github code example here
There we have it!
In just a few minutes, we fired up azure functions locally, and learned how to deploy with the new VSCode Azure Functions Extension, taking our serverless NestJS application to the cloud in no time!
Future Plans for NestJS & Azure ✨
It's our mission to make this entire process even simpler in the future!
Stay tuned for more articles and updates on the upcoming
nest deploy azure
, and other amazing Azure integrations! ✨Azure Storage, improved serverless support, and much more!
(Video) Node.js Azure Functions Introduction
Keep reading more about Azure & NestJS:
📚 Introducing NestJS Azure Table Storage integration by Wassim Chegham.
In Conclusion
- Azure Functions let you deploy your NestJS applications to the cloud with ease, letting you use all of your other favorite Azure tools from within your application.
- Make sure your scripts are building your NestJS before deploying.
- Deploy through either the command-line or through IDE Extensions
- More NestJS & Azure integrations coming soon!
- Enjoy the ☁ responsibly!
FAQs
How do I deploy NestJS app to Azure? ›
- Go to Pipelines and create New pipeline .
- Select Azure Repos Git (YAML) , there are other options as classic editor without YAML.
- Select your code repository.
- Select Node. ...
- Select the web app where you will deploy.
- Modify your current YAML and add the following points: ...
- Save and run the pipeline.
During scale-out, there's currently a limit of 500 instances per subscription per hour for Linux apps on a Consumption plan. In some regions, Linux apps on a Premium plan can scale to 100 instances. For more information, see the Premium plan article.
What is the maximum execution time for Azure durable functions? ›For JavaScript, Python, and PowerShell apps, Durable timers are limited to six days. To work around this limitation, you can use the timer APIs in a while loop to simulate a longer delay.
- Create a Procfile in the root of your project and add the following lines. ...
- Now you need to add the deploy script to the package.json file "deploy": "npm install && npm run build && npm run start:dev"
Navigate to your app in the Azure portal and select Deployment Center under Deployment. Follow the instructions to select your repository and branch. This will configure a DevOps build and release pipeline to automatically build, tag, and deploy your container when new commits are pushed to your selected branch.
- Sign in to the Azure portal, and then go to your function app.
- On the Overview tab, select Download app content. Select your download options, and then select Download. The downloaded . zip file is in the correct format to be republished to your function app by using . zip push deployment.
Importantly, Azure Functions is not designed to carry out multiple tasks. The service was created to perform one or very few tasks as fast as possible. Azure Functions is not recommended for infrequent, time-sensitive or long and computationally intensive tasks.
Functions in a Consumption plan are limited to 10 minutes for a single execution. In the Premium plan, the run duration defaults to 30 minutes to prevent runaway executions. However, you can modify the host.
How many requests can Azure function handle? ›A single function app only scales out to a maximum of 200 instances.
- You will have to be very much attentive during updating the Azure Durable function app code. ...
- It's tough to generate guides or random numbers.
- It's very difficult to implement Thread. ...
- You cannot call the non-deterministic APIs from the Azure Durable Functions.
What is the maximum execution time for serverless? ›
If you work on a serverless project, you have probably run into the issue of AWS Lambda timeouts handling. Lambda functions are short lived; the Lambda max timeout is 900 seconds (15 minutes).
You can configure the functionTimeout in the host. json file to change the maximum duration of the execution time. In the Azure Portal, you can select you Function App, which contains your functions and under App Files, you can see the host. json file, which allows you to add or change properties.
Where can I deploy my NestJS app? ›- Step 1: Get your app ready. Listen on PORT. Change your start script to production. ...
- Step 2: Connect to GitHub.
- Step 3: Choose a GitHub repo to deploy.
- Step 4: Choose a Deploy Template.
- Step 5: Review settings.
- Step 6: Choose an app name.
- Step 7: Pre-flight checks.
- Deployed! Having trouble?
Do not use NestJS if: You are building micro-services. The level of abstraction is too generic with overly simple examples in the documentation and it does not allow for the level of granular control needed.
Where to host NestJS server? ›NestJS will run on any generic-purpose hosting (Heroku, Vercel, AWS, etc). In your bootstrap function ( main. ts ) use the PORT env var: await app.
App Service Plan SKU | Max Apps |
---|---|
B2, S2, P2v2, I2v1 | 16 |
B3, S3, P3v2, I3v1 | 32 |
P0v3 | 8 |
P1v3, I1v2 | 16 |
Use Azure Pipelines to automatically deploy your web app to Azure App Service on every successful build. Azure Pipelines lets you build, test, and deploy with continuous integration (CI) and continuous delivery (CD) using Azure DevOps. YAML pipelines are defined using a YAML file in your repository.
Right-click the console app project in Solution Explorer, and then select Publish as Azure WebJob. The Add Azure WebJob dialog box appears, with the project selected in the Project name box. Complete the Add Azure WebJob dialog box, and then select OK.
What is the difference between function app and Azure function? ›Functions and Logic Apps are Azure services that enable serverless workloads. Azure Functions is a serverless compute service, whereas Azure Logic Apps is a serverless workflow integration platform. Both can create complex orchestrations.
- From the Azure portal menu or the Home page, select Create a resource.
- In the New page, select Compute > Function App.
- On the Basics page, use the function app settings as specified in the following table: ...
- Select Next : Hosting. ...
- Select Next : Monitoring.
How do I deploy Azure function pipeline? ›
To create a build pipeline in Azure, use the az functionapp devops-pipeline create command. The build pipeline is created to build and release any code changes that are made in your repo. The command generates a new YAML file that defines the build and release pipeline and then commits it to your repo.
Azure Functions is a serverless solution that allows you to write less code, maintain less infrastructure, and save on costs. Instead of worrying about deploying and maintaining servers, the cloud infrastructure provides all the up-to-date resources needed to keep your applications running.
In which situation should you use Azure function app? ›Azure Functions are best suited for smaller apps have events that can work independently of other websites. Some of the common azure functions are sending emails, starting backup, order processing, task scheduling such as database cleanup, sending notifications, messages, and IoT data processing.
But the way they create Azure Functions could be better. First off, they create one file per Azure Function in your solution. That's not an issue if you only have one Azure Function, but it can be problematic if you have many. However, you can get around this by putting multiple Azure Functions in the same file.
What is the timeout for Azure serverless functions? ›Azure Functions in the Consumption plan have a default timeout of 5 minutes and an upper limit of 10 minutes. If you need a longer timeout, you need to switch to a different plan, such as the Premium plan, which provides longer timeouts and dedicated resources.
Azure DNS and Azure Private DNS have a throttle limit of 500 read (GET) operations per 5 minutes.
What is the memory size of Azure functions? ›Memory used by a function is measured by rounding up to the nearest 128 MB, up to the maximum memory size of 1,536 MB, with execution time calculated by rounding up to the nearest 1 ms. The minimum execution time and memory for a single function execution is 100 ms and 128 mb respectively.
Each instance of the function app, whether the app runs on the Consumption hosting plan or a regular App Service hosting plan, might process concurrent function invocations in parallel using multiple threads.
Can Azure function have multiple Functions? ›These functions are often combined into a single function app, but they can also run in separate function apps. In Premium and Dedicated (App Service) hosting plans, multiple function apps can also share the same resources by running in the same plan.
I understand that the limit is maximum 59 characters. When you put 59 characters in the function app name, it deploys successfully.
Is Azure obsolete? ›
This functionality will be fully retired on September 1, 2023. Today, about 90 percent of the IaaS VMs are using Azure Resource Manager.
Multiple apps in the same plan
Function apps in a given plan are all scaled together, so any issues with scaling can affect all apps in the plan.
Azure Functions are cheap. While most cloud services will send a monthly invoice based on how many resources you've provisioned, Azure Functions only bill you for the resources you actively consume. Cost is based on execution time and memory usage for each function invocation.
- Deploy all your Serverless services concurrently and reliably.
- Incrementally deploy only the services that've been updated.
- Optimize how your dependencies are cached.
- Incrementally and concurrently deploy only the Lamda functions that've been updated.
Hobby | Pro | |
---|---|---|
Serverless Function Execution | Up to 100 GB-Hrs | Up to 1000 GB-Hrs |
Edge Function Execution Units | Up to 500,000 | Up to 1,000,000 |
Edge Middleware Invocations | Up to 1,000,000 | Up to 1,000,000 |
Build Execution | Up to 100 Hrs | Up to 400 Hrs |
This is because Serverless Functions have a payload limit of 4.5mb for request and response bodies.
How do I trigger Azure function every 5 minutes? ›The TimerInfo object is passed into the function. The following example function triggers and executes every five minutes. The @TimerTrigger annotation on the function defines the schedule using the same string format as CRON expressions.
- Avoid long running functions. ...
- Make sure background tasks complete. ...
- Cross function communication. ...
- Write functions to be stateless. ...
- Write defensive functions. ...
- Function organization best practices.
For some reason, 1 function takes between 2 to 20 minutes to deploy.
- Who uses NestJS? Some of the most notable companies that use Nest JS to build efficient and scalable server-side applications are Autodesk, Societe Generale, Gojob, Adidas, Decathlon, Rewe Digital, and many others.
- Is NestJS TypeScript? ...
- Is NestJS good for my project?
How to deploy NestJS API free? ›
- Step 1: Registration and Setup. First, we need to create a new account on Cyclic. ...
- Step 2: Deployment. Now we can go to the cyclic dashboard and click on the “Deploy Now” button to start deploying our Nestjs application. ...
- Step 3: Verifying.
- Ensure your Node version is the same as you run locally. ...
- Use the same package manager as you do locally for your Build & Start Commands, (e.g. npm or yarn )
- Install dependencies and build the app in the Build Command, (e.g. npm install; npm build; )
Cons for using the NestJS framework
At some point, most NestJS projects will encounter circular dependencies. This problem is well-documented by both Nest and the community package nestjs-spelunker, which focuses on the overall dependency injection tree.
js is a minimalistic framework that contains all the necessary features to create an application using React. On the other hand, Nest. js is not just a framework but an entire platform for building server-side applications using TypeScript and Node. js.
Is NestJS slower than Express? ›The native version is 42% faster. In my experience, the difference in real applications is even greater. But that also has to do with the fact that we can optimize the application structure better than with Nest.
- Prerequisites.
- Start a NestJS project.
- Configure a PORT environment variable.
- Prepare the Docker image.
- Test the container locally.
- Manually deploying to Cloud Run.
- Check your gcloud CLI project is set.
- Use gcloud run deploy.
- Create an Nx workspace by running the following command: > npx create-nx-workspace@latest.
- Once the workspace is created, install the project dependencies by running the following commands: > cd nestjs-microservices > npm i @nestjs/microservices kafkajs class-validator class-transformer.
- Right-click on App Services and select Create new Web App. ...
- Type a globally unique name for your web app and press Enter. ...
- In Select a runtime stack, select the Node. ...
- In Select a pricing tier, select Free (F1) and wait for the resources to be created in Azure.
- On your nestjs app's terminal window Run npm run build.
- Copy up all the files in your nestjs app's dist folder to the root of your dreamhost site, NOT the public folder.
- Copy up the package.json file to the root, NOT the public folder.
- Run npm install in the root of your site on Dreamhost.
- Create a new VM instance.
- Install nginx.
- Configure nginx to act as a proxy server. Route all traffic to port 80 on your VM to the running instance of the Node. js application on port 3000.
- Install Node. js on the VM and clone the app from the GitHub repo into a folder in the VM.
- Install pm2 globally.
How do I deploy a NodeJS app on Azure DevOps? ›
- NPM task: Set its operation property to install. ...
- Copy files task: This task copies all . ...
- Archive NodeJS app: This task creates the .ZIP file of the whole app. ...
- Publish Artifacts: This task will publish the output artifact with a name “drop”.
- Create a pipeline and select the ASP.NET Core template. ...
- Save the pipeline and queue a build to see it in action.
- Create a release pipeline and select the Azure App Service Deployment template for your stage. ...
- Link the build pipeline as an artifact for this release pipeline.
- Select the subscription where the Azure Web App resource is located.
- Select the Azure Web App resource to which you will publish.
- Select Deploy when prompted with a confirmation dialog.
You can also deploy the VM application to currently running VMs. Select the Extensions + applications option under Settings in the left menu when viewing the VM details in the portal. Choose VM applications and then select Add application to add your VM application.
How to deploy NestJS to Lambda? ›- Application.
- Serverless Dependencies.
- Creating Handler. The yaml file.
- Running the lambda locally. Verify.
- Deploying.
- Writing the Dockerfile.
- Test the container locally.
- Optimize Dockerfile for production.
- Use Alpine node images.
- Add a NODE_ENV environment variable.
- Use npm ci instead of npm install.
- The USER instruction.
- Use multistage builds.
- Create a new folder, and go to it using your preferred command line tool.
- Execute nest new service-a . It will prompt you to choose between npm and yarn. ...
- Delete the files src/app. ...
- Remove the AppService usages from the AppModule .
- Remove the AppService usages from the AppController .
- npm install -g serverless.
- serverless config credentials --provider aws --key <PUBLIC_KEY> --secret <SECRET_KEY>
- mkdir serverless-nodejs-app && cd serverless-nodejs-app.
- Select the following image to sign in to Azure and open a template. The template creates a key vault and a secret.
- Select or enter the following values. Use the default values, when available. ...
- Select Review + create. After validation completes, select Create to create and deploy the VM.
- curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - ...
- sudo apt-get install -y nodejs. ...
- node --version && npm --version. ...
- sudo vi app.js. ...
- const express = require('express') const app = express() const port = 3000 app. ...
- npm install express. ...
- node app.js.
Should I use npm install or npm CI? ›
json file, ensuring a clean and consistent installation. In conclusion, npm ci is a command that developers should consider using instead of npm install for their Node. js projects. It provides consistency, speed, predictability, and automation benefits, making it a valuable tool for any development team.
- Prerequisites.
- Step 1: Create an Azure Resource Group.
- Step 2: Create an Azure Storage Account.
- Step 3: Configure the App Service Plan with Consumption Pricing. Configure App Service Plan using a Windows host. ...
- Step 4: Configure the Azure Function App. ...
- Conclusion.