教程:在 Azure 中生成 Node.js 和 MongoDB 应用Tutorial: Build a Node.js and MongoDB app in Azure

Azure 应用服务提供高度可缩放、自修复的 Web 托管服务。Azure App Service provides a highly scalable, self-patching web hosting service. 本教程演示如何在 Windows 上的应用服务中创建 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. 完成操作后,将拥有一个在 Azure 应用服务上运行的 MEAN 应用程序(MongoDB、Express、AngularJS 和 Node.js)。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 应用服务使用 Linux 操作系统,提供高度可缩放的自修补 Web 托管服务。Azure App Service provides a highly scalable, self-patching web hosting service using the Linux operating system. 本教程演示如何在 Linux 上的应用服务中创建 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. 完成操作后,将拥有一个在 Linux 应用服务中运行的 MEAN 应用程序(MongoDB、Express、AngularJS 和 Node.js)。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 应用服务中运行的 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 trial account before you begin.

先决条件Prerequisites

完成本教程:To complete this tutorial:

  1. 安装 GitInstall Git
  2. 安装 Node.js 和 NPMInstall Node.js and NPM
  3. 安装 BowerMEAN.js 必需的)Install Bower (required by MEAN.js)
  4. 安装 Gulp.jsMEAN.js 必需的)Install Gulp.js (required by MEAN.js)
  5. 安装并运行 MongoDB 社区版Install and run MongoDB Community Edition

测试本地 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 数据库。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. 对它进行了修改,以便在应用服务上运行(有关详细信息,请参阅 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.

在终端按 Ctrl+C,随时停止 Node.js。To 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 like 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.

在 Azure CLI 中,使用 az group create 命令创建资源组。In the Azure CLI, create a resource group with the az group create command. 以下示例在“中国北部”位置创建名为“myResourceGroup”的资源组。The following example creates a resource group named myResourceGroup in the China North location. 要查看“免费”层中应用服务支持的所有位置,请运行 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 "China North"

通常在附近的区域中创建资源组和资源。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 连接字符串,以便在本教程的后面使用。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.

在 Azure CLI 中,使用 az cosmosdb create 命令创建 Cosmos DB 帐户。In Azure CLI, 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.cn/ 的一部分,因此需要在 Azure 中的所有 Cosmos DB 帐户中具有唯一性。This name is used as the part of the Cosmos DB endpoint, https://<cosmosdb_name>.documents.azure.cn/, 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.cn: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. 在 Azure CLI 中,使用 az cosmosdb list-keys 命令检索主键。In Azure CLI, 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. 请确保将两个 <cosmosdb-name> 占位符替换为 Cosmos DB 数据库名称,将 <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.cn: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 使用存储库根路径中的 server.js 启动 Node.js 服务器。node server.js starts the Node.js server with server.js in your repository root. 这就是 Node.js 应用程序在 Azure 中加载的方式。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.cn: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.cn: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 应用服务。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

使用 az appservice plan create 命令创建应用服务计划。Create an App Service plan with the az appservice plan create command.

以下示例在免费定价层中创建名为 myAppServicePlan 的应用服务计划: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

创建应用服务计划后,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": "China North",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "app",
  "location": "China North",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

在 Azure CLI 中,使用 az appservice plan create 命令在资源组中创建应用服务计划。In the Azure CLI, create an App Service plan in the resource group with the az appservice plan create command.

应用服务计划指定托管应用的 Web 服务器场的位置、大小和功能。An App Service plan specifies the location, size, and features of the web server farm that hosts your app. 可以在托管多个应用时节省资金,方法是将多个 Web 应用配置为共用单个应用服务计划。You can save money when hosting multiple apps by configuring the web apps to share a single App Service plan.

应用服务计划定义:App Service plans define:

  • 区域(例如:中国东部、中国东部 2、中国北部、中国北部 2)Region (for example: China East, China East 2, China North, China North 2)
  • 实例大小(小、中、大)Instance size (small, medium, or large)
  • 规模计数(1 到 10 个实例)Scale count (1 to 10 instances)
  • SKU(基本、标准)SKU (Basic, Standard)

以下示例在免费定价层 (--sku F1) 和 Linux 容器 (--is-linux) 中创建名为 myAppServicePlan 的应用服务计划。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

创建应用服务计划后,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": "China East 2",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "linux",
  "location": "China East 2",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

创建 Web 应用Create a web app

myAppServicePlan 应用服务计划中创建一个 Web 应用Create a web app in the myAppServicePlan App Service plan.

在 Azure CLI 中,可以使用 az webapp create 命令。在以下示例中,将 <app-name> 替换为全局唯一的应用名称(有效字符是 a-z0-9-)。In the Azure CLI, you can use the az webapp create command.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.chinacloudsites.cn/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.chinacloudsites.cn",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.chinacloudsites.cn/<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.chinacloudsites.cn/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git. 保存此 URL,后续将会用到。Save this URL as you need it later.

myAppServicePlan 应用服务计划中创建一个 Web 应用Create a web app in the myAppServicePlan App Service plan.

在 Azure CLI 中,可以使用 az webapp create 命令。In the Azure CLI, you can use the az webapp create command. 在以下示例中,将 <app-name> 替换为全局唯一的应用名称(有效字符是 a-z0-9-)。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.chinacloudsites.cn/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.chinacloudsites.cn",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.chinacloudsites.cn/<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.chinacloudsites.cn/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.chinacloudsites.cn/<app-name>.git. 保存此 URL,后续将会用到。Save this URL as you need it later.

配置环境变量Configure an environment variable

默认情况下,MEAN.js 项目会在 Git 存储库外部保留 config/env/local-production.jsBy 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.

若要设置应用设置,请在 Azure CLI 中使用 az webapp config appsettings set 命令。To set app settings, use the az webapp config appsettings set command in Azure CLI.

以下示例在 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.cn: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. 将 <deploymentLocalGitUrl-from-create-step> 替换为在创建 Web 应用中保存的 Git 远程 URL。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.chinacloudsites.cn/<app-name>.git
 * [new branch]      master -> master

你可能会注意到,部署进程将在运行 npm install 之后运行 GulpYou may notice that the deployment process runs Gulp after npm install. 应用服务在部署期间不会运行 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 - 此文件告知应用服务将 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 应用(无论何时),应用服务都不会重新运行这些自动化任务。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

使用 Web 浏览器转到已部署的应用。Browse to the deployed app using your web browser.

http://<app-name>.chinacloudsites.cn 

单击菜单顶部的“注册”,创建虚拟用户。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 应用服务中运行的 MEAN.js 应用

选择“管理员”>“管理文章”,添加一些文章。Select Admin > Manage Articles to add some articles.

祝贺你!Congratulations! 正在 Azure 应用服务中运行数据驱动的 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
  }
});

更新文章代码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.js。Open 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.html。Open 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.html。Open 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.html。Open modules/articles/client/views/admin/list-articles.client.view.html.

<div class="list-group"> 元素内,以及 </a> 结尾标记正上方,添加下列行以显示 comment 和其余文章数据: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.html。Open 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.

发布对 Azure 所做的更改Publish 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 应用服务中运行时,可以将控制台日志通过管道传输到终端。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.

若要启动日志流式处理,请使用 az webapp log tail 命令。To start log streaming, use the az webapp log tail command.

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.

若要访问应用服务中的应用程序代码内生成的控制台日志,请在 Azure CLI 中运行以下命令以打开诊断日志记录: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 Azure CLI:

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.chinacloudsites.cn/api/logs/docker 中检查日志文件。You can also inspect the log files from the browser at https://<app-name>.scm.chinacloudsites.cn/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 门户中的“应用服务”页

清理资源Clean up resources

若要清理资源,请运行以下命令:To clean up your resources, run the following command:

az group delete --name myResourceGroup

后续步骤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: