Deploy a Node.js + MongoDB web app to Azure

In this tutorial, you'll deploy a sample Express.js app using a MongoDB database to Azure. The Express.js app will be hosted in Azure App Service, which supports hosting Node.js apps in both Linux (Node versions 12, 14, and 16) and Windows (versions 12 and 14) server environments. The MongoDB database will be hosted in Azure Cosmos DB, a cloud native database offering a 100% MongoDB compatible API.

A diagram showing how the Express.js app will be deployed to Azure App Service and the MongoDB data will be hosted inside of Azure Cosmos DB.

This article assumes you're already familiar with Node.js development and have Node and MongoDB installed locally. You'll also need an Azure account with an active subscription. If you don't have an Azure account, you can create one for free.

Sample application

To follow along with this tutorial, clone or download the sample application from the repository https://github.com/Azure-Samples/msdocs-nodejs-mongodb-azure-sample-app.

git clone https://github.com/Azure-Samples/msdocs-nodejs-mongodb-azure-sample-app.git

Follow these steps to run the application locally:

  • Install the package dependencies by running npm install.
  • Copy the .env.sample file to .env and populate the DATABASE_URL value with your MongoDB URL (for example mongodb://localhost:27017/).
  • Start the application using npm start.
  • To view the app, browse to http://localhost:3000.

1 - Create the Azure App Service

Azure App Service is used to host the Express.js web app. When setting up the App Service for the application, you'll specify:

  • The Name for the web app. It's the name used as part of the DNS name for your webapp in the form of https://<app-name>.azurewebsites.net.
  • The Runtime for the app. It's where you select the version of Node to use for your app.
  • The App Service plan which defines the compute resources (CPU, memory) available for the application.
  • The Resource Group for the app. A resource group lets you group (in a logical container) all the Azure resources needed for the application.

Create Azure resources using the Azure portal, VS Code using the Azure Tools extension pack, or the Azure CLI.

Sign in to the Azure portal and follow these steps to create your Azure App Service resources.

Instructions Screenshot
In the Azure portal:
  1. Enter "app services" in the search bar at the top of the Azure portal.
  2. select the item labeled App Services under the under Services heading on the menu that appears below the search bar.
A screenshot showing how to use the search box in the top tool bar to find App Services in Azure.
On the App Services page, select + Create A screenshot showing the create button on the App Services page used to create a new web app.
On the Create Web App page, fill out the form as follows.
  1. Resource Group → Select Create new and use a name of msdocs-expressjs-mongodb-tutorial.
  2. Namemsdocs-expressjs-mongodb-XYZ where XYZ is any three random characters. This name must be unique across Azure.
  3. PublishCode.
  4. Runtime stackNode 14 LTS.
  5. Operating SystemLinux.
  6. Region → Any Azure region near you.
  7. Linux Plan → Select Create new and use a name of msdocs-expressjs-mongodb-plan.
  8. Sku and size → Select Change size to select a different App Service plan.
A screenshot showing the form to fill out to create a web app in Azure.
The App Service plan controls how many resources (CPU/memory) are available to your app and the cost of those resources. You can learn more about choosing an App Service plan in the article App Service plan overview. For a full list of App Service plans, view the App Service pricing page.

For this example, select Dev / Test at the top of the screen and select B1 (Basic) plan. The B1 Basic plan will incur a small charge against your Azure account but offers better performance than the F1 (Free) plan.

When finished, select Apply to apply your changes.
A screenshot of the Spec Picker dialog that lets you select the App Service plan to use for your web app.
On the main Create Web App page, select the *Review + create button at the bottom of the screen.

This will take you to the Review page. Select Create to create your App Service.
A screenshot of the main web app create page showing the button to select on to create your web app in Azure.

2 - Create an Azure Cosmos DB in MongoDB compatibility mode

Azure Cosmos DB is a fully managed NoSQL database for modern app development. Among its features are a 100% MongoDB compatible API allowing you to use your existing MongoDB tools, packages, and applications with Cosmos DB.

You must sign in to the Azure portal to finish these steps to create a Cosmos DB.

Instructions Screenshot
In the Azure portal:
  1. In the search bar at the top of the Azure portal, enter "Cosmos DB".

  2. On the menu that appears below the search bar, under Services, select the item labeled Azure Cosmos DB.

A screenshot showing how to use the search box in the top tool bar to find Cosmos DB in Azure.
On the Azure Cosmos DB page, select + Create A screenshot showing the create button on the Cosmos DB page used to create a database.
A page will appear asking you to select an API option for your Cosmos DB database.Choose Azure Cosmos DB API for MongoDB. A screenshot showing the page where you select the MongoDB API for your Cosmos DB.
On the Create Azure Cosmos DB Account page, fill out the form as follows.
  1. For the Resource Group, choose the same resource group from the dropdown list as you used for your web app in App Service (msdocs-expressjs-mongodb-quickstart). This logically groups together all of the components needed for this application together in the same resource group for easier discoverability and management.

  2. Enter an Account Name of msdocs-expressjs-mongodb-database-XYZ for the name of the Azure CosmosDb instance where XYZ is any three unique characters. Cosmos DB account names must be unique across Azure. The name must be between 3 and 44 characters in length and only contain lowercase letters, numbers and the hyphen (-) symbol.

  3. For the Location, select the same Azure location as you used for your App service web app. It is important to host your application and database in the same Azure location to minimize network latency between different components of the solution.

  4. If the Free Tier Discount is available for your account, you may apply it.

  5. Select Review + create to go to the confirmation page and then select Create to create your database.

Creating a new Azure CosmosDB typically takes about 5 minutes.
A screenshot showing how to fill out the page to create a new Cosmos DB.

3 - Connect your App Service to your Cosmos DB

To connect to your Cosmos DB database, you need to provide the connection string for the database to your application. It's done in the sample application by reading the DATABASE_URL environment variable. When you locally run it, the sample application uses the dotenv package to read the connection string value from the .env file.

When you run in Azure, configuration values like connection strings can be stored in the application settings of the App Service hosting the web app. These values are then made available to your application as environment variables during runtime. In this way, the application uses the connection string from process.env the same way whether being run locally or in Azure. Further, it eliminates the need to manage and deploy environment specific config files with your application.

Instructions Screenshot
Navigate to your Cosmos DB account. If you have just created your Cosmos DB account, you can select the Go to resource button to be taken directly to the account. Or you can use the search box at the top of the screen to search for and navigate to your Cosmos DB database.
  1. On the page for your Cosmos DB, make sure the Quick start item is selected in the left menu. You will see text box labeled Primary Connection String. While there are tabs for different languages, the connection string is the same regardless of language.
  2. Copy the value of the connection string into your clipboard buffer.
A screenshot showing the location of the Cosmos DB connection string on the Cosmos DB quick start page.
Navigate back to your App Service instance to set the connection string for your web app.

  1. In the search box at the top of the screen, type the name of your App Service (msdocs-expressjs-mongodb-XYZ).
  2. Select your App Service when it appears under the Resources section of the dialog to go to the App Service.
A screenshot showing how to search for and go to the App Service, where the connection string needs to store the connection string.
On the page for the App Service:
  1. Select the Configuration item under Settings.
  2. In the Application settings section (not the Connection strings section), select the + New application setting menu item to add a setting.
A screenshot showing how to use the Application settings within an App Service.
In the Add/Edit application setting dialog, set the Name of the setting to DATABASE_URL to match the name used in the application code. Then paste the connection string value for your database into the Value field.Select OK to save this setting. A screenshot showing the dialog used to set an application setting in Azure App Service.

4 - Deploy application code to Azure

Azure App service supports multiple methods to deploy your application code to Azure including support for GitHub Actions and all major CI/CD tools. This article focuses on how to deploy your code from your local workstation to Azure.

To deploy your application code directly from VS Code, you must have the Azure Tools extension pack installed and be signed into Azure from VS Code.

Instructions Screenshot
Locate the Azure icon in the left-hand toolbar and select it to bring up the Azure Tools for VS Code extension. A screenshot showing the location of the Azure Tool icon in Visual Studio Code.
Find the App Service section in the Azure Tools extension and then locate your web app under the correct subscription. Right-click on the web app and then select Deploy to Web App... from the menu. A screenshot showing how you deploy an application to Azure by right-clicking on a web app in VS Code and selecting deploy from the context menu.
A dialog box will appear at the top of the window to choose the directory to deploy from. Choose the root directory of where the source code is for your application.

A dialog will prompt you to run build commands on the target server. Answering Yes to this question will improve performance for future deployments.
A screenshot showing the dialog box used to select the deployment directory in VS Code.
A notification will appear in the bottom right-hand corner of VS Code to inform you the deployment is underway. When deployment is complete, this notification will be replaced by a dialog box allowing you to browse to the website. A screenshot showing the Output window of VS Code while deploying an application to Azure.

5 - Browse to the application

The application will have a url of the form https://<app name>.azurewebsites.net. Browse to this URL to view the application.

Use the form elements in the application to add and complete tasks.

A screenshot showing the application running in a browser.

6 - Configure and view application logs

Azure App Service captures all messages logged to the console to assist you in diagnosing issues with your application. The sample app outputs console log messages in each of its endpoints to demonstrate this capability. For example, the get endpoint outputs a message about the number of tasks retrieved from the database and an error message appears if something goes wrong.

router.get('/', function(req, res, next) {
  Task.find()
    .then((tasks) => {      
      const currentTasks = tasks.filter(task => !task.completed);
      const completedTasks = tasks.filter(task => task.completed === true);

      console.log(`Total tasks: ${tasks.length}   Current tasks: ${currentTasks.length}    Completed tasks:  ${completedTasks.length}`)
      res.render('index', { currentTasks: currentTasks, completedTasks: completedTasks });
    })
    .catch((err) => {
      console.log(err);
      res.send('Sorry! Something went wrong.');
    });
});

The contents of the App Service diagnostic logs can be reviewed in the Azure portal, VS Code, or using the Azure CLI.

Instructions Screenshot
First, you need to enabled streaming logs in Azure App Service. Navigate to page for the App Service instance in the Azure portal.

  1. Select the App Service logs under the Monitoring heading in the menu on the left side of the page.
  2. Change the Application Logging property from Off to **File System.
  3. Enter a retention period of 30 days for the logs.
  4. Select Save to save your changes.
A screenshot showing the location of the Azure Tool icon in Visual Studio Code.
Select the Log stream item from the menu under the Monitoring section. Refresh the home page in the app or attempt other requests to generate some log messages.

You will see any log messages generated by your app and messages generated by the service in the output.
A screenshot showing how you deploy an application to Azure by right-clicking on a web app in VS Code and selecting deploy from the context menu.

7 - Inspect deployed files using Kudu

Azure App Service provides a web-based diagnostics console named Kudu that lets you examine the server hosting environment for your web app. Using Kudu, you can view the files deployed to Azure, review the deployment history of the application, and even open an SSH session into the hosting environment.

To access Kudu, go to one of the following URLs. You'll need to sign into the Kudu site with your Azure credentials.

  • For apps deployed in Free, Shared, Basic, Standard, and Premium App Service plans - https://<app-name>.scm.azurewebsites.net.
  • For apps deployed in Isolated service plans - https://<app-name>.scm.<ase-name>.p.azurewebsites.net.

From the main page in Kudu, you can access information about the application hosting environment, app settings, deployments, and browse the files in the wwwroot directory.

A screenshot of the main page in the Kudu SCM app showing the different information available about the hosting environment.

Selecting the Deployments link under the REST API header will show you a history of deployments of your web app.

A screenshot of the deployments JSON in the Kudu SCM app showing the history of deployments to this web app.

Selecting the Site wwwroot link under the Browse Directory heading lets you browse and view the files on the web server.

A screenshot of files in the wwwroot directory showing how Kudu lets you to see what has been deployed to Azure.

Clean up resources

When you're finished, you can delete all the resources from Azure by deleting the resource group for the application.

Follow these steps while you're signed-in to the Azure portal to delete a resource group.

Instructions Screenshot
Navigate to the resource group in the Azure portal.
  1. Enter the name of the resource group in the search bar at the top of the page.
  2. Under the Resource Groups heading in the dialog below, select the name of the resource group to navigate to it.
A screenshot showing how to search for and go to a resource group in the Azure portal.
Select the Delete resource group button at the top of the page. A screenshot showing the location of the Delete Resource Group button in the Azure portal.
In the confirmation dialog, enter the name of the resource group to confirm deletion. Select the Delete button at the bottom of the page to delete the resource group. A screenshot of the confirmation dialog for deleting a resource group in the Azure portal.

Next steps