教學課程:在 Azure 中建置 Node.js 和 MongoDB 應用程式Tutorial: Build a Node.js and MongoDB app in Azure

Azure App Service 可提供可高度擴充、自我修復的 Web 主控服務。Azure App Service provides a highly scalable, self-patching web hosting service. 本教學課程示範如何在 Windows 上的 App Service 中建立 Node.js 應用程式,並將其連線到 MongoDB 資料庫。This tutorial shows how to create a Node.js app in App Service on Windows and connect it to a MongoDB database. 完成之後,您的 MEAN 應用程式 (MongoDB、Express、AngularJS 及 Node.js) 將會在 Azure App Service 中執行。When you're done, you'll have a MEAN application (MongoDB, Express, AngularJS, and Node.js) running in Azure App Service. 為了簡單起見,範例應用程式會使用 MEAN.js web 架構For simplicity, the sample application uses the MEAN.js web framework.

Azure App Service 使用 Linux 作業系統提供可高度擴充、自我修復的 Web 主機服務。Azure App Service provides a highly scalable, self-patching web hosting service using the Linux operating system. 本教學課程說明如何在 Linux 上的 App Service 中建立 Node.js 應用程式,將其連線至本機 MongoDB 資料庫,然後在 Azure Cosmos DB 的 MongoDB 版 API 中將其部署至資料庫。This tutorial shows how to create a Node.js app in App Service on Linux, connect it locally to a MongoDB database, then deploy it to a database in Azure Cosmos DB's API for MongoDB. 完成之後,您的 MEAN 應用程式 (MongoDB、Express、AngularJS 及 Node.js) 將會在 Linux 上的 App Service 中執行。When you're done, you'll have a MEAN application (MongoDB, Express, AngularJS, and Node.js) running in App Service on Linux. 為了簡單起見,範例應用程式會使用 MEAN.js web 架構For simplicity, the sample application uses the MEAN.js web framework.

在 Azure App Service 中執行的 MEAN.js 應用程式

您將學到什麼:What you'll learn:

  • 在 Azure 中建立 MongoDB 資料庫Create a MongoDB database in Azure
  • 將 Node.js 應用程式連線至 MongoDBConnect a Node.js app to MongoDB
  • 將應用程式部署至 AzureDeploy the app to Azure
  • 將資料模型更新並將應用程式重新部署Update the data model and redeploy the app
  • 來自 Azure 的串流診斷記錄Stream diagnostic logs from Azure
  • 在 Azure 入口網站中管理應用程式Manage the app in the Azure portal

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

必要條件Prerequisites

若要完成本教學課程:To complete this tutorial:

測試本機的 MongoDBTest local MongoDB

開啟終端機視窗,然後 cd 至 MongoDB 安裝的 bin 目錄。Open the terminal window and cd to the bin directory of your MongoDB installation. 您可使用這個終端機視窗來執行本教學課程中的所有命令。You can use this terminal window to run all the commands in this tutorial.

在終端機上執行 mongo,以連接到本機的 MongoDB 伺服器。Run mongo in the terminal to connect to your local MongoDB server.

mongo

如果連接成功,則您的 MongoDB 資料庫已在執行中。If your connection is successful, then your MongoDB database is already running. 如果沒有,請確定您的本機 MongoDB 資料庫已遵循安裝 MongoDB Community Edition 中的步驟來啟動。If not, make sure that your local MongoDB database is started by following the steps at Install MongoDB Community Edition. MongoDB 通常已安裝,但您仍需要執行 mongod 才能將它啟動。Often, MongoDB is installed, but you still need to start it by running mongod.

當您完成測試 MongoDB 資料庫時,在終端機上輸入 Ctrl+CWhen you're done testing your MongoDB database, type Ctrl+C in the terminal.

建立本機的 Node.js 應用程式Create local Node.js app

在此步驟中,您要設定本機的 Node.js 專案。In this step, you set up the local Node.js project.

複製範例應用程式Clone the sample application

在終端機視窗中,使用 cd 移至工作目錄。In the terminal window, cd to a working directory.

執行下列命令來複製範例存放庫。Run the following command to clone the sample repository.

git clone https://github.com/Azure-Samples/meanjs.git

此範例存放庫包含 MEAN.js 存放庫的副本。This sample repository contains a copy of the MEAN.js repository. 若要在 App Service 上執行,會將它做修改 (如需詳細資訊,請參閱 MEAN.js 存放庫讀我檔案)。It is modified to run on App Service (for more information, see the MEAN.js repository README file).

