Connect a Node.js Application with MongoDB in Microsoft Azure 

Connect Node.js with MongoDB in Azure
This tutorial focuses on creating a Node.js app in App Service on Linux and connecting it locally to a MongoDB database.

 

Microsoft Azure App Service is an HTTP-based service for REST APIs, hosting web applications, and mobile back ends. Users can develop these apps in their favorite language like Java, Ruby, .NET, .NET Core, Node.js, Python, or PHP. In addition, azure applications can scale and run on both Linux and Windows-based environments with ease. After this tutorial, you will learn how to create a Node.js application in App Service on Linux and connect it locally to a MongoDB database.

 

Prerequisites

  • Install Git 
  • Install Node.js and Node Package Manager (NPM)
  • Install Microsoft Azure Command-Line Interface 

 

Create Local Node.js Application

To set up the local Node.js project, follow the below steps: 

 

Step 1: Clone the Sample Application 

In order to clone the sample application, follow the below process: 

 

 1. First, switch to a working directory in the terminal window.

cd

 

2. Next, clone the sample repository by executing the following command.

git clone https://github.com/Azure-Samples/mean-todoapp.git

 

Step 2: Run the Application 

Install the required packages and start the application by executing the following commands: 

cd mean-todoapp
npm install
node app.js --alter

 

After the application is fully loaded, users should see a message similar to the one shown below: 

debug: -------------------------------------------------------
debug: :: Fri Jul 09 2021 13:10:34 GMT+0200 (Central European Summer Time)
debug: Environment : development
debug: Port       
: 1337
debug: -------------------------------------------------------

 

To stop the Node.js at any time, press the Ctrl+C keys in the terminal. 

 

Create Production MongoDB 

This tutorial uses Azure Cosmos DB for MongoDB. In this step, users can create a MongoDB database in Azure. When the user’s app is deployed to Azure, it uses this cloud database to store data. Azure Cosmos DB supports MongoDB client connections.

 

Step 1: Create a Resource Group 

A resource group is a logical container into which Azure resources, such as web apps, storage accounts, and databases are deployed and managed. For example, users can choose to delete the entire resource group in one simple step later.

Create a resource group by executing the az group create command in the Cloud Shell. The below example creates a resource group named myResourceGroup in the East Europe location. To see all supported locations for App Service in Free tier, run the az appservice list-locations –sku FREE command.

az group create --name myResourceGroup --location "East Europe"

 

Users should generally create their resource group and the resources in a region near to their customers. When the command finishes, a JSON output will display the resource group properties.

 

Step 2: Create an Azure Cosmo DB Account 

>> Note: We are using the paid version of Azure Cosmos DB databases in this tutorial. To use a free Azure Cosmos DB account for seven days, users can use the Try Azure Cosmos DB for free experience. Click the Create button in the MongoDB tile to create a free MongoDB database on Microsoft Azure. After creating the database, navigate to the Connection String section in the portal and retrieve the Azure Cosmos DB connection string to use later. 

 

To create an Azure Cosmo DB account, follow the below process: 

 Create an Azure Cosmos DB account with the az cosmosdb create command in the Cloud Shell. In the below command, substitute the <cosmosdb-name> placeholder with a unique Cosmos DB name. This name will be used as the part of the Cosmos DB endpoint, https://<cosmosdb-name>.documents.azure.com/, so the Cosmo DB name needs to be unique across all Cosmos DB accounts in Azure. The Cosmo DB name must contain only lowercase letters, hyphen (-) characters and numbers, and between 3 and 50 characters long.

az cosmosdb create --name <cosmosdb-name> --resource-group myResourceGroup --kind MongoDB

 

The –-kind MongoDB parameter mentioned in the above command will enable MongoDB client connections. When the Azure Cosmos DB account is created, the Azure CLI shows information similar to the one shown below:

{
  "apiProperties": {
    "serverVersion": "3.6"
  },
  "backupPolicy": {
    "periodicModeProperties": {
      "backupIntervalInMinutes": 240,
      "backupRetentionIntervalInHours": 8,
      "backupStorageRedundancy": "Geo"
    },
    "type": "Periodic"
  },
  "capabilities": [
    {
      "name": "EnableMongo"
    }
  ],
  "connectorOffer": null,
  "consistencyPolicy": {
    "defaultConsistencyLevel": "Session",
    "maxIntervalInSeconds": 5,
    "maxStalenessPrefix": 100
  },
  "cors": [],
  "databaseAccountOfferType": "Standard",
  "defaultIdentity": "FirstPartyIdentity",
  "disableKeyBasedMetadataWriteAccess": false,
  "documentEndpoint": "https://<cosmosdb-name>.documents.azure.com:443/",
  ...
  < Output truncated for readability >
}

 

 

Connect the Application to the Production MongoDB 

In this step, we will connect the sample application to the Cosmos DB database that the user just created, using a MongoDB connection string.

 

Step 1: Retrieve the database key.

To connect to the Azure Cosmos DB database, users need the database key. To retrieve the database key, follow the below process: 

Use the az cosmosdb keys list command to retrieve the primary key in the Cloud Shell.

az cosmosdb keys list --name <cosmosdb-name> --resource-group myResourceGroup

 

The Azure Command-Line Interface should display an output similar to the one shown below: 

{
  "primaryMasterKey": "RS4CmUwzGRASJPMoc0kiEvdnKmxyRILC9BWisAYh3Hq4zBYKr0XQiSE4pqx3UchBeO4QRCzUt1i7w0rOkitoJw==",
  "primaryReadonlyMasterKey": "HvitsjIYz8TwRmIuPEUAALRwqgKOzJUjW22wPL2U8zoMVhGvregBkBk9LdMTxqBgDETSq7obbwZtdeFY7hElTg==",
  "secondaryMasterKey": "Lu9aeZTiXU4PjuuyGBbvS1N9IRG3oegIrIh95U6VOstf9bJiiIpw3IfwSUgQWSEYM3VeEyrhHJ4rn3Ci0vuFqA==",
  "secondaryReadonlyMasterKey": "LpsCicpVZqHRy7qbMgrzbRKjbYCwCKPQRl0QpgReAOxMcggTvxJFA94fTi0oQ7xtxpftTJcXkjTirQ0pT7QFrQ=="
}

 

Finally, copy the primaryMasterKey value. 

 

Step 2: Configure the connection string in the sample application

In the local repository, replace the existing content with the following code in config/datastores.js and save the changes.

module.exports.datastores = {
  default: {
    adapter: 'sails-mongo',
    url: process.env.MONGODB_URI,
    ssl: true,
  },
};

 

The ssl: true value is required because Cosmos DB requires TLS/SSL url to be set to an environment variable, which the user will set next.

Set the MONGODB_URI environment variable in the terminal. Ensure to replace the two <cosmosdb-name> placeholders with the Azure Cosmos DB database name and replace the <cosmosdb-key> placeholder with the key the user copied in the previous step.

export MONGODB_URI=mongodb://<cosmosdb-name>:<cosmosdb-key>@<cosmosdb-name>.documents.azure.com:10250/todoapp

 

Step 3: Test the Application with MongoDB 

In a local terminal window, execute the following command:

node app.js --alter

 

After that, navigate to http://localhost:1337 web page. If the user can create and see to-do items, their app reads and writes data using the Azure Cosmos DB database.

Stop Node.js by typing Ctrl+C in the terminal.

 

Conclusion 

This tutorial presents the steps to create a Node.js application in App Service on Linux, connect it locally to a MongoDB database in Microsoft Azure. After this tutorial, if the user wants to deploy a Node.js application to a database in Azure Cosmos DB’s API for MongoDB, follow the steps mentioned in the “Deploy Node.js Application with MongoDB in Microsoft Azure” tutorial. Hope this tutorial was helpful, and do reach out to us if you have any query or suggestions.

Share this post

Services to Explore

Stay up to date!

Stay up to date with the Web Hosting, Cloud and Server Management Industry News and Tutorials!

We will send you only the relevant emails, and we respect your privacy. Please review our privacy policy for more info.

Managed Microsoft Azure Services

Focus on your business, and let us take care of your Azure Cloud Infrastructure!
From what you are reading, it seems you are interested in Azure Cloud and related technologies. If you have a moment to spare, please take a look at our Managed Azure Services, which might interest you even more!
Managed Azure Cloud

Value-Added Services

We have services that can help you run a successful business. With us, you don't have to worry about these areas because our experts will take care of it for you.

Introducing - WPHealers!

Complete WordPress Management, 24x7 Support & White Label Agency Plans!

WordPress migration service, security, white-label reseller services and lot more! Grab the introductory deals now!

WPHealers

ServerHealers uses cookies.