教程:开发适用于 Linux 设备的 IoT Edge 模块Tutorial: Develop IoT Edge modules for Linux devices

使用 Visual Studio Code 开发代码并将其部署到运行 IoT Edge 的 Linux 设备。Use Visual Studio Code to develop and deploy code to Linux devices running IoT Edge.

在快速入门中,你已使用 Linux 虚拟机创建了 IoT Edge 设备,并部署了来自 Azure 市场的模块。In the quickstart, you created an IoT Edge device using a Linux virtual machine and deployed a module from the Azure Marketplace. 本教程逐步介绍如何开发自己的代码并将其部署到 IoT Edge 设备。This tutorial walks through developing and deploying your own code to an IoT Edge device. 本文是学习其他教程的有用先决条件,其他教程将更详细地介绍特定编程语言或 Azure 服务。This article is a useful prerequisite for the other tutorials, which go into more detail about specific programming languages or Azure services.

本教程使用 将 C# 模块部署到 Linux 设备 的示例。This tutorial uses the example of deploying a C# module to a Linux device. 之所以选择此示例,是因为它是 IoT Edge 解决方案中最常见的开发人员方案。This example was chosen because it's the most common developer scenario for IoT Edge solutions. 即使你计划使用其他语言或部署 Azure 服务,本教程仍然有助于了解开发工具和概念。Even if you plan on using a different language or deploying an Azure service, this tutorial is still useful to learn about the development tools and concepts. 阅读开发过程的介绍,然后选择偏好的语言或 Azure 服务来深入了解细节。Complete this introduction to the development process, then choose your preferred language or Azure service to dive into the details.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 设置开发计算机。Set up your development machine.
  • 使用适用于 Visual Studio Code 的 IoT Edge Tools 创建新项目。Use the IoT Edge tools for Visual Studio Code to create a new project.
  • 将项目作为容器生成并将其存储在 Azure 容器注册表中。Build your project as a container and store it in an Azure container registry.
  • 将代码部署到 IoT Edge 设备。Deploy your code to an IoT Edge device.


开发计算机:A development machine:

  • 可以使用自己的计算机或虚拟机,具体取决于开发首选项。You can use your own computer or a virtual machine, depending on your development preferences.
    • 请确保开发计算机支持嵌套虚拟化。Make sure that your development machine supports nested virtualization. 此功能对于运行容器引擎是必需的,你将在下一部分中安装。This capability is necessary for running a container engine, which you install in the next section.
  • 大多数可以运行容器引擎的操作系统都可用于为 Linux 设备开发 IoT Edge 模块。Most operating systems that can run a container engine can be used to develop IoT Edge modules for Linux devices. 本教程使用 Windows 计算机,但指出 macOS 或 Linux 上的已知差异。This tutorial uses a Windows computer, but points out known differences on macOS or Linux.
  • 安装 Git,以便在本教程稍后部分拉取模块模板包。Install Git, to pull module template packages later in this tutorial.
  • 适用于 Visual Studio Code 的 C# 扩展(由 OmniSharp 提供支持)C# for Visual Studio Code (powered by OmniSharp) extension.
  • .NET Core 2.1 SDK.NET Core 2.1 SDK.

Linux 上的 Azure IoT Edge 设备:An Azure IoT Edge device on Linux:

  • 我们建议不要在开发计算机上运行 IoT Edge,而应使用单独的设备。We recommend that you don't run IoT Edge on your development machine, but instead use a separate device. 开发计算机和 IoT Edge 设备之间的这一区分可更准确地反映真实部署方案,并有助于区分不同的概念。This distinction between development machine and IoT Edge device more accurately mirrors a true deployment scenario, and helps to keep the different concepts straight.
  • 如果没有第二台可用的设备,请按照快速入门文章的说明在 Azure 中使用 Linux 虚拟机创建 IoT Edge 设备。If you don't have a second device available, use the quickstart article to create an IoT Edge device in Azure with a Linux virtual machine.

云资源:Cloud resources:

  • Azure 中的免费或标准层 IoT 中心A free or standard-tier IoT hub in Azure.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

关键概念Key concepts

本教程详细介绍如何开发 IoT Edge 模块。This tutorial walks through the development of an IoT Edge module. IoT Edge 模块有时简称模块,它是一个包含可执行代码的容器 。An IoT Edge module, or sometimes just module for short, is a container with executable code. 可以将一个或多个模块部署到 IoT Edge 设备。You can deploy one or more modules to an IoT Edge device. 模块执行特定的任务,例如,从传感器引入数据、清理和分析数据,或者将消息发送到 IoT 中心。Modules perform specific tasks like ingesting data from sensors, cleaning and analyzing data, or sending messages to an IoT hub. 有关详细信息,请参阅了解 Azure IoT Edge 模块For more information, see Understand Azure IoT Edge modules.