執行應用程式Run the application

執行下列命令以安裝必要的套件,然後啟動應用程式。Run the following commands to install the required packages and start the application.

cd meanjs
npm install
npm start

忽略 config.domain 警告。Ignore the config.domain warning. 當應用程式完全載入時,您會看到類似下列的訊息:When the app is fully loaded, you see something similar to the following message:

--
MEAN.JS - 開發環境MEAN.JS - Development Environment

環境:     開發伺服器:        http://0.0.0.0:3000 資料庫:        mongodb://localhost/mean-dev 應用程式版本:   0.5.0 MEAN.JS 版本:0.5.0 --Environment:     development Server:          http://0.0.0.0:3000 Database:        mongodb://localhost/mean-dev App version:     0.5.0 MEAN.JS version: 0.5.0 --

在瀏覽器中,瀏覽至 http://localhost:3000Navigate to http://localhost:3000 in a browser. 按一下上層功能表中的 [註冊],然後建立測試使用者。Click Sign Up in the top menu and create a test user.

MEAN.js 範例應用程式會將使用者資料儲存於資料庫中。The MEAN.js sample application stores user data in the database. 如果您成功建立使用者並且登入,則您的應用程式正在將資料寫入本機 MongoDB 資料庫。If you are successful at creating a user and signing in, then your app is writing data to the local MongoDB database.

MEAN.js 成功連線至 MongoDB

選取 [系統管理員] > [管理文章] 來新增一些文章。Select Admin > Manage Articles to add some articles.

如需隨時停止 Node.js,請在終端機上按下 Ctrl+CTo stop Node.js at any time, press Ctrl+C in the terminal.

建立生產環境 MongoDBCreate production MongoDB

在此步驟中,您要在 Azure 中建立 MongoDB 資料庫。In this step, you create a MongoDB database in Azure. 當您的應用程式部署至 Azure 時,它會使用此雲端資料庫。When your app is deployed to Azure, it uses this cloud database.

針對 MongoDB,本教學課程使用 Azure Cosmos DBFor MongoDB, this tutorial uses Azure Cosmos DB. Cosmos DB 支援 MongoDB 用戶端連線。Cosmos DB supports MongoDB client connections.

建立資源群組Create a resource group

資源群組是一個邏輯容器,可在其中部署與管理 Azure 資源 (例如 Web 應用程式、資料庫和儲存體帳戶)。A resource group is a logical container into which Azure resources, such as web apps, databases, and storage accounts, are deployed and managed. 例如,您可以選擇在稍候透過一個簡單的步驟刪除整個資源群組。For example, you can choose to delete the entire resource group in one simple step later.

在 Cloud Shell 中,使用 az group create 命令來建立資源群組。In the Cloud Shell, create a resource group with the az group create command. 下列範例會在「西歐」位置建立名為 myResourceGroup 的資源群組。The following example creates a resource group named myResourceGroup in the West Europe location. 若要查看 免類 層中 App Service 的所有支援位置,請執行 az appservice list-locations --sku FREE 命令。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 "West Europe"

您通常會在附近的區域中建立資源群組和資源。You generally create your resource group and the resources in a region near you.

當命令完成時,JSON 輸出會顯示資源群組屬性。When the command finishes, a JSON output shows you the resource group properties.

建立 Cosmos DB 帳戶Create a Cosmos DB account

注意

在本教學課程中,當您在自己的 Azure 訂用帳戶中建立 Azure Cosmos DB 資料庫時會產生費用。There is a cost to creating the Azure Cosmos DB databases in this tutorial in your own Azure subscription. 若要使用為期七天的免費 Azure Cosmos DB 帳戶,您可以使用免費試用 Azure Cosmos DB 的體驗。To use a free Azure Cosmos DB account for seven days, you can use the Try Azure Cosmos DB for free experience. 直接按一下 [MongoDB] 圖格中的 [建立] 按鈕,在 Azure 上建立免費的 MongoDB 資料庫。Just click the Create button in the MongoDB tile to create a free MongoDB database on Azure. 資料庫建立好之後,在入口網站中瀏覽至 連接字串,並擷取 Azure Cosmos DB 連線字串以供在本教學課程稍後使用。Once the database is created, navigate to Connection String in the portal and retrieve your Azure Cosmos DB connection string for use later in the tutorial.

在 Cloud Shell 中,使用 az cosmosdb create 命令來建立 Cosmos DB 帳戶。In the Cloud Shell, create a Cosmos DB account with the az cosmosdb create command.

在下列命令中,以唯一的 Cosmos DB 名稱替代 <cosmosdb-name> 預留位置。In the following command, substitute a unique Cosmos DB name for the <cosmosdb-name> placeholder. 這個名稱會用來作為 Cosmos DB 端點 https://<cosmosdb-name>.documents.azure.com/ 的一部分,因此,這個名稱在 Azure 中的所有 Cosmos DB 帳戶上必須是唯一的。This name is used as the part of the Cosmos DB endpoint, https://<cosmosdb-name>.documents.azure.com/, so the name needs to be unique across all Cosmos DB accounts in Azure. 名稱只能包含小寫字母、數字及連字號 (-) 字元,且長度必須為 3 到 50 個字元。The name must contain only lowercase letters, numbers, and the hyphen (-) character, and must be between 3 and 50 characters long.

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

--kind MongoDB 參數會啟用 MongoDB 用戶端連線。The --kind MongoDB parameter enables MongoDB client connections.

建立 Cosmos DB 帳戶之後,Azure CLI 會顯示類似下列範例的資訊:When the Cosmos DB account is created, the Azure CLI shows information similar to the following example:

{
  "consistencyPolicy":
  {
    "defaultConsistencyLevel": "Session",
    "maxIntervalInSeconds": 5,
    "maxStalenessPrefix": 100
  },
  "databaseAccountOfferType": "Standard",
  "documentEndpoint": "https://<cosmosdb-name>.documents.azure.com:443/",
  "failoverPolicies": 
  ...
  < Output truncated for readability >
}

將應用程式連線至生產環境 MongoDBConnect app to production MongoDB

在此步驟中,您要使用 MongoDB 連接字串,將 MEAN.js 範例應用程式連線至您剛才建立的 Cosmos DB 資料庫。In this step, you connect your MEAN.js sample application to the Cosmos DB database you just created, using a MongoDB connection string.

擷取資料庫索引鍵Retrieve the database key

若要連線至 Cosmos DB 資料庫,您需要資料庫金鑰。To connect to the Cosmos DB database, you need the database key. 在 Cloud Shell 中,使用 az cosmosdb list-keys 命令來擷取主要金鑰。In the Cloud Shell, use the az cosmosdb list-keys command to retrieve the primary key.

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

Azure CLI 會顯示類似下列範例的資訊:The Azure CLI shows information similar to the following example:

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

複製 primaryMasterKey 的值。 您需要在下一個步驟中用到此資訊。You need this information in the next step.

在 Node.js 應用程式中設定連接字串Configure the connection string in your Node.js application

在本機 MEAN.js 存放庫的 config/env/ 資料夾中,建立名為 local-production.js 的檔案。In your local MEAN.js repository, in the config/env/ folder, create a file named local-production.js. .gitignore 已設定為在存放庫外保留此檔案。.gitignore is already configured to keep this file out of the repository.

請將下列程式碼複製到其中。Copy the following code into it. 務必以您的 Cosmos DB 資料庫名稱取代這兩個 <cosmosdb-name> 預留位置,並以您在前一個步驟中複製的索引鍵取代 <primary-master-key> 預留位置。Be sure to replace the two <cosmosdb-name> placeholders with your Cosmos DB database name, and replace the <primary-master-key> placeholder with the key you copied in the previous step.

module.exports = {
  db: {
    uri: 'mongodb://<cosmosdb-name>:<primary-master-key>@<cosmosdb-name>.documents.azure.com:10250/mean?ssl=true&sslverifycertificate=false'
  }
};

需要 ssl=true 選項,因為 Cosmos DB 需要 SSLThe ssl=true option is required because Cosmos DB requires SSL.

儲存您的變更。Save your changes.

在生產模式中測試應用程式Test the application in production mode

在本機終端機視窗中,執行下列命令以縮短及組合生產環境的指令碼。In a local terminal window, run the following command to minify and bundle scripts for the production environment. 這個流程會產生生產環境所需的檔案。This process generates the files needed by the production environment.

gulp prod

在本機終端機視窗中,執行下列命令,可使用您在 config/env/local-production.js 中設定的連接字串。In a local terminal window, run the following command to use the connection string you configured in config/env/local-production.js. 忽略憑證錯誤和 config.domain 警告。Ignore the certificate error and the config.domain warning.

# Bash
NODE_ENV=production node server.js

# Windows PowerShell
$env:NODE_ENV = "production" 
node server.js

NODE_ENV=production 會設定環境變數,告知 Node.js 在生產環境中執行。NODE_ENV=production sets the environment variable that tells Node.js to run in the production environment. node server.js 會啟動存放庫根目錄中的 Node.js 伺服器與 server.jsnode server.js starts the Node.js server with server.js in your repository root. 這是在 Azure 中載入 Node.js 應用程式的方式。This is how your Node.js application is loaded in Azure.

載入應用程式之後,請檢查以確定它正在生產環境中執行:When the app is loaded, check to make sure that it's running in the production environment:

--
MEAN.JSMEAN.JS

環境:     實際執行伺服器:        http://0.0.0.0:8443 資料庫:        mongodb://< cosmosdb-name>:< primary-master-key>@< cosmosdb-name>.documents.azure.com:10250/mean?ssl=true&sslverifycertificate=false 應用程式版本:   0.5.0 MEAN.JS 版本:0.5.0Environment:     production Server:          http://0.0.0.0:8443 Database:        mongodb://<cosmosdb-name>:<primary-master-key>@<cosmosdb-name>.documents.azure.com:10250/mean?ssl=true&sslverifycertificate=false App version:     0.5.0 MEAN.JS version: 0.5.0

在瀏覽器中,瀏覽至 http://localhost:8443Navigate to http://localhost:8443 in a browser. 按一下上層功能表中的 [註冊],然後建立測試使用者。Click Sign Up in the top menu and create a test user. 如果您成功建立使用者並且登入,則您的應用程式正在將資料寫入 Azure 中的 Cosmos DB 資料庫。If you are successful creating a user and signing in, then your app is writing data to the Cosmos DB database in Azure.

在終端機中,輸入 Ctrl+C 以停止 Node.js。In the terminal, stop Node.js by typing Ctrl+C.

將應用程式部署到 AzureDeploy app to Azure

在此步驟中,您要將已與 MongoDB 連接的 Node.js 應用程式部署至 Azure App Service。In this step, you deploy your MongoDB-connected Node.js application to Azure App Service.

設定部署使用者Configure a deployment user

FTP 和本機 Git 可以透過使用「部署使用者」 部署到 Azure Web 應用程式。FTP and local Git can deploy to an Azure web app by using a deployment user. 部署使用者只需設定一次,就能供所有 Azure 部署使用。Once you configure your deployment user, you can use it for all your Azure deployments. 使用者名稱和密碼屬於帳戶等級部署,因此與 Azure 訂用帳戶認證不同。Your account-level deployment username and password are different from your Azure subscription credentials.

若要設定部署使用者,請在 Azure Cloud Shell 中執行 az webapp deployment user set 命令。To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. 以部署使用者的使用者名稱和密碼取代 <username> 和 <password>。Replace <username> and <password> with a deployment user username and password.

  • 使用者名稱在 Azure 服務及本機 Git 推送中都必須是唯一的,且不能包含 ‘@’ 符號。The username must be unique within Azure, and for local Git pushes, must not contain the ‘@’ symbol.
  • 密碼長度必須至少為 8 個字元,包含下列三個元素其中兩個:字母、數字及符號。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

JSON 輸出會將密碼顯示為 nullThe JSON output shows the password as null. 如果您收到 'Conflict'. Details: 409 錯誤,請變更使用者名稱。If you get a 'Conflict'. Details: 409 error, change the username. 如果您收到 'Bad Request'. Details: 400 錯誤,請使用更強的密碼。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

將使用者名稱和密碼記錄下來,在部署 Web 應用程式時還會用到。Record your username and password to use to deploy your web apps.

建立應用程式服務方案Create an App Service plan

在 Cloud Shell 中,使用 az appservice plan create 命令來建立 App Service 方案。In the Cloud Shell, create an App Service plan with the az appservice plan create command.

下列範例會在 免費 定價層中建立名為 myAppServicePlan 的 App Service 方案。The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE

建立 App Service 方案後,Azure CLI 會顯示類似下列範例的資訊:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

在 Cloud Shell 中,使用 az appservice plan create 命令在資源群組中建立 App Service 方案。In the Cloud Shell, create an App Service plan in the resource group with the az appservice plan create command.

下列範例會在 免費 定價層 (--sku F1) 和 Linux 容器 (--is-linux) 中,建立名為 myAppServicePlan 的 App Service 方案。The following example creates an App Service plan named myAppServicePlan in the Free pricing tier (--sku F1) and in a Linux container (--is-linux).

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku F1 --is-linux

建立 App Service 方案後,Azure CLI 會顯示類似下列範例的資訊:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "linux",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  <JSON data removed for brevity.>
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

建立 Web 應用程式Create a web app

myAppServicePlan App Service 方案中建立 Web 應用程式Create a web app in the myAppServicePlan App Service plan.

在 Cloud Shell 中,您可以使用 az webapp create 命令。In the Cloud Shell, you can use the az webapp create command. 在下列範,了中,使用全域唯一的應用程式名稱 (有效的字元為 a-z0-9-) 取代 <app-name>In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -). 執行階段設定為 NODE|6.9The runtime is set to NODE|6.9. 若要查看所有支援的執行階段,請執行 az webapp list-runtimesTo see all supported runtimes, run az webapp list-runtimes.

# Bash
az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "NODE|6.9" --deployment-local-git
# PowerShell
az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "NODE|6.9" --deployment-local-git

建立 Web 應用程式後,Azure CLI 會顯示類似下列範例的輸出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.azurewebsites.net",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

您已建立空的 Web 應用程式,其中已啟用 Git 部署。You’ve created an empty web app, with git deployment enabled.

注意

Git 遠端的 URL 會顯示在 deploymentLocalGitUrl 屬性中,其格式為 https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git. 儲存此 URL,稍後您會用到此資訊。Save this URL as you need it later.

myAppServicePlan App Service 方案中建立 Web 應用程式Create a web app in the myAppServicePlan App Service plan.

在 Cloud Shell 中,您可以使用 az webapp create 命令。In the Cloud Shell, you can use the az webapp create command. 在下列範,了中,使用全域唯一的應用程式名稱 (有效的字元為 a-z0-9-) 取代 <app-name>In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -). 執行階段設定為 NODE|6.9The runtime is set to NODE|6.9. 若要查看所有支援的執行階段,請執行 az webapp list-runtimes --linuxTo see all supported runtimes, run az webapp list-runtimes --linux.

# Bash
az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "NODE|6.9" --deployment-local-git
# PowerShell
az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "NODE|6.9" --deployment-local-git

建立 Web 應用程式後,Azure CLI 會顯示類似下列範例的輸出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.azurewebsites.net",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

您已建立空的 Web 應用程式,其中已啟用 Git 部署。You’ve created an empty web app, with git deployment enabled.

注意

Git 遠端的 URL 會顯示在 deploymentLocalGitUrl 屬性中,其格式為 https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git. 儲存此 URL,稍後您會用到此資訊。Save this URL as you need it later.

設定環境變數Configure an environment variable

根據預設,MEAN.js 專案會將 config/env/local-production.js 屏除在 Git 存放庫之外。By default, the MEAN.js project keeps config/env/local-production.js out of the Git repository. 因此會針對您的 Azure 應用程式,使用應用程式設定來定義 MongoDB 連接字串。So for your Azure app, you use app settings to define your MongoDB connection string.

若要設定應用程式的設定,請在 Cloud Shell 中使用 az webapp config appsettings set 命令。To set app settings, use the az webapp config appsettings set command in the Cloud Shell.

下列範例會在 Azure 應用程式中設定 MONGODB_URI 應用程式設定。The following example configures a MONGODB_URI app setting in your Azure app. 取代 <app-name><cosmosdb-name><primary-master-key> 預留位置。Replace the <app-name>, <cosmosdb-name>, and <primary-master-key> placeholders.

az webapp config appsettings set --name <app-name> --resource-group myResourceGroup --settings MONGODB_URI="mongodb://<cosmosdb-name>:<primary-master-key>@<cosmosdb-name>.documents.azure.com:10250/mean?ssl=true"

在 Node.js 程式碼中,您可以利用 process.env.MONGODB_URI存取此應用程式設定,就像存取任何環境變數一樣。In Node.js code, you access this app setting with process.env.MONGODB_URI, just like you would access any environment variable.

在本機 MEAN.js 存放庫中,開啟 config/env/production.js (而不是 config/env/local-production.js),它具有生產環境特定設定。In your local MEAN.js repository, open config/env/production.js (not config/env/local-production.js), which has production-environment specific configuration. 預設的 MEAN.js 應用程式已經設定為使用您建立的 MONGODB_URI 環境變數。The default MEAN.js app is already configured to use the MONGODB_URI environment variable that you created.

db: {
  uri: ... || process.env.MONGODB_URI || ...,
  ...
},

從 Git 推送至 AzurePush to Azure from Git

回到本機終端視窗,將 Azure 遠端新增至本機 Git 存放庫。Back in the local terminal window, add an Azure remote to your local Git repository. 以您從 建立 Web 應用程式儲存的 Git 遠端 URL 取代 <deploymentLocalGitUrl-from-create-step>Replace <deploymentLocalGitUrl-from-create-step> with the URL of the Git remote that you saved from Create a web app.

git remote add azure <deploymentLocalGitUrl-from-create-step>

推送到 Azure 遠端,使用下列命令來部署您的應用程式。Push to the Azure remote to deploy your app with the following command. 當 Git 認證管理員提示輸入認證時,請務必輸入您在 設定部署使用者 中建立的認證,而不是您用來登入 Azure 入口網站的認證。When Git Credential Manager prompts you for credentials, make sure you enter the credentials you created in Configure a deployment user, not the credentials you use to sign in to the Azure portal.

git push azure master

此命令可能會花數分鐘執行。This command may take a few minutes to run. 執行上述命令時,會顯示類似下列範例的資訊:While running, it displays information similar to the following example:

Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 489 bytes | 0 bytes/s, done.
Total 5 (delta 3), reused 0 (delta 0)
remote: Updating branch 'master'.
remote: Updating submodules.
remote: Preparing deployment for commit id '6c7c716eee'.
remote: Running custom deployment command...
remote: Running deployment command...
remote: Handling node.js deployment.
.
.
.
remote: Deployment successful.
To https://<app-name>.scm.azurewebsites.net/<app-name>.git
 * [new branch]      master -> master

您可能會注意到,部署程序會在 npm install 之後執行 GulpYou may notice that the deployment process runs Gulp after npm install. App Service 不會在部署期間執行 Gulp 或 Grunt 工作,因此,這個範例存放庫在其根目錄中有兩個其他檔案可啟用它:App Service does not run Gulp or Grunt tasks during deployment, so this sample repository has two additional files in its root directory to enable it:

  • .deployment - 此檔案會告訴 App Service,執行 bash deploy.sh 以作為自訂部署指令碼。.deployment - This file tells App Service to run bash deploy.sh as the custom deployment script.
  • deploy.sh - 自訂部署指令碼。deploy.sh - The custom deployment script. 如果您檢閱檔案,您將看到它會在 npm installbower install 之後執行 gulp prodIf you review the file, you will see that it runs gulp prod after npm install and bower install.

您可以使用這種方法,將任何步驟新增至您的 Git 部署。You can use this approach to add any step to your Git-based deployment. 如果您在任一時間點重新啟動 Azure 應用程式,App Service 並不會重新執行這些自動化工作。If you restart your Azure app at any point, App Service doesn't rerun these automation tasks. 如需詳細資訊,請參閱執行 Grunt/Bower/GulpFor more information, see Run Grunt/Bower/Gulp.

瀏覽至 Azure 應用程式Browse to the Azure app

使用網頁瀏覽器,瀏覽至已部署的應用程式。Browse to the deployed app using your web browser.

http://<app-name>.azurewebsites.net 

按一下上層功能表中的 [註冊],然後建立一位虛擬使用者。Click Sign Up in the top menu and create a dummy user.

如果成功且應用程式會自動登入已建立的使用者,則您在 Azure 中的 MEAN.js 應用程式就已連線到 MongoDB (Cosmos DB) 資料庫。If you are successful and the app automatically signs in to the created user, then your MEAN.js app in Azure has connectivity to the MongoDB (Cosmos DB) database.

在 Azure App Service 中執行的 MEAN.js 應用程式

選取 [系統管理員] > [管理文章] 來新增一些文章。Select Admin > Manage Articles to add some articles.

恭喜!Congratulations! 您正在 Azure App Service 中執行資料驅動的 Node.js 應用程式。You're running a data-driven Node.js app in Azure App Service.

更新資料模型並重新部署Update data model and redeploy

在此步驟中,您會變更 article 資料模型,並將變更發佈至 Azure。In this step, you change the article data model and publish your change to Azure.

更新資料模型Update the data model

在本機 MEAN.js 存放庫中,開啟 modules/articles/server/models/article.server.model.jsIn your local MEAN.js repository, open modules/articles/server/models/article.server.model.js.

ArticleSchema 中,新增名為 commentString 類型。In ArticleSchema, add a String type called comment. 完成時,您的結構描述程式碼應該如下所示:When you're done, your schema code should look like this:

const ArticleSchema = new Schema({
  ...,
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  comment: {
    type: String,
    default: '',
    trim: true
  }
});

更新 articles 程式碼Update the articles code

更新 articles 程式碼的其餘部分以使用 commentUpdate the rest of your articles code to use comment.

有五個需要修改的檔案:伺服器控制器和四個用戶端檢視。There are five files you need to modify: the server controller and the four client views.

開啟 modules/articles/server/controllers/articles.server.controller.jsOpen modules/articles/server/controllers/articles.server.controller.js.

update 函式中,新增 article.comment 的指派。In the update function, add an assignment for article.comment. 下列程式碼會顯示已完成的 update 函式:The following code shows the completed update function:

exports.update = function (req, res) {
  let article = req.article;

  article.title = req.body.title;
  article.content = req.body.content;
  article.comment = req.body.comment;

  ...
};

開啟 modules/articles/client/views/view-article.client.view.htmlOpen modules/articles/client/views/view-article.client.view.html.

就在結尾 </section> 標記的正上方,新增下列程式碼行來顯示 comment 以及剩餘的文章資料:Just above the closing </section> tag, add the following line to display comment along with the rest of the article data:

<p class="lead" ng-bind="vm.article.comment"></p>

開啟 modules/articles/client/views/list-articles.client.view.htmlOpen modules/articles/client/views/list-articles.client.view.html.

就在結尾 </a> 標記的正上方,新增下列程式碼行來顯示 comment 以及剩餘的文章資料:Just above the closing </a> tag, add the following line to display comment along with the rest of the article data:

<p class="list-group-item-text" ng-bind="article.comment"></p>

開啟 modules/articles/client/views/admin/list-articles.client.view.htmlOpen modules/articles/client/views/admin/list-articles.client.view.html.

<div class="list-group"> 元素內部且就在結尾 comment 標記的正上方,新增下列程式碼行來顯示 </a> 以及剩餘的文章資料:Inside the <div class="list-group"> element and just above the closing </a> tag, add the following line to display comment along with the rest of the article data:

<p class="list-group-item-text" data-ng-bind="article.comment"></p>

開啟 modules/articles/client/views/admin/form-article.client.view.htmlOpen modules/articles/client/views/admin/form-article.client.view.html.

找到包含提交按鈕的 <div class="form-group"> 元素,如下所示:Find the <div class="form-group"> element that contains the submit button, which looks like this:

<div class="form-group">
  <button type="submit" class="btn btn-default">{{vm.article._id ? 'Update' : 'Create'}}</button>
</div>

就在此標記的正上方,新增另一個 <div class="form-group"> 元素,讓使用者能夠編輯 comment 欄位。Just above this tag, add another <div class="form-group"> element that lets people edit the comment field. 新的元素應該如下所示:Your new element should look like this:

<div class="form-group">
  <label class="control-label" for="comment">Comment</label>
  <textarea name="comment" data-ng-model="vm.article.comment" id="comment" class="form-control" cols="30" rows="10" placeholder="Comment"></textarea>
</div>

本機測試您的變更Test your changes locally

儲存您的所有變更。Save all your changes.

在本機終端機視窗中,再次於生產模式中測試變更。In the local terminal window, test your changes in production mode again.

# Bash
gulp prod
NODE_ENV=production node server.js

# Windows PowerShell
gulp prod
$env:NODE_ENV = "production" 
node server.js

在瀏覽器中,瀏覽至 http://localhost:8443,並確定您已登入。Navigate to http://localhost:8443 in a browser and make sure that you're signed in.

選取 [系統管理員] > [管理文章],然後選取 [+] 按鈕來新增文章。Select Admin > Manage Articles, then add an article by selecting the + button.

您現在會看到新的 Comment 文字方塊。You see the new Comment textbox now.

已將註解欄位新增到文章中

在終端機中,輸入 Ctrl+C 以停止 Node.js。In the terminal, stop Node.js by typing Ctrl+C.

將變更發佈至 AzurePublish changes to Azure

在本機終端機視窗中,在 Git 中認可您的變更,然後將程式碼變更推送至 Azure。In the local terminal window, commit your changes in Git, then push the code changes to Azure.

git commit -am "added article comment"
git push azure master

完成 git push 之後,巡覽至 Azure 應用程式,然後嘗試執行新功能。Once the git push is complete, navigate to your Azure app and try out the new functionality.

發佈至 Azure 的模型和資料庫變更

如果您先前已新增任何文章,您仍然可以看到它們。If you added any articles earlier, you still can see them. Cosmos DB 中的現有資料不會遺失。Existing data in your Cosmos DB is not lost. 此外,您的變更會更新至資料結構描述,並讓現有資料保留不變。Also, your updates to the data schema and leaves your existing data intact.

資料流診斷記錄Stream diagnostic logs

當 Node.js 應用程式在 Azure App Service 中執行時,您可以使用管線將主控台記錄傳送至終端機。While your Node.js application runs in Azure App Service, you can get the console logs piped to your terminal. 這樣一來,您就能取得相同的診斷訊息,以協助您偵錯應用程式錯誤。That way, you can get the same diagnostic messages to help you debug application errors.

若要開始記錄資料流,請在 Cloud Shell 中使用 az webapp log tail 命令。To start log streaming, use the az webapp log tail command in the Cloud Shell.

az webapp log tail --name <app-name> --resource-group myResourceGroup

開始記錄串流之後,在瀏覽器中重新整理 Azure 應用程式以取得部分 Web 流量。Once log streaming has started, refresh your Azure app in the browser to get some web traffic. 您現在會看到使用管線傳送到終端機的主控台記錄。You now see console logs piped to your terminal.

您隨時可以輸入 Ctrl+C 以停止記錄資料流。Stop log streaming at any time by typing Ctrl+C.

若要存取 App Service 中應用程式程式碼內部產生的主控台記錄,請在 Cloud Shell 中執行下列命令,以開啟診斷記錄功能:To access the console logs generated from inside your application code in App Service, turn on diagnostics logging by running the following command in the Cloud Shell:

az webapp log config --resource-group <resource-group-name> --name <app-name> --application-logging true --level Verbose

--level 的可能值為:ErrorWarningInfoVerbosePossible values for --level are: Error, Warning, Info, and Verbose. 後續的每個層級都包含上一個層級。Each subsequent level includes the previous level. 例如:Error 只包含錯誤訊息,而 Verbose 包含所有訊息。For example: Error includes only error messages, and Verbose includes all messages.

開啟診斷記錄後,請執行下列命令來查看記錄資料流:Once diagnostic logging is turned on, run the following command to see the log stream:

az webapp log tail --resource-group <resource-group-name> --name <app-name>

如果您沒有立即看到主控台記錄,請在 30 秒後再查看。If you don't see console logs immediately, check again in 30 seconds.

注意

您也可以在瀏覽器中的 https://<app-name>.scm.azurewebsites.net/api/logs/docker 檢查記錄檔。You can also inspect the log files from the browser at https://<app-name>.scm.azurewebsites.net/api/logs/docker.

若要隨時停止記錄資料流,請輸入 Ctrl+CTo stop log streaming at any time, type Ctrl+C.

管理您的 Azure 應用程式Manage your Azure app

移至 Azure 入口網站,以查看您所建立的應用程式。Go to the Azure portal to see the app you created.

按一下左側功能表中的 [應用程式服務],然後按一下 Azure 應用程式的名稱。From the left menu, click App Services, then click the name of your Azure app.

入口網站瀏覽至 Azure 應用程式

根據預設,入口網站會顯示應用程式的 [概觀] 頁面。By default, the portal shows your app's Overview page. 此頁面可讓您檢視應用程式的執行方式。This page gives you a view of how your app is doing. 您也可以在這裡執行基本管理工作,像是瀏覽、停止、啟動、重新啟動及刪除。Here, you can also perform basic management tasks like browse, stop, start, restart, and delete. 分頁左側的索引標籤會顯示您可開啟的各種設定分頁。The tabs on the left side of the page show the different configuration pages you can open.

Azure 入口網站中的 App Service 頁面

清除資源Clean up resources

在前述步驟中,您在資源群組中建立了 Azure 資源。In the preceding steps, you created Azure resources in a resource group. 如果您在未來不需要這些資源,請在 Cloud Shell 中執行下列命令,刪除資源群組:If you don't expect to need these resources in the future, delete the resource group by running the following command in the Cloud Shell:

az group delete --name myResourceGroup

此命令可能會花一分鐘執行。This command may take a minute to run.

後續步驟Next steps

您已了解如何︰What you learned:

  • 在 Azure 中建立 MongoDB 資料庫Create a MongoDB database in Azure
  • 將 Node.js 應用程式連線至 MongoDBConnect a Node.js app to MongoDB
  • 將應用程式部署至 AzureDeploy the app to Azure
  • 將資料模型更新並將應用程式重新部署Update the data model and redeploy the app
  • 將記錄從 Azure 串流到終端機Stream logs from Azure to your terminal
  • 在 Azure 入口網站中管理應用程式Manage the app in the Azure portal

前往下一個教學課程,了解如何將自訂的 DNS 名稱對應至該應用程式。Advance to the next tutorial to learn how to map a custom DNS name to the app.

或者,查看其他資源:Or, check out other resources: