How to Set Up a Pipeline for Deploying Serverless Node.js on Azure

Written by nuralem | Published 2023/05/25
Tech Story Tags: nodejs | azure | devops | serveless | cicd | pipeline | node.js-development | microsoft-azure

TLDRThis article is specially tailored to provide you with a gentle, yet comprehensive, introduction to this exciting area of cloud computing. Microsoft Azure is a top-tier cloud services provider that offers a robust platform for serverless applications. In this guide, we'll be using Azure Functions, a serverless computing service that lets you run event-triggered code.via the TL;DR App

Hello, software adventurers!

Today, we'll be embarking on a new journey — a journey where you'll learn how to set up a pipeline to deploy serverless Node.js applications on Azure. If you're new to software development, fear not! This article is specially tailored to provide you with a gentle, yet comprehensive, introduction to this exciting area of cloud computing.

With the rise of cloud computing, the concept of serverless computing has become more prominent. The term "serverless" doesn't mean there are no servers, but rather that you don't have to manage them.

Essentially, it enables you to focus more on writing code and less on infrastructure management. Microsoft Azure is a top-tier cloud services provider that offers a robust platform for serverless applications. In this guide, we'll be using Azure Functions, a serverless computing service that lets you run event-triggered code without having to provision or manage infrastructure.

Article Content

  1. Setting Up Azure Account
  2. Creating A Web App Resource
  3. Creating Node.js Application
  4. Setting Up Azure DevOps Project
  5. Configuring Azure Pipeline
  6. Deploying Your Serverless Application

Let's dive in and start exploring these sections one by one.

Setting Up Azure Account

Before we can deploy anything, we first need to create an Azure account. If you haven't done this before, follow these steps:

  • Visit the Azure portal at https://portal.azure.com.
  • Click on "Create a free account".

Fill in your details and follow the prompts. After all, you'll get $200 in Azure credits and free access to popular services for 12 months.

Creating A Web App Resource

The comprehensive procedure was covered in another article. Our goal is to establish a fully operational web application server, serving as a bridge between our deployment pipeline on dev.azure.com and the previously created web application. Consequently, every change in the branch will trigger an automatic deployment of our web application.

Creating a Node.js Application

To create a "Hello World" application in Node.js, follow these steps:

  1. Install Node.js

If you don't have Node.js installed on your computer, you can download it from https://nodejs.org/. , the latest LTS version of Node.js is 18. Follow the instructions on the website to install it.

  1. Setup Your Project

Create a new directory on your computer where you want your project to reside. Open a terminal or command prompt, navigate to your newly created directory, and initiate a new Node.js project by typing the following command:

npm init -y

The npm init -y command creates a new package.json file in your directory with default values. The package.json file is used to manage the dependencies of your Node.js project.

  1. Create a New JavaScript File

In the same directory, create a new JavaScript file. You can name it anything you like, but for this example, let's call it app.js.

  1. Write the "Hello World" Code

Open app.js file in your preferred text editor and enter the following code:

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
});

server.listen(8080, '0.0.0.0', () => {
    console.log('Server running at http://0.0.0.0:8080/');
});

Also, you need to change the package.json file to run in on Azure:

{
  "name": "hackernoon",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Setting Up Azure DevOps Project

After creating your Azure account and Node.js application, the next step is to create an Azure DevOps project:

  1. Go to the Azure DevOps portal at https://dev.azure.com.

  2. Log in with your Azure account.

  3. Click on "New project" and provide a name and description for the project.

Configuring Azure Pipeline

To set up your automatic deploy pipeline, you need to store the project code somewhere. We need to upload our project to the private Azure git repo (Image 1).

Using git you should upload your code to Azure Repos. Some commands that I have used (inside the project folder I have opened cmd.exe and wrote these commands)

git init
git remote add origin https://<your_name>/<Your name>/hackernoon/_git/hackernoon
git add .
git commit -m "initial"
git push --set-upstream origin master

After doing this, your code will be on Azure Cloud.

Next step, you should click on the “Pipelines“ button (Image 2).

Then “Create Pipeline”. Choose “Azure Repos Git“ (Image 3), then choose Node.js App for Linux (Image 4).

Then the process will ask you to get access to your subscription plan and after all, you will see your Web App name, which you have created earlier (Image 5).

Finally, Azure will create a yaml file for us. We need to change some parameters.

# Node.js Express Web App to Linux on Azure
# Build a Node.js Express app and deploy it to Azure as a Linux web app.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
- master

variables:

  # Azure Resource Manager connection created during pipeline creation
  azureSubscription: '<Your sub>'

  # Web app name
  webAppName: '<Your name>'

  # Environment name
  environmentName: 'Your name'

  # Agent VM image name
  vmImageName: 'ubuntu-latest'

stages:
- stage: Build
  displayName: Build stage
  jobs:
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)

    steps:
    - task: NodeTool@0
      inputs:
        # change this "versionSpec: '10.x' to versionSpec: '18.x'
      displayName: 'Install Node.js'

    - script: |
        npm install
        # Delete this "npm run build --if-present"
        # Delete this "npm run test --if-present"
      displayName: 'npm install, build and test'

    - task: ArchiveFiles@2
      displayName: 'Archive files'
      inputs:
        rootFolderOrFile: '$(System.DefaultWorkingDirectory)'
        includeRootFolder: false
        archiveType: zip
        archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
        replaceExistingArchive: true

    - upload: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
      artifact: drop

- stage: Deploy
  displayName: Deploy stage
  dependsOn: Build
  condition: succeeded()
  jobs:
  - deployment: Deploy
    displayName: Deploy
    environment: $(environmentName)
    pool:
      vmImage: $(vmImageName)
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureWebApp@1
            displayName: 'Azure Web App Deploy: <Your name>'
            inputs:
              azureSubscription: $(azureSubscription)
              appType: webAppLinux
              appName: $(webAppName)
              runtimeStack: 'NODE|10.10'
              package: $(Pipeline.Workspace)/drop/$(Build.BuildId).zip
              startUpCommand: 'npm run start'

Press “Save and run”button. Commit directly to the branch. It will add this new config file to your project. For the first time, you will be asked for permission (Image 6).

Deploying Your Serverless Application

Finally, we can deploy our serverless application to Azure (Image 7). Once the upload is complete, your serverless Node.js application should be live on Azure (Image 8).

And there you have it — you've just set up a pipeline to deploy serverless Node.js applications on Azure! Take a moment to celebrate this accomplishment.

Conclusion

As we wrap up, it's crucial to understand the value of setting up a deployment pipeline for a Serverless Node.js application on Azure. We have demonstrated how, through the use of Azure Functions, Azure DevOps, and other Azure services, you can automate your deployment process, ensuring smoother, more efficient, and error-free deployments.

Incorporating a CI/CD pipeline significantly reduces the risk of deployment-related issues and enhances the overall quality of the software. It promotes an efficient development practice that encourages frequent code changes while providing instant feedback on the success of these changes.

This tutorial should serve as a robust foundation, providing the necessary tools and understanding to further explore the potential of Azure and its integration capabilities. It's now time for you to take this knowledge and apply it to your projects, customizing and optimizing as per your unique requirements.

At the end of the day, the goal is to automate processes, increase productivity, and deliver high-quality, efficient applications, and hopefully, this guide has brought you one step closer to achieving that.

Happy coding!


Written by nuralem | Software engineer
Published by HackerNoon on 2023/05/25