开发 IoT Edge 模块时,了解开发计算机和最终将部署模块的目标 IoT Edge 设备之间的差异非常重要。When developing IoT Edge modules, it's important to understand the difference between the development machine and the target IoT Edge device where the module will eventually be deployed. 为保存模块代码而生成的容器必须与 目标设备 的操作系统 (OS) 匹配。The container that you build to hold your module code must match the operating system (OS) of the target device. 例如,最常见的方案是在 Windows 计算机上开发面向运行 IoT Edge 的 Linux 设备的模块。For example, the most common scenario is someone developing a module on a Windows computer intending to target a Linux device running IoT Edge. 在这种情况下,容器操作系统将为 Linux。In that case, the container operating system would be Linux. 在学习本教程的过程中,请记住 开发计算机 OS容器 OS 之间的差异。As you go through this tutorial, keep in mind the difference between the development machine OS and the container OS.

本教程针对运行 IoT Edge 的 Linux 设备。This tutorial targets Linux devices running IoT Edge. 只要开发计算机可以运行 Linux 容器,就可以使用首选操作系统。You can use your preferred operating system as long as your development machine runs Linux containers. 我们建议使用 Visual Studio Code 进行 Linux 设备开发,这也是本教程将使用的工具。We recommend using Visual Studio Code to develop for Linux devices, so that's what this tutorial will use. 还可以使用 Visual Studio,但这两个工具提供的支持存在差异。You can use Visual Studio as well, although there are differences in support between the two tools.

下表列出了 Visual Studio Code 和 Visual Studio 支持的 Linux 容器 开发方案。The following table lists the supported development scenarios for Linux containers in Visual Studio Code and Visual Studio.

Visual Studio CodeVisual Studio Code Visual Studio 2017/2019Visual Studio 2017/2019
Linux 设备体系结构Linux device architecture Linux AMD64Linux AMD64
Linux ARM32Linux ARM32
Linux AMD64Linux AMD64
Linux ARM32Linux ARM32
Azure 服务Azure services Azure FunctionsAzure Functions
Azure 流分析Azure Stream Analytics
Azure 机器学习Azure Machine Learning
语言Languages CC
详细信息More information 适用于 Visual Studio Code 的 Azure IoT EdgeAzure IoT Edge for Visual Studio Code 适用于 Visual Studio 2017 的 Azure IoT Edge ToolsAzure IoT Edge Tools for Visual Studio 2017
适用于 Visual Studio 2019 的 Azure IoT Edge 工具Azure IoT Edge Tools for Visual Studio 2019


公共预览版中提供对 Linux ARM64 设备的支持。Support for Linux ARM64 devices is available in public preview. 有关详细信息,请参阅在 Visual Studio Code(预览版)中开发和调试 ARM64 IoT Edge 模块For more information, see Develop and debug ARM64 IoT Edge modules in Visual Studio Code (preview).

本教程讲解适用于 Visual Studio Code 的开发步骤。This tutorial teaches the development steps for Visual Studio Code. 如果想要使用 Visual Studio,请参阅使用 Visual Studio 2019 为 Azure IoT Edge 开发和调试模块中的说明。If you would rather use Visual Studio, refer to the instructions in Use Visual Studio 2019 to develop and debug modules for Azure IoT Edge.

安装容器引擎Install container engine

IoT Edge 模块被打包为容器,因此,需要在开发计算机上安装容器引擎来生成和管理容器。IoT Edge modules are packaged as containers, so you need a container engine on your development machine to build and manage them. Docker Desktop 提供广泛的功能支持且非常流行,因此我们建议使用它进行开发。We recommend Docker Desktop for development because of its feature support and popularity. 使用 Windows 上的 Docker Desktop 可在 Linux 容器和 Windows 容器之间切换,以便轻松地为不同类型的 IoT Edge 设备开发模块。Docker Desktop on Windows lets you switch between Linux containers and Windows containers so that you can easily develop modules for different types of IoT Edge devices.

按照 Docker 文档的说明在开发计算机上安装:Use the Docker documentation to install on your development machine:

设置 VS Code 和工具Set up VS Code and tools

使用适用于 Visual Studio Code 的 IoT 扩展开发 IoT Edge 模块。Use the IoT extensions for Visual Studio Code to develop IoT Edge modules. 这些扩展提供项目模板、自动化部署清单的创建,并允许监视和管理 IoT Edge 设备。These extensions provide project templates, automate the creation of the deployment manifest, and allow you to monitor and manage IoT Edge devices. 本部分将安装 Visual Studio Code 和 IoT 扩展,然后设置 Azure 帐户用于在 Visual Studio Code 中管理 IoT 中心资源。In this section, you install Visual Studio Code and the IoT extension, then set up your Azure account to manage IoT Hub resources from within Visual Studio Code.

  1. 在开发计算机上安装 Visual Studio CodeInstall Visual Studio Code on your development machine.

  2. 安装完成后,选择“查看” > “扩展” 。Once the installation is finished, select View > Extensions.

  3. 搜索 Azure IoT Tools,它实际上是一个扩展集合,可帮助与 IoT 中心和 IoT 设备进行交互,以及开发 IoT Edge 模块。Search for Azure IoT Tools, which is actually a collection of extensions that help you interact with IoT Hub and IoT devices, as well as developing IoT Edge modules.

  4. 选择“安装” 。Select Install. 每个随附的扩展均单独安装。Each included extension installs individually.

  5. 完成扩展安装后,通过选择“查看” > “命令面板”来打开命令面板 。When the extensions are done installing, open the command palette by selecting View > Command Palette.

  6. 在命令面板中,搜索并选择 Azure:Sign in 命令。In the command palette, search for and select Azure: Sign in. 根据提示登录到 Azure 帐户。Follow the prompts to sign in to your Azure account.

  7. 再次在命令面板中搜索并选择 Azure IoT Hub:Select IoT Hub 命令。In the command palette again, search for and select Azure IoT Hub: Select IoT Hub. 按照提示选择 Azure 订阅和 IoT 中心。Follow the prompts to select your Azure subscription and IoT hub.

  8. 通过选择左侧活动栏中的图标,或选择“查看” > “资源管理器”,打开 Visual Studio Code 的“资源管理器”部分 。Open the explorer section of Visual Studio Code by either selecting the icon in the activity bar on the left, or by selecting View > Explorer.

  9. 在“资源管理器”部分的底部,展开折叠的“Azure IoT 中心/设备”菜单。At the bottom of the explorer section, expand the collapsed Azure IoT Hub / Devices menu. 应该看到与通过命令面板选择的 IoT 中心关联的设备和 IoT Edge 设备。You should see the devices and IoT Edge devices associated with the IoT hub that you selected through the command palette.

    查看 IoT 中心中的设备

创建容器注册表Create a container registry

本教程将使用 Azure IoT Tools 扩展来生成模块并从文件创建 容器映像In this tutorial, you use the Azure IoT Tools extension to build a module and create a container image from the files. 然后将该映像推送到用于存储和管理映像的 注册表Then you push this image to a registry that stores and manages your images. 最后,从注册表部署在 IoT Edge 设备上运行的映像。Finally, you deploy your image from your registry to run on your IoT Edge device.

可以使用任意兼容 Docker 的注册表来保存容器映像。You can use any Docker-compatible registry to hold your container images. 两个常见 Docker 注册表服务分别是 Azure 容器注册表Docker 中心Two popular Docker registry services are Azure Container Registry and Docker Hub. 本教程使用 Azure 容器注册表。This tutorial uses Azure Container Registry.

如果还没有容器注册表,请执行以下步骤,以便在 Azure 中创建一个新的:If you don't already have a container registry, follow these steps to create a new one in Azure:

  1. Azure 门户中,选择“创建资源” > “容器” > “容器注册表”。In the Azure portal, select Create a resource > Containers > Container Registry.

  2. 提供以下值,以便创建容器注册表:Provide the following values to create your container registry:

    字段Field Value
    订阅Subscription 从下拉列表中选择“订阅”。Select a subscription from the drop-down list.
    资源组Resource group 建议对在 IoT Edge 快速入门和教程中创建的所有测试资源使用同一资源组。We recommend that you use the same resource group for all of the test resources that you create during the IoT Edge quickstarts and tutorials. 例如,IoTEdgeResourcesFor example, IoTEdgeResources.
    注册表名称Registry name 提供唯一名称。Provide a unique name.
    位置Location 选择靠近你的位置。Choose a location close to you.
    SKUSKU 选择“基本”。Select Basic.
  3. 选择“创建”。Select Create.

  4. 创建容器注册表后,浏览到它,然后从左窗格中,选择“设置”下菜单中的“访问密钥” 。After your container registry is created, browse to it, and from the left pane select Access keys from the menu located under Settings.

  5. 单击以允许管理员用户查看容器注册表的“用户名”和“密码”。Click to Enable Admin user to view the Username and Password for your container registry.

  6. 复制“登录服务器”、“用户名”和“密码”的值,并将其保存在方便的位置 。Copy the values for Login server, Username, and Password and save them somewhere convenient. 本教程将使用这些值来访问容器注册表。You use these values throughout this tutorial to provide access to the container registry.


创建新的模块项目Create a new module project

Azure IoT Edge Tools 扩展为 Visual Studio Code 中支持的所有 IoT Edge 模块语言提供项目模板。The Azure IoT Tools extension provides project templates for all supported IoT Edge module languages in Visual Studio Code. 这些模板包含将工作模块部署到测试 IoT Edge 所需的所有文件和代码,或为你提供使用自己的业务逻辑自定义模板的起点。These templates have all the files and code that you need to deploy a working module to test IoT Edge, or give you a starting point to customize the template with your own business logic.

本教程使用 C# 模块模板,因为它是最常用的模板。For this tutorial, we use the C# module template because it is the most commonly used template.

创建项目模板Create a project template

在 Visual Studio Code 命令面板中,搜索并选择 Azure IoT Edge: New IoT Edge Solution 命令。In the Visual Studio Code command palette, search for and select Azure IoT Edge: New IoT Edge Solution. 按照提示操作并使用以下值创建解决方案:Follow the prompts and use the following values to create your solution:

字段Field Value
选择文件夹Select folder 在适用于 VS Code 的开发计算机上选择用于创建解决方案文件的位置。Choose the location on your development machine for VS Code to create the solution files.
提供解决方案名称Provide a solution name 输入解决方案的描述性名称,或者接受默认的 EdgeSolutionEnter a descriptive name for your solution or accept the default EdgeSolution.
选择模块模板Select module template 选择“C# 模块”。Choose C# Module.
提供模块名称Provide a module name 接受默认的 SampleModuleAccept the default SampleModule.
为模块提供 Docker 映像存储库Provide Docker image repository for the module 映像存储库包含容器注册表的名称和容器映像的名称。An image repository includes the name of your container registry and the name of your container image. 容器映像是基于你在上一步中提供的名称预先填充的。Your container image is prepopulated from the name you provided in the last step. 将 localhost:5000 替换为 Azure 容器注册表中的“登录服务器”值。Replace localhost:5000 with the Login server value from your Azure container registry. 可以在 Azure 门户的容器注册表的“概述”页中检索“登录服务器”值。You can retrieve the Login server value from the Overview page of your container registry in the Azure portal.

最终的映像存储库看起来类似于 <registry name>.azurecr.cn/samplemodule。The final image repository looks like <registry name>.azurecr.cn/samplemodule.

提供 Docker 映像存储库

在 Visual Studio Code 窗口中加载新解决方案后,请花时间熟悉其创建的文件:Once your new solution loads in the Visual Studio Code window, take a moment to familiarize yourself with the files that it created:

  • .vscode 文件夹包含名为 launch.json 的文件,该文件用于调试模块。The .vscode folder contains a file called launch.json, which is used for debugging modules.

  • modules 文件夹包含用于解决方案中每个模块的文件夹。The modules folder contains a folder for each module in your solution. 现在应该只有 SampleModule,或为模块提供的任何名称。Right now, that should only be SampleModule, or whatever name you gave to the module. SampleModule 文件夹包含主程序代码、模块元数据和多个 Docker 文件。The SampleModule folder contains the main program code, the module metadata, and several Docker files.

  • .env 文件保存容器注册表凭据。The .env file holds the credentials to your container registry. 这些凭据与 IoT Edge 设备共享,以便它可以访问并拉取容器映像。These credentials are shared with your IoT Edge device so that it has access to pull the container images.

  • deployment.debug.template.json 文件和 deployment.template.json 文件是帮助创建部署清单的模板。The deployment.debug.template.json file and deployment.template.json file are templates that help you create a deployment manifest. 部署清单 是一个文件,可准确定义想要在设备上部署的模块、应如何配置它们以及它们如何相互通信及与云通信。A deployment manifest is a file that defines exactly which modules you want deployed on a device, how they should be configured, and how they can communicate with each other and the cloud. 模板文件使用指针来表示某些值。The template files use pointers for some values. 将模板转换为真正的部署清单时,指针将替换为从其他解决方案文件中获取的值。When you transform the template into a true deployment manifest, the pointers are replaced with values taken from other solution files. 找到部署模板中的两个常用占位符:Locate the two common placeholders in your deployment template:

    • 在“注册表凭据”部分中,将根据创建解决方案时提供的信息自动填充地址。In the registry credentials section, the address is autofilled from the information you provided when you created the solution. 但是,用户名和密码引用 .env 文件中存储的变量。However, the username and password reference the variables stored in the .env file. 此配置是出于安全考量,因为 .env 文件被 Git 忽略,但部署模板未被忽略。This configuration is for security, as the .env file is git ignored, but the deployment template is not.
    • 在“SampleModule”部分中,即使在创建解决方案时提供了映像存储库,也未填充容器映像。In the SampleModule section, the container image isn't filled in even though you provided the image repository when you created the solution. 此占位符指向 SampleModule 文件夹中的 module.json 文件。This placeholder points to the module.json file inside the SampleModule folder. 如果转到该文件,将看到“映像”字段确实包含存储库,但也包含由容器的版本和平台组成的标记值。If you go to that file, you'll see that the image field does contain the repository, but also a tag value that is made up of the version and the platform of the container. 可以在开发周期中手动迭代版本,并使用我们在本部分稍后介绍的开关选择容器平台。You can iterate the version manually as part of your development cycle, and you select the container platform using a switcher that we introduce later in this section.

向 IoT Edge 代理提供注册表凭据Provide your registry credentials to the IoT Edge agent

环境文件存储容器注册表的凭据,并将其与 IoT Edge 运行时共享。The environment file stores the credentials for your container registry and shares them with the IoT Edge runtime. 运行时需要这些凭据才能将容器映像拉取到 IoT Edge 设备中。The runtime needs these credentials to pull your container images onto the IoT Edge device.


如果你未将 localhost:5000 值替换为 Azure 容器注册表中的登录服务器值,则在创建项目模板步骤中,部署清单的 .env 文件和 registryCredentials 部分将缺失 。If you didn't replace the localhost:5000 value with the login server value from your Azure container registry, in the Create a project template step, the .env file and the registryCredentials section of the deployment manifest will be missing.

IoT Edge 扩展尝试从 Azure 中拉取容器注册表凭据并将其填充到环境文件中。The IoT Edge extension tries to pull your container registry credentials from Azure and populate them in the environment file. 检查凭据是否已包含在内。Check to see if your credentials are already included. 如果没有,请立即添加:If not, add them now:

  1. 打开模块解决方案中的 .env 文件。Open the .env file in your module solution.
  2. 添加从 Azure 容器注册表中复制的 usernamepassword 值。Add the username and password values that you copied from your Azure container registry.
  3. 将更改保存到 .env 文件。Save your changes to the .env file.

选择目标体系结构Select your target architecture

目前,Visual Studio Code 可以为 Linux AMD64 和 ARM32v7 设备开发 C# 模块。Currently, Visual Studio Code can develop C# modules for Linux AMD64 and ARM32v7 devices. 需要选择每种解决方案的目标体系结构,因为这会影响容器的生成和运行方式。You need to select which architecture you're targeting with each solution, because that affects how the container is built and runs. 默认值为 Linux AMD64。The default is Linux AMD64.

  1. 打开命令面板并搜索 Azure IoT Edge:Set Default Target Platform for Edge Solution,或选择窗口底部侧栏中的快捷方式图标。Open the command palette and search for Azure IoT Edge: Set Default Target Platform for Edge Solution, or select the shortcut icon in the side bar at the bottom of the window.


  2. 在命令面板中,从选项列表中选择目标体系结构。In the command palette, select the target architecture from the list of options. 在本教程中,我们使用 Ubuntu 虚拟机作为 IoT Edge 设备,因此将保留默认的“amd64” 。For this tutorial, we're using an Ubuntu virtual machine as the IoT Edge device, so will keep the default amd64.

查看示例代码Review the sample code

创建的解决方案模板包含 IoT Edge 模块的示例代码。The solution template that you created includes sample code for an IoT Edge module. 此示例模块仅接收消息,然后传递消息。This sample module simply receives messages and then passes them on. 管道功能演示 IoT Edge 中的一个重要概念,即模块之间相互通信的方式。The pipeline functionality demonstrates an important concept in IoT Edge, which is how modules communicate with each other.

每个模块可以在其代码中声明多个 输入输出 队列。Each module can have multiple input and output queues declared in their code. 在设备上运行的 IoT Edge 中心将来自一个模块的输出的消息路由到一个或多个模块的输入。The IoT Edge hub running on the device routes messages from the output of one module into the input of one or more modules. 用于声明输入和输出的特定代码因语言而异,但所有模块的概念都相同。The specific code for declaring inputs and outputs varies between languages, but the concept is the same across all modules. 有关在模块之间路由的详细信息,请参阅声明路由For more information about routing between modules, see Declare routes.

项目模板附带的示例 C# 代码使用适用于 .NET 的 IoT 中心 SDK 中的 ModuleClient 类The sample C# code that comes with the project template uses the ModuleClient Class from the IoT Hub SDK for .NET.

  1. 打开 Program.cs 文件,该文件位于 modules/SampleModule/ 文件夹中。Open the Program.cs file, which is inside the modules/SampleModule/ folder.

  2. 在 program.cs 中,找到 SetInputMessageHandlerAsync 方法。In program.cs, find the SetInputMessageHandlerAsync method.

  3. SetInputMessageHandlerAsync 方法会设置一个输入队列,用来接收传入消息。The SetInputMessageHandlerAsync method sets up an input queue to receive incoming messages. 查看此方法,并了解它如何初始化名为 input1 的输入队列。Review this method and see how it initializes an input queue called input1.

    在 SetInputMessageCallback 构造函数中找到输入名称

  4. 接下来,找到 SendEventAsync 方法。Next, find the SendEventAsync method.

  5. SendEventAsync 方法会处理收到的消息,并设置一个输出队列,用来传递这些消息。The SendEventAsync method processes received messages and sets up an output queue to pass them along. 查看此方法,可以看到它会初始化名为 output1 的输出队列。Review this method and see that it initializes an output queue called output1.

    在 SendEventToOutputAsync 中找到输出名称

  6. 打开 deployment.template.json 文件。Open the deployment.template.json file.

  7. 找到 $edgeAgent 所需属性的 modules 属性。Find the modules property of the $edgeAgent desired properties.

    此处应该列出两个模块。There should be two modules listed here. 一个模块是 SimulatedTemperatureSensor 模块,该模块默认包含在所有模板中,提供可用于测试模块的模拟温度数据。One is the SimulatedTemperatureSensor module, which is included in all the templates by default to provide simulated temperature data that you can use to test your modules. 另一个模块是作为此解决方案一部分创建的 SampleModule 模块。The other is the SampleModule module that you created as part of this solution.

  8. 在文件底部,找到 $edgeHub 模块的所需属性。At the bottom of the file, find the desired properties for the $edgeHub module.

    IoT Edge 中心模块的其中一个函数可在部署中的所有模块之间路由消息。One of the functions of the IoT Edge hub module is to route messages between all the modules in a deployment. 查看 routes 属性中的值。Review the values in the routes property. 一个路由 SampleModuleToIoTHub 使用通配符 (*) 来指示来自 SampleModule 模块中任何输出队列的任何消息。One route, SampleModuleToIoTHub, uses a wildcard character (** _) to indicate any messages coming from any output queues in the SampleModule module. 这些消息进入 $upstream(用于指示 IoT 中心的预留名称)。These messages go into _$upstream*, which is a reserved name that indicates IoT Hub. 另一个路由 sensorToSampleModule 接收来自 SimulatedTemperatureSensor 模块的消息,并将它们路由到在 SampleModule 代码中初始化的 input1 输入队列。The other route, sensorToSampleModule, takes messages coming from the SimulatedTemperatureSensor module and routes them to the input1 input queue that you saw initialized in the SampleModule code.

    查看 deployment.template.json 中的路由

生成并推送解决方案Build and push your solution

你已查看模块代码和部署模板来了解一些关键部署概念。You've reviewed the module code and the deployment template to understand some key deployment concepts. 现在,已准备好生成 SampleModule 容器映像并将其推送到容器注册表。Now, you're ready to build the SampleModule container image and push it to your container registry. 借助适用于 Visual Studio Code 的 IoT Tools 扩展,此步骤还会根据模板文件中的信息和解决方案文件中的模块信息生成部署清单。With the IoT tools extension for Visual Studio Code, this step also generates the deployment manifest based on the information in the template file and the module information from the solution files.

登录 DockerSign in to Docker

向 Docker 提供容器注册表凭据,以便它可以推送要存储在注册表中的容器映像。Provide your container registry credentials to Docker so that it can push your container image to be stored in the registry.

  1. 选择“查看” > “终端”,打开 Visual Studio Code 集成终端 。Open the Visual Studio Code integrated terminal by selecting View > Terminal.

  2. 使用创建注册表后保存的 Azure 容器注册表凭据登录 Docker。Sign in to Docker with the Azure Container registry credentials that you saved after creating the registry.

    docker login -u <ACR username> -p <ACR password> <ACR login server>

    可能会收到一条安全警告,推荐使用 --password-stdinYou may receive a security warning recommending the use of --password-stdin. 这条最佳做法是针对生产方案建议的,这超出了本教程的范畴。While that best practice is recommended for production scenarios, it's outside the scope of this tutorial. 有关详细信息,请参阅 docker login 参考。For more information, see the docker login reference.

  3. 登录到 Azure 容器注册表Log in to Azure Container Registry

    az acr login -n <ACR registry name>

生成并推送Build and push

Visual Studio Code 现在有权访问容器注册表,因此可以将解决方案代码转换为容器映像。Visual Studio Code now has access to your container registry, so it's time to turn the solution code into a container image.

  1. 在 Visual Studio Code 资源管理器中右键单击 deployment.template.json 文件,然后选择“生成并推送 IoT Edge 解决方案” 。In the Visual Studio Code explorer, right-click the deployment.template.json file and select Build and Push IoT Edge Solution.

    生成并推送 IoT Edge 模块

    “生成并推送”命令会启动三项操作。The build and push command starts three operations. 首先,它在解决方案中创建名为 config 的新文件夹,用于保存基于部署模板和其他解决方案文件中的信息生成的完整部署清单。First, it creates a new folder in the solution called config that holds the full deployment manifest, built out of information in the deployment template and other solution files. 其次,它会运行 docker build,以基于目标体系结构的相应 dockerfile 生成容器映像。Second, it runs docker build to build the container image based on the appropriate dockerfile for your target architecture. 然后,它会运行 docker push,以将映像存储库推送到容器注册表。Then, it runs docker push to push the image repository to your container registry.

    首次执行此过程可能需要几分钟时间,但下次运行命令时速度会变快。This process may take several minutes the first time, but is faster the next time that you run the commands.

  2. 打开新建的 config 文件夹中的 deployment.amd64.json 文件。Open the deployment.amd64.json file in newly created config folder. 文件名反映目标体系结构,因此,如果选择其他体系结构,则会有所不同。The filename reflects the target architecture, so it will be different if you chose a different architecture.

  3. 请注意,具有占位符的两个参数现在都填充了适当的值。Notice that the two parameters that had placeholders now are filled in with their proper values. registryCredentials 部分具有从 .env 文件中拉取的注册表用户名和密码。The registryCredentials section has your registry username and password pulled from the .env file. SampleModule 具有完整的映像存储库,以及 module.json 文件的名称、版本和体系结构标记。The SampleModule has the full image repository with the name, version, and architecture tag from the module.json file.

  4. 打开 SampleModule 文件夹中的 module.json 文件。Open the module.json file in the SampleModule folder.

  5. 更改模块映像的版本号。Change the version number for the module image. (版本,而不是 $schema-version。)例如,将补丁版本号递增为 0.0.2,就像我们对模块代码进行了小修补一样。(The version, not the $schema-version.) For example, increment the patch version number to 0.0.2 as though we had made a small fix in the module code.


    模块版本支持版本控制,允许在将更新部署到生产环境之前在少量设备上测试更改。Module versions enable version control, and allow you to test changes on a small set of devices before deploying updates to production. 如果在生成并推送之前未递增模块版本,则会替代容器注册表中的存储库。If you don't increment the module version before building and pushing, then you overwrite the repository in your container registry.

  6. 将更改保存到 module.json 文件。Save your changes to the module.json file.

  7. 再次右键单击 deployment.template.json 文件,然后再次选择“生成并推送 IoT Edge 解决方案” 。Right-click the deployment.template.json file again, and again select Build and Push IoT Edge Solution.

  8. 再次打开 deployment.amd64.json 文件。Open the deployment.amd64.json file again. 请注意,再次运行“生成并推送”命令时未创建新文件,Notice that a new file wasn't created when you ran the build and push command again. 而是更新了同一文件以反映更改。Rather, the same file was updated to reflect the changes. SampleModule 映像现在指向容器的 0.0.2 版。The SampleModule image now points to the 0.0.2 version of the container.

  9. 若要进一步验证“生成并推送”命令执行的操作,请转到 Azure 门户并导航到容器注册表。To further verify what the build and push command did, go to the Azure portal and navigate to your container registry.

  10. 在容器注册表中,依次选择“存储库”和“samplemodule” 。In your container registry, select Repositories then samplemodule. 验证映像的两个版本是否都已推送到注册表。Verify that both versions of the image were pushed to the registry.



如果在生成并推送模块映像时遇到错误,这通常与开发计算机上的 Docker 配置有关。If you encounter errors when building and pushing your module image, it often has to do with Docker configuration on your development machine. 使用以下检查来检查配置:Use the following checks to review your configuration:

  • 是否使用从容器注册表复制的凭据运行 docker login 命令?Did you run the docker login command using the credentials that you copied from your container registry? 这些凭据与用于登录 Azure 的凭据不同。These credentials are different than the ones that you use to sign in to Azure.
  • 你的容器存储库是否正确?Is your container repository correct? 它是否拥有正确的容器注册表名称和正确的模块名称?Does it have your correct container registry name and your correct module name? 打开 SampleModule 文件夹中的 module.json 文件进行检查。Open the module.json file in the SampleModule folder to check. 存储库值应类似于 <registry name>.azurecr.cn/samplemoduleThe repository value should look like <registry name>.azurecr.cn/samplemodule.
  • 如果为模块使用的名称不是 SampleModule,那么使用的名称在整个解决方案中是否保持一致?If you used a different name than SampleModule for your module, is that name consistent throughout the solution?
  • 计算机运行的容器类型与要生成的容器类型是否相同?Is your machine running the same type of containers that you're building? 本教程适用于 Linux IoT Edge 设备,因此,Visual Studio Code 应在侧栏指明 amd64arm32v7,且 Docker Desktop 应运行 Linux 容器。This tutorial is for Linux IoT Edge devices, so Visual Studio Code should say amd64 or arm32v7 in the side bar, and Docker Desktop should be running Linux containers.

将模块部署到设备Deploy modules to device

因为已确认生成的容器映像存储在容器注册表中,所以现在可将它们部署到设备中。You verified that the built container images are stored in your container registry, so it's time to deploy them to a device. 确保 IoT Edge 设备已启动并运行。Make sure that your IoT Edge device is up and running.

  1. 在 Visual Studio Code 资源管理器中的“Azure IoT 中心”部分下,展开“设备”可查看 IoT 设备的列表。 In the Visual Studio Code explorer, under the Azure IoT Hub section, expand Devices to see your list of IoT devices.

  2. 右键单击想要在其中部署的 IoT Edge 设备,然后选择“为单个设备创建部署” 。Right-click the IoT Edge device that you want to deploy to, then select Create Deployment for Single Device.


  3. 在文件资源管理器中,导航到 config 文件夹,然后选择 deployment.amd64.json 文件。In the file explorer, navigate into the config folder then select the deployment.amd64.json file.

    不要使用 deployment.template.json 文件,该文件不包含容器注册表凭据或模块映像值。Do not use the deployment.template.json file, which doesn't have the container registry credentials or module image values in it. 如果面向 Linux ARM32 设备,则部署清单将命名为 deployment.arm32v7.json。If you're targeting a Linux ARM32 device, the deployment manifest will be named deployment.arm32v7.json.

  4. 在设备下,展开“模块”可查看已部署的正在运行的模块的列表。Under your device, expand Modules to see a list of deployed and running modules. 单击“刷新”按钮。Click the refresh button. 应看到新的 SimulatedTemperatureSensor 和 SampleModule 模块在设备上运行。You should see the new SimulatedTemperatureSensor and SampleModule modules running on your device.

    启动模块可能需要数分钟时间。It may take a few minutes for the modules to start. IoT Edge 运行时需要接收其新的部署清单,从容器运行时下拉模块映像,然后启动每个新模块。The IoT Edge runtime needs to receive its new deployment manifest, pull down the module images from the container runtime, then start each new module.

    查看在 IoT Edge 设备上运行的模块

查看设备消息View messages from device

SampleModule 代码通过其输入队列接收消息,并通过其输出队列传递消息。The SampleModule code receives messages through its input queue and passes them along through its output queue. 部署清单声明了从 SimulatedTemperatureSensor 将消息传递到 SampleModule,再将消息从 SampleModule 转发到 IoT 中心的路由。The deployment manifest declared routes that passed messages to SampleModule from SimulatedTemperatureSensor, and then forwarded messages from SampleModule to IoT Hub. 适用于 Visual Studio Code 的 Azure IoT Tools 允许查看从各个设备到达 IoT 中心的消息。The Azure IoT tools for Visual Studio Code allow you to see messages as they arrive at IoT Hub from your individual devices.

  1. 在 Visual Studio Code 资源管理器中,右键单击想要监视的 IoT Edge 设备,然后选择“开始监视内置事件终结点” 。In the Visual Studio Code explorer, right-click the IoT Edge device that you want to monitor, then select Start Monitoring Built-in Event Endpoint.

  2. 观察 Visual Studio Code 的输出窗口,查看到达 IoT 中心的消息。Watch the output window in Visual Studio Code to see messages arriving at your IoT hub.


查看设备上的更改View changes on device

如果想要查看设备本身发生的情况,请使用本部分中的命令检查设备上运行的 IoT Edge 运行时和模块。If you want to see what's happening on your device itself, use the commands in this section to inspect the IoT Edge runtime and modules running on your device.

本部分中的命令适用于 IoT Edge 设备,而不适用于开发计算机。The commands in this section are for your IoT Edge device, not your development machine. 如果为 IoT Edge 设备使用虚拟机,请立即连接到虚拟机。If you're using a virtual machine for your IoT Edge device, connect to it now. 在 Azure 中,转到虚拟机的“概述”页,然后选择“连接”以访问安全 shell 连接 。In Azure, go to the virtual machine's overview page and select Connect to access the secure shell connection.

  • 查看部署到设备的所有模块,并检查其状态:View all modules deployed to your device, and check their status:

    iotedge list

    应该看到四个模块:两个 IoT Edge 运行时模块、SimulatedTemperatureSensor 和 SampleModule。You should see four modules: the two IoT Edge runtime modules, SimulatedTemperatureSensor, and SampleModule. 全部四个模块都应列为“正在运行”。All four should be listed as running.

  • 检查特定模块的日志:Inspect the logs for a specific module:

    iotedge logs <module name>

    IoT Edge 模块区分大小写。IoT Edge modules are case-sensitive.

    SimulatedTemperatureSensor 和 SampleModule 日志应显示其正在处理的消息。The SimulatedTemperatureSensor and SampleModule logs should show the messages they're processing. edgeAgent 模块负责启动其他模块,因此其日志将包含有关实施部署清单的信息。The edgeAgent module is responsible for starting the other modules, so its logs will have information about implementing the deployment manifest. 如果有任何模块未列出或未运行,则 edgeAgent 日志可能包含相关错误信息。If any module isn't listed or isn't running, the edgeAgent logs will probably have the errors. edgeHub 模块负责模块和 IoT 中心之间的通信。The edgeHub module is responsible for communications between the modules and IoT Hub. 如果模块已启动并运行,但消息未到达 IoT 中心,则 edgeHub 日志可能包含相关错误信息。If the modules are up and running, but the messages aren't arriving at your IoT hub, the edgeHub logs will probably have the errors.

清理资源Clean up resources

如果打算继续学习下一篇建议的文章,可以保留已创建的资源和配置,以便重复使用。If you plan to continue to the next recommended article, you can keep the resources and configurations that you created and reuse them. 还可以继续使用相同的 IoT Edge 设备作为测试设备。You can also keep using the same IoT Edge device as a test device.

否则,可以删除本文中使用的本地配置和 Azure 资源,以免产生费用。Otherwise, you can delete the local configurations and the Azure resources that you used in this article to avoid charges.

删除 Azure 资源Delete Azure resources

删除 Azure 资源和资源组的操作不可逆。Deleting Azure resources and resource groups is irreversible. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在现有的包含要保留资源的资源组中创建了 IoT 中心,请只删除 IoT 中心资源本身,而不要删除资源组。If you created the IoT hub inside an existing resource group that has resources that you want to keep, delete only the IoT hub resource itself, instead of deleting the resource group.

若要删除资源,请执行以下操作:To delete the resources:

  1. 登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal and select Resource groups.

  2. 选择包含 IoT Edge 测试资源的资源组的名称。Select the name of the resource group that contains your IoT Edge test resources.

  3. 查看包含在资源组中的资源的列表。Review the list of resources contained in your resource group. 若要删除这一切,可以选择“删除资源组”。 If you want to delete all of them, you can select Delete resource group. 如果只需删除部分内容,可以单击要单独删除的每个资源。If you want to delete only some of them, you can click into each resource to delete them individually.

后续步骤Next steps

在本教程中,在开发计算机上设置了 Visual Studio Code 并从中部署了第一个 IoT Edge 模块。In this tutorial, you set up Visual Studio Code on your development machine and deployed your first IoT Edge module from it. 你已经了解基本概念,请尝试向模块添加功能,以便它可以分析通过它传递的数据。Now that you know the basic concepts, try adding functionality to a module so that it can analyze the data passing through it. 选择首选语言:Choose your preferred language: