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.
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.
Sign in to the Azure portal and follow these steps to create your Azure App Service resources.
Instructions
Screenshot
In the Azure portal:
Enter "app services" in the search bar at the top of the Azure portal.
select the item labeled App Services under the under Services heading on the menu that appears below the search bar.
On the App Services page, select + Create
On the Create Web App page, fill out the form as follows.
Resource Group → Select Create new and use a name of msdocs-expressjs-mongodb-tutorial.
Name → msdocs-expressjs-mongodb-XYZ where XYZ is any three random characters. This name must be unique across Azure.
Publish → Code.
Runtime stack → Node 14 LTS.
Operating System → Linux.
Region → Any Azure region near you.
Linux Plan → Select Create new and use a name of msdocs-expressjs-mongodb-plan.
Sku and size → Select Change size to select a different App Service plan.
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.
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.
To create Azure resources in VS Code, you must have the Azure Tools extension pack installed and be signed into Azure from VS Code.
Locate the Azure icon in the left-hand toolbar and select it to bring up the Azure Tools for VS Code extension.
In the Azure Tools extension for VS Code:
Locate the App Service section in the Azure Tools extension
Right-click on the Azure subscription you want to create the web app in.
Select Create New Web App...(Advanced) from the context menu. Be sure to select the Advanced option.
Enter a name for the app in the dialog box. For this example, give your web app a name of msdocs-expressjs-mongodb-XYZ where XYZ is any three random characters. This name must be unique across Azure.
The fully qualified domain name of your app will be https://<app name>.azurewebsites.net.
Select + Create new resource group to create a new resource group.
Enter a name of msdocs-expressjs-mongodb-tutorial for the resource group.
The dialog box will now display a list of available runtimes for your web app. Choose the option Node 14 LTS for this example.
Select an OS to use for the web hosting environment. For this example, select Linux.
Select a location close to you where your web app will be run.
Select + Create new App Service plan.
Enter a name of msdocs-expressjs-mongodb-plan for the App Service plan name.
It is recommended to select the Basic (B1) pricing tier for this example.
The Basic (B1) tier will incur a small charge against your Azure account but provides better performance than the Free (F1) pricing tier.
Select Skip for now when prompted to select a new Application Insights resource.
# Use 'az account list-locations --output table' to list locations
LOCATION='eastus'
RESOURCE_GROUP_NAME='msdocs-expressjs-mongodb-tutorial'
az group create \
--location $LOCATION \
--name $RESOURCE_GROUP_NAME
# Use 'az account list-locations --output table' to list locations
$location='eastus'
$resourceGroupName='msdocs-expressjs-mongodb-tutorial'
# Create a resource group
az group create `
--location $location `
--name $resourceGroupName
The --sku parameter defines the size (CPU, memory) and cost of the app service plan. This example uses the F1 (Free) service plan. For a full list of App Service plans, view the App Service pricing page.
The --is-linux flag selects the Linux as the host operating system. To use Windows, remove this flag from the command.
APP_SERVICE_PLAN_NAME='msdocs-expressjs-mongodb-plan'
az appservice plan create \
--name $APP_SERVICE_PLAN_NAME \
--resource-group $RESOURCE_GROUP_NAME \
--sku B1 \
--is-linux
$appServicePlanName='msdocs-expressjs-mongodb-plan'
az appservice plan create `
--name $appServicePlanName `
--resource-group $resourceGroupName `
--sku B1 `
--is-linux
Finally, create the App Service web app using the az webapp create command.
The app service name is used as both the name of the resource in Azure and to form the fully qualified domain name for your app in the form of https://<app service name>.azurewebsites.com.
The runtime specifies what version of Node your app is running. This example uses Node 14 LTS. To list all available runtimes, use the command az webapp list-runtimes --os linux --output table for Linux and az webapp list-runtimes --os windows --output table for Windows.
# Change 123 to any three characters to form a unique name across Azure
APP_SERVICE_NAME='msdocs-expressjs-mongodb-123'
az webapp create \
--name $APP_SERVICE_NAME \
--runtime 'NODE|14-lts' \
--plan $APP_SERVICE_PLAN_NAME \
--resource-group $RESOURCE_GROUP_NAME \
--query 'defaultHostName' \
--output table
# Change 123 to any three characters to form a unique name across Azure
$appServiceName='msdocs-expressjs-mongodb-123'
az webapp create `
--name $appServiceName `
--runtime 'NODE:14-lts' `
--plan $appServicePlanName `
--resource-group $resourceGroupName `
--query 'defaultHostName' `
--output table
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:
In the search bar at the top of the Azure portal, enter "Cosmos DB".
On the menu that appears below the search bar, under Services, select the item labeled Azure Cosmos DB.
On the Azure Cosmos DB page, select + Create
A page will appear asking you to select an API option for your Cosmos DB database.Choose Azure Cosmos DB API for MongoDB.
On the Create Azure Cosmos DB Account page, fill out the form as follows.
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.
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.
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.
If the Free Tier Discount is available for your account, you may apply it.
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.
Instructions
Screenshot
Locate and select the Databases section in the Azure Tools extension for VS Code. Select the plus sign (+) to create a new database.
At the top of the VS Code Window, a dialog box will appear.Select the Azure subscription where the database will be created. This should be the same subscription you used when you created your App Service.
Select Azure Cosmos DB for MongoDB API as the type of database you want to create from the dialog.
Enter a name for the database in the dialog box. For this example, give your database a name of msdocs-expressjs-mongodb-XYZ where XYZ are any three random characters. Cosmos DB account names must be unique across Azure and the name must be between 3 and 44 characters long and only contain lowercase letters, numbers, and the hyphen (-) symbol.
Select Provisioned Throughouput for the throughput dialog.
Select the resource group to create your Cosmos DB in. The resource group should be the same as your App Service as it typical to group all of the Azure resources needed for one application together in a single resource group for ease of management.
Select the location of where your Cosmos DB will be created. This should be the same as the location as your App Service as you always want your application and database running in the same location.
A new Azure Cosmos DB account is created by using the az cosmosdb create command.
The name of the Cosmos DB account must be unique across Azure. The name can only contain lowercase letters, numbers, and the hyphen (-) character and must be between 3 and 50 characters long.
The --kind MongoDB flag tells Azure to create a Cosmos DB that is compatible with the MongoDB API. This flag must be included for your Cosmos DB to work as a MongoDB database.
# Replace 123 with any three characters to form a unique name
COSMOS_DB_NAME='msdocs-expressjs-mongodb-database-123'
az cosmosdb create \
--name $COSMOS_DB_NAME \
--resource-group $RESOURCE_GROUP_NAME \
--kind MongoDB
# Replace 123 with any three characters to form a unique name
$cosmosDbName='msdocs-expressjs-mongodb-database-123'
az cosmosdb create `
--name $cosmosDbName `
--resource-group $resourceGroupName `
--kind MongoDB
Creating a new Azure Cosmos DB typically takes about 5 minutes.
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.
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.
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.
Copy the value of the connection string into your clipboard buffer.
Navigate back to your App Service instance to set the connection string for your web app.
In the search box at the top of the screen, type the name of your App Service (msdocs-expressjs-mongodb-XYZ).
Select your App Service when it appears under the Resources section of the dialog to go to the App Service.
On the page for the App Service:
Select the Configuration item under Settings.
In the Application settings section (not the Connection strings section), select the + New application setting menu item to add a setting.
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.
Instructions
Screenshot
In the Databases section of the Azure Tools extension for VS Code:
Locate the database for your application and right-click on your database.
Select Copy Connection String from the context menu to copy the connection string to your clipboard.
Locate the App Service section of the Azure Tools for VS Code extension.
Find your application and select the caret symbol (>) to expand the properties of the application.
Right-click on the Application Settings item and select Add New Setting... from the context menu.
Enter the name of DATABASE_URL in the dialog box that appears at the top of the VS Code editor window.
This name needs to be the same as the environment variable name used to read the setting in code.
Enter the value (paste from clipboard) of the connection string in the next dialog box that appears.
The application setting is now saved in Azure App Service.
To view this or any other app settings for the app, expand the Application Settings node under the application in the Azure Tools extension and select the eyeball icon. Right-clicking on a setting allows you to edit or delete a setting.
To get the connection string for a Cosmos DB database, use the az cosmos keys list command.
The az webapp config appsettings command is used to set application setting values for an App Service web app. One or more key-value pairs are set using the --settings parameter. To set the DATABASE_URL value to the connection string for your web app, use the following command.
az webapp config appsettings set \
--name $APP_SERVICE_NAME \
--resource-group $RESOURCE_GROUP_NAME \
--settings DATABASE_URL=$COSMOS_DB_CONNECTION_STRING
az webapp config appsettings set `
--name $appServiceName `
--resource-group $resourceGroupName `
--settings DATABASE_URL=$cosmosDbConnectionString
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.
Locate the Azure icon in the left-hand toolbar and select it to bring up the Azure Tools for VS Code extension.
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 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 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.
You can deploy your application code from a local Git repository to Azure by configuring a Git remote in your local repo pointing at Azure to push code to. The URL of the remote repository and Git credentials needed for configuration can be retrieved using either the Azure portal or the Azure CLI.
Enter the name of your App Service in the search box at the top of the screen.
The App Service will appear under the Resources heading. Select the App Service to navigate to it.
On the page for the App Service:
Select Deployment Center from the menu on the left side of the screen.
In the dropdown list labeled Source, select Local Git.
Select Save from the top menu bar.
After saving, the page will refresh and display the address for the remote Git repository.
Copy the value of the Git Clone Uri as this value will be used to set up a Git remote in a later step.
On the Deployment Center page
Navigate to the Local Git/FTPS credentials tab.
Locate the username and password under the Application Scope credentials.
Keep this screen open so you can use these credentials momentarily when you deploy your code to the remote repository.
When you push code to the remote Git repository for the first time, these credentials are needed to authenticate to the remote repository.
First, configure the deployment source for your web app to be local Git using the az webapp deployment command.
Retrieve the deployment credentials for your application. These will be needed for Git to authenticate to Azure when you push code to Azure in a later step.
Next, let's add an Azure origin to our local Git repo using the App Service Git deployment URL from the step where we created our App Service. Make sure to replace your app name in the url below. You can also get this completed URL from the Azure Portal Local Git/FTPS Credentials tab.
You can now push code from your local Git repository to Azure using the Git remote you just configured.
## Master is the default deployment branch for App Service - this will ensure our local main branch works for the deployment
git push azure main:master
The first time you push code to Azure, Git will prompt you for the Azure deployment credentials you obtained in a previous step. Git will then cache these credentials so you will not have to re-enter them on subsequent deployments.
Applications can be deployed to Azure by creating a ZIP file of the application artifacts and uploading the ZIP file to Azure. ZIP files can be uploaded to Azure using the Azure CLI or a HTTP client like Postman or cURL.
There are two approaches of deploying a ZIP file to Azure:
Deploying a ZIP file that contains all artifacts (such as node_modules) needed for the application.
Deploying a ZIP file only containing the application source code and making use of Azure's build automation.
In this tutorial, you will enable build automation in Azure App Service. By enabling build automation, App Service will run build tasks like npm for you such that you only need to include your application source code in your zip file.
Enable build automation
To enable build automation, set the SCM_DO_BUILD_DURING_DEPLOYMENT app setting in either the Azure portal or Azure CLI.
# Change these values to the ones used to create the App Service.
RESOURCE_GROUP_NAME='msdocs-expressjs-mongodb-tutorial'
APP_SERVICE_NAME='msdocs-expressjs-mongodb-123'
az webapp config appsettings set \
--resource-group $RESOURCE_GROUP_NAME \
--name $APP_SERVICE_NAME \
--settings SCM_DO_BUILD_DURING_DEPLOYMENT=true
# Change these values to the ones used to create the App Service.
$resourceGroupName='msdocs-expressjs-mongodb-tutorial'
$appServiceName='msdocs-expressjs-mongodb-123'
az webapp config appsettings set `
--resource-group $resourceGroupName `
--name $appServiceName `
--settings SCM_DO_BUILD_DURING_DEPLOYMENT=true
Create a ZIP file of your application
Create a ZIP file of your application. You only need to include the application source code and should not include any files or directories that start with a dot (.) such as .env, .gitignore, .github, or .vscode. You also should not include the node_modules directory since you enabled build automation in the last step.
# Change these values to the ones used to create the App Service.
RESOURCE_GROUP_NAME='msdocs-python-webapp-quickstart'
APP_SERVICE_NAME='msdocs-python-webapp-quickstart-123'
az webapp deploy \
--name $APP_SERVICE_NAME \
--resource-group $RESOURCE_GROUP_NAME \
--src-path <zip-file-path>
# Change these values to the ones used to create the App Service.
$resourceGroupName='msdocs-python-webapp-quickstart'
$appServiceName='msdocs-python-webapp-quickstart-123'
az webapp deploy `
--name $appServiceName `
--resource-group $resourceGroupName `
--src-path <zip-file-path>
To use Postman to upload your ZIP file to Azure, you will need the deployment username and password for your App Service. These credentials can be obtained from the Azure portal.
On the page for the web app, select Deployment center from the menu on the left side of the page.
Select the FTPS credentials tab.
The Username and Password are shown under the Application scope heading. For zip file deployments, only use the part of the username after the \ character that starts with a $, for example $msdocs-python-webapp-quickstart-123. These credentials will be needed when uploading your zip file with Postman.
In Postman, upload your file using the following steps.
Instructions
Screenshot
Click on the plus (+) sign icon to create a new request.
Select POST for the request type.
Enter the url https://\<app-name\>.scm.azurewebsites.net/api/zipdeploy where <app-name> is the name of the web app. This URL is the endpoint used to deploy a ZIP file to your Azure service.
In the Authorization tab:
Set the Type to Basic.
Enter the deployment username and password obtained from the Azure portal above. Be sure to only use the portion of the username after the \ character that starts with a $.
In the Body tab:
Select binary as the content type.
USe the Select File button to select your zip file.
The filename of the file to be uploaded will be shown in the Body section.
Select the Send button to upload your zip file to Azure.
Depending on your network bandwidth, files usually take between 10 and 30 seconds to upload to Azure.
Depending on your network bandwidth, files usually take between 10 and 30 seconds to upload to Azure.
To use cURL to upload your ZIP file to Azure, you will need the deployment username and password for your App Service. These credentials can be obtained from the Azure portal.
On the page for the web app, select Deployment center from the menu on the left side of the page.
Select the FTPS credentials tab.
The Username and Password are shown under the Application scope heading. For zip file deployments, only use the part of the username after the \ character that starts with a $, for example $msdocs-python-webapp-quickstart-123. These credentials will be needed in the cURL command.
Run the following curl command to upload your zip file to Azure and deploy your application.
Depending on your network bandwidth, files usually take between 10 and 30 seconds to upload 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.
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.
First, you need to enabled streaming logs in Azure App Service. Navigate to page for the App Service instance in the Azure portal.
Select the App Service logs under the Monitoring heading in the menu on the left side of the page.
Change the Application Logging property from Off to **File System.
Enter a retention period of 30 days for the logs.
Select Save to save your changes.
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.
Instructions
Screenshot
First, you need to enabled streaming logs in Azure App Service.
In the App Service section of the Azure Tools for VS Code extension, right-click on your App Service instance and select Start Streaming Logs from the menu.
The console logs appear in VS Code's Output window. 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 as well as other messages generated by the service in the output.
First, you need to configure Azure App Service to output logs to the App Service filesystem using the az webapp log config command.
az webapp log tail \
--name $APP_SERVICE_NAME \
--resource-group $RESOURCE_GROUP_NAME
az webapp log tail `
--name $appServiceName `
--resource-group $resourceGroupName
Refresh the home page in the app or attempt other requests to generate some log messages. The output should look similar to the following.
2021-10-26T20:12:01.825485319Z npm start
2021-10-26T20:12:04.478474807Z npm info it worked if it ends with ok
2021-10-26T20:12:04.496736134Z npm info using npm@6.14.10
2021-10-26T20:12:04.497958909Z npm info using node@v14.15.1
2021-10-26T20:12:05.874225522Z npm info lifecycle todolist@0.0.0~prestart: todolist@0.0.0
2021-10-26T20:12:05.891572192Z npm info lifecycle todolist@0.0.0~start: todolist@0.0.0
2021-10-26T20:12:05.941127150Z
2021-10-26T20:12:05.941161452Z > todolist@0.0.0 start /home/site/wwwroot
2021-10-26T20:12:05.941168852Z > node ./bin/www
2021-10-26T20:12:05.941173652Z
2021-10-26T20:12:16.234642191Z Mongoose connection open to database
2021-10-26T20:12:19.360371481Z GET /robots933456.txt 404 2144.146 ms - 1497
2021-10-26T20:12:38.419182028Z Total tasks: 6 Current tasks: 3 Completed tasks: 3
2021-10-26T20:12:38.799957538Z GET / 304 500.485 ms - -
2021-10-26T20:12:38.900597945Z GET /stylesheets/style.css 304 2.574 ms - -
2021-10-26T20:12:38.900637447Z GET /css/bootstrap.css 304 12.300 ms - -
2021-10-26T20:12:38.903103684Z GET /images/Azure-A-48px-product.svg 304 8.896 ms - -
2021-10-26T20:12:38.904441659Z GET /js/bootstrap.min.js 304 9.372 ms - -
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.
Selecting the Deployments link under the REST API header will show you a history of deployments of your web app.
Selecting the Site wwwroot link under the Browse Directory heading lets you browse and view the files on the web server.
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.
Enter the name of the resource group in the search bar at the top of the page.
Under the Resource Groups heading in the dialog below, select the name of the resource group to navigate to it.
Select the Delete resource group button at the top of the page.
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.
Instructions
Screenshot
In the Azure Tools extension for VS Code:
Locate the section named Resource Groups and right-click on the name of the resource group you want to delete.
Select Delete from the menu.
Enter the name of the resource group in the dialog box to confirm deletion of the resource group.
Delete the resource group by using the az group delete command.
RESOURCE_GROUP_NAME='msdocs-expressjs-mongodb-tutorial'
# Removing a resource group will delete all Azure resources inside the resource group!
az group delete \
--name $RESOURCE_GROUP_NAME
$resourceGroupName='msdocs-expressjs-mongodb-tutorial'
# Removing a resource group will delete all Azure resources inside the resource group!
az group delete `
--name $resourceGroupName