教程:使用 Azure 虚拟网络 NAT 网关控制 Azure Functions 出站 IPTutorial: Control Azure Functions outbound IP with an Azure virtual network NAT gateway

虚拟网络地址转换 (NAT) 简化了虚拟网络仅限出站的 Internet 连接。Virtual network address translation (NAT) simplifies outbound-only internet connectivity for virtual networks. 在子网中配置后,所有出站连接将使用指定的静态公共 IP 地址。When configured on a subnet, all outbound connectivity uses your specified static public IP addresses. NAT 对于需要使用第三方服务(使用 IP 地址允许列表作为安全措施)的 Azure Functions 或 Web 应用非常有用。An NAT can be useful for Azure Functions or Web Apps that need to consume a third-party service that uses an allowlist of IP address as a security measure. 若要了解详细信息,请参阅什么是虚拟网络 NAT?To learn more, see What is Virtual Network NAT?.

本教程介绍如何使用虚拟网络 NAT 从 HTTP 触发的函数路由出站流量。This tutorial shows you how to use virtual network NATs to route outbound traffic from an HTTP triggered function. 此函数可让你检查其自身的出站 IP 地址。This function lets you check its own outbound IP address. 在本教程中,你将:During this tutorial, you'll:

  • 创建虚拟网络Create a virtual network
  • 创建高级计划函数应用Create a Premium plan function app
  • 创建公共 IP 地址Create a public IP address
  • 创建 NAT 网关Create a NAT gateway
  • 配置函数应用以通过 NAT 网关路由出站流量Configure function app to route outbound traffic through the NAT gateway

拓扑Topology

下图显示了你创建的解决方案的体系结构:The following diagram shows the architecture of the solution that you create:

NAT 网关集成的 UI

高级计划中运行的函数与 Azure 应用服务中的 Web 应用具有相同的承载功能,其中包括 VNet 集成功能。Functions running in the Premium plan have the same hosting capabilities as web apps in Azure App Service, which includes the VNet Integration feature. 若要了解有关 VNet 集成的详细信息(包括故障排除和高级配置),请参阅将应用与 Azure 虚拟网络集成To learn more about VNet Integration, including troubleshooting and advanced configuration, see Integrate your app with an Azure virtual network.

先决条件Prerequisites

若要学习本教程,必须了解 IP 寻址和子网划分。For this tutorial, it's important that you understand IP addressing and subnetting. 可以从这篇介绍了寻址和子网划分基础知识的文章入手。You can start with this article that covers the basics of addressing and subnetting. 网上还有其他许多相关文章。Many more articles are available online.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don’t have an Azure subscription, create a Trial before you begin.

如果已完成将 Functions 与 Azure 虚拟网络集成教程,可以跳至创建 HTTP 触发器函数If you've already completed the integrate Functions with an Azure virtual network tutorial, you can skip to Create an HTTP trigger function.

创建虚拟网络Create a virtual network

  1. 在 Azure 门户菜单中,选择“创建资源”。From the Azure portal menu, select Create a resource. 在 Azure 市场中,选择“网络” > “虚拟网络” 。From the Azure Marketplace, select Networking > Virtual network.

  2. 在“创建虚拟网络”中,按照下表中显示的说明输入或选择设置:In Create virtual network, enter or select the settings specified as shown in the following table:

    设置Setting Value
    订阅Subscription 选择订阅。Select your subscription.
    资源组Resource group 选择“新建”,输入 myResourceGroup,然后选择“确定”。Select Create new, enter myResourceGroup, then select OK.
    名称Name 输入 myResourceGroup-vnetEnter myResourceGroup-vnet.
    位置Location 选择“中国北部 2”。Select China North 2.
  3. 选择“下一步: IP 地址”,输入 10.10.0.0/16 作为“IPv4 地址空间”。Select Next: IP Addresses, and for IPv4 address space, enter 10.10.0.0/16.

  4. 选择“添加子网”,输入 Tutorial-Net 作为“子网名称”,输入 10.10.1.0/24 作为“子网地址范围” 。Select Add subnet, then enter Tutorial-Net for Subnet name and 10.10.1.0/24 for Subnet address range.

    用于创建 VNet 的“IP 地址”选项卡

  5. 选择“添加”,然后选择“查看 + 创建”。 Select Add, then select Review + create. 将其余的设置保留默认值,然后选择“创建”。Leave the rest as default and select Create.

  6. 在“创建虚拟网络”中,选择“创建”。 In Create virtual network, select Create.

接下来,在高级计划中创建一个函数应用。Next, you create a function app in the Premium plan. 此计划提供无服务器规模,同时支持虚拟网络集成。This plan provides serverless scale while supporting virtual network integration.

在高级计划中创建函数应用Create a function app in a Premium plan

备注

为在本教程中获得最佳体验,请选择“.NET”作为运行时堆栈,选择“Windows”作为操作系统。For the best experience in this tutorial, choose .NET for runtime stack and choose Windows for operating system. 此外,在虚拟网络所在的同一区域中创建函数应用。Also, create you function app in the same region as your virtual network.

  1. 在 Azure 门户菜单或“主页”页中,选择“创建资源” 。From the Azure portal menu or the Home page, select Create a resource.

  2. “新建” 页面,选择 “计算” > “函数应用”In the New page, select Compute > Function App.

  3. 在“基本信息”页面上,按照下列所述使用函数应用设置:On the Basics page, use the function app settings as specified in the following table:

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 订阅Your subscription 要在其下创建此新函数应用的订阅。The subscription under which this new function app is created.
    资源组Resource Group myResourceGroupmyResourceGroup 要在其中创建 Function App 的新资源组的名称。Name for the new resource group in which to create your function app.
    函数应用名称Function App name 全局唯一名称Globally unique name 用于标识新 Function App 的名称。Name that identifies your new function app. 有效字符为 a-z(不区分大小写)、0-9-Valid characters are a-z (case insensitive), 0-9, and -.
    发布Publish 代码Code 用于发布代码文件或 Docker 容器的选项。Option to publish code files or a Docker container.
    运行时堆栈Runtime stack 首选语言Preferred language 选择支持你喜欢的函数编程语言的运行时。Choose a runtime that supports your favorite function programming language.
    区域Region 首选区域Preferred region 选择离你近或离函数访问的其他服务近的区域Choose a region near you or near other services your functions access.
  4. 在完成时选择“下一步:托管”。Select Next: Hosting. 在“托管”页面上,输入以下设置:On the Hosting page, enter the following settings:

    设置Setting 建议的值Suggested value 说明Description
    存储帐户Storage account 全局唯一名称Globally unique name 创建函数应用使用的存储帐户。Create a storage account used by your function app. 存储帐户名称必须为 3 到 24 个字符,并且只能包含数字和小写字母。Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only. 也可使用现有帐户,但该帐户必须符合存储帐户要求You can also use an existing account, which must meet the storage account requirements.
    操作系统Operating system 首选操作系统Preferred operating system 系统会根据你的运行时堆栈选择为你预先选择一个操作系统,但你可以根据需要更改该设置。An operating system is pre-selected for you based on your runtime stack selection, but you can change the setting if necessary. Python 仅在 Linux 上受支持。Python is only supported on Linux. 仅在 Windows 上支持门户内编辑。In-portal editing is only supported on Windows.
    计划Plan PremiumPremium 定义如何将资源分配给 Function App 的托管计划。Hosting plan that defines how resources are allocated to your function app. 选择“高级”。Select Premium. 默认创建一个新的应用服务计划。By default, a new App Service plan is created. 默认的“SKU 和大小”为 EP1,其中 EP 表示“弹性高级”(elastic premium) 。The default Sku and size is EP1, where EP stands for elastic premium. 要了解详细信息,请参阅高级 SKU 的列表To learn more, see the list of Premium SKUs.
    在高级计划上运行 JavaScript 函数时,应选择 vCPU 数更少的实例。When running JavaScript functions on a Premium plan, you should choose an instance that has fewer vCPUs. 有关详细信息,请参阅选择单核心高级计划For more information, see Choose single-core Premium plans.
  5. 在完成时选择“下一步:监视”。Select Next: Monitoring. 在“监视”页面上,输入以下设置:On the Monitoring page, enter the following settings:

    设置Setting 建议的值Suggested value 说明Description
    Application InsightsApplication Insights 默认Default 在最近的受支持的区域中,创建一个具有相同应用名称的 Application Insights 资源。Creates an Application Insights resource of the same App name in the nearest supported region. 展开此设置即可更改“新建资源名称”,或者在 Azure 地理位置选择其他位置来存储你的数据 。By expanding this setting, you can change the New resource name or choose a different Location in an Azure geography to store your data.
  6. 选择“查看 + 创建”,以便查看应用配置选择。Select Review + create to review the app configuration selections.

  7. 在“查看 + 创建”页上查看设置,然后选择“创建”来预配并部署函数应用 。On the Review + create page, review your settings, and then select Create to provision and deploy the function app.

  8. 选择门户右上角的“通知”图标,留意是否显示了“部署成功”消息。 Select the Notifications icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

  9. 选择“转到资源”,查看新的函数应用。Select Go to resource to view your new function app. 还可选择“固定到仪表板”。You can also select Pin to dashboard. 固定可以更轻松地从仪表板返回此函数应用资源。Pinning makes it easier to return to this function app resource from your dashboard.

    部署通知

将函数应用连接到虚拟网络Connect your function app to the virtual network

现在可以将函数应用连接到虚拟网络。You can now connect your function app to the virtual network.

  1. 在函数应用中,选择左侧菜单中的“网络”,然后在“VNet 集成”下选择“单击此处进行配置” 。In your function app, select Networking in the left menu, then under VNet Integration, select Click here to configure.

    在函数应用中选择“网络”

  2. 在“VNET 集成”页上,选择“添加 VNet” 。On the VNET Integration page, select Add VNet.

  3. 在“网络功能状态”中,使用插图下面的表格中的设置:In Network Feature Status, use the settings in the table below the image:

    定义函数应用虚拟网络

    设置Setting 建议的值Suggested value 说明Description
    虚拟网络Virtual Network MyResourceGroup-vnetMyResourceGroup-vnet 此虚拟网络就是你先前创建的网络。This virtual network is the one you created earlier.
    子网Subnet 创建新子网Create New Subnet 在虚拟网络中创建一个子网供函数应用使用。Create a subnet in the virtual network for your function app to use. 必须将 VNet 集成配置为使用空子网。VNet Integration must be configured to use an empty subnet.
    子网名称Subnet name Function-NetFunction-Net 新子网的名称。Name of the new subnet.
    虚拟网络地址块Virtual network address block 10.10.0.0/1610.10.0.0/16 只应定义一个地址块。You should only have one address block defined.
    子网地址块Subnet Address Block 10.10.2.0/2410.10.2.0/24 子网大小限制高级计划函数应用可以横向扩展到的实例总数。The subnet size restricts the total number of instances that your Premium plan function app can scale out to. 此示例使用具有 254 个可用主机地址的 /24 子网。This example uses a /24 subnet with 254 available host addresses. 此子网进行了超量预配,但易于计算。This subnet is over-provisioned, but easy to calculate.
  4. 选择“确定”以添加子网。Select OK to add the subnet. 关闭“VNet 集成”和“网络功能状态”页,返回到函数应用页 。Close the VNet Integration and Network Feature Status pages to return to your function app page.

函数应用现在可以访问虚拟网络。The function app can now access the virtual network. 接下来,将 HTTP 触发的函数添加到函数应用中。Next, you'll add an HTTP-triggered function to the function app.

创建 HTTP 触发器函数Create an HTTP trigger function

  1. 从“Functions”窗口的左侧菜单中选择“Functions”,然后从顶部菜单中选择“添加”。From the left menu of the Functions window, select Functions, then select Add from the top menu.

  2. 在“新建函数”窗口中,选择“Http 触发器”并接受 新函数 的默认名称,或输入新名称 。From the New Function window, select Http trigger and accept the default name for New Function, or enter a new name.

  3. 在“代码 + 测试”中,将模板生成的 C# 脚本 (.csx) 代码替换为以下代码:In Code + Test, replace the template-generated C# script (.csx) code with the following code:

    #r "Newtonsoft.Json"
    
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
    
        var client = new HttpClient();
        var response = await client.GetAsync(@"https://ifconfig.me");
        var responseMessage = await response.Content.ReadAsStringAsync();
    
        return new OkObjectResult(responseMessage);
    }
    

    此代码将调用一个外部网站,该网站返回调用方的 IP 地址,在本例中为此函数。This code calls an external website that returns the IP address of the caller, which in this case is this function. 此方法可让你轻松确定函数应用使用的出站 IP 地址。This method lets you easily determine the outbound IP address being used by your function app.

现已准备好运行函数并检查当前的出站 IP。Now you're ready to run the function and check the current outbound IPs.

验证当前出站 IPVerify current outbound IPs

现在可以运行该函数。Now, you can run the function. 但首先请在门户中查看函数应用正在使用哪些出站 IP。But first, check in the portal and see what outbound IPs are being use by the function app.

  1. 在函数应用中,选择“属性”并查看“出站 IP 地址”字段 。In your function app, select Properties and review the Outbound IP Addresses field.

    查看函数应用的出站 IP 地址

  2. 现在,返回到你的 HTTP 触发器函数,选择“代码 + 测试”,然后选择“测试/运行” 。Now, return to your HTTP trigger function, select Code + Test and then Test/Run.

    测试函数

  3. 选择“运行”以执行该函数,然后切换到“输出” 。Select Run to execute the function, then switch to the Output.

    测试函数输出

  4. 验证 HTTP 响应正文中的 IP 地址是否为先前查看的出站 IP 地址中的值之一。Verify that IP address in the HTTP response body is one of the values from the outbound IP addresses you viewed earlier.

现在,可以创建一个公共 IP,并使用 NAT 网关来修改此出站 IP 地址。Now, you can create a public IP and use a NAT gateway to modify this outbound IP address.

创建公共 IPCreate public IP

  1. 在你的资源组中选择“添加”,在 Azure 市场中搜索“公共 IP 地址”,然后选择“创建” 。From your resource group, select Add, search the Azure Marketplace for Public IP address, and select Create. 使用插图下面的表格中的设置:Use the settings in the table below the image:

    创建公共 IP 地址

    设置Setting 建议的值Suggested value
    IP 版本IP Version IPv4IPv4
    SKUSKU StandardStandard
    Tier 区域Regional
    名称Name 出站 IPOutbound-IP
    订阅Subscription 确保已显示你的订阅ensure your subscription is displayed
    资源组Resource group myResourceGroup(或分配给你的资源组的名称)myResourceGroup (or name you assigned to your resource group)
    位置Location 中国北部 2(或已分配给其他资源的位置)China North 2 (or location you assigned to your other resources)
    可用性区域Availability Zone 无区域No Zone
  2. 选择“创建”以提交部署。Select Create to submit the deployment.

  3. 部署完成后,导航到新建的“公共 IP 地址”资源,并查看“概述”中的 IP 地址。Once the deployment completes, navigate to your newly created Public IP Address resource and view the IP Address in the Overview.

    查看公共 IP 地址

创建 NAT 网关Create NAT gateway

现在,让我们创建 NAT 网关。Now, let's create the NAT gateway. 开始学习前面的虚拟网络教程时,Function-Net 是该教程中建议的子网名称,MyResourceGroup-vnet 是该教程中建议的虚拟网络名称。When you start with the previous virtual networking tutorial, Function-Net was the suggested subnet name and MyResourceGroup-vnet was the suggested virtual network name in that tutorial.

  1. 在你的资源组中选择“添加”,在 Azure 市场中搜索“NAT 网关”,然后选择“创建” 。From your resource group, select Add, search the Azure Marketplace for NAT gateway, and select Create. 使用插图下面的表格中的设置来填充“基本信息”选项卡:Use the settings in the table below the image to populate the Basics tab:

    创建 NAT 网关

    设置Setting 建议的值Suggested value
    订阅Subscription 你的订阅Your subscription
    资源组Resource group myResourceGroup(或分配给你的资源组的名称)myResourceGroup (or name you assigned to your resource group)
    NAT 网关名称NAT gateway name myNatGatewaymyNatGateway
    区域Region 中国北部 2(或已分配给其他资源的位置)China North 2 (or location you assigned to your other resources)
    可用性区域Availability Zone None
  2. 选择“下一步: 出站 IP”。Select Next: Outbound IP. 在“公共 IP 地址”字段中,选择前面创建的公共 IP 地址。In the Public IP addresses field, select the previously created public IP address. 将“公共 IP 前缀”保持未选中状态。Leave Public IP Prefixes unselected.

  3. 选择“下一步: 子网”。Select Next: Subnet. 在“虚拟网络”字段中选择“myResourceGroup-vnet”资源,并选择“Function-Net”子网。Select the myResourceGroup-vnet resource in the Virtual network field and Function-Net subnet.

    选择子网

  4. 依次选择“查看 + 创建”和“创建”来提交部署 。Select Review + Create then Create to submit the deployment.

部署完成后,NAT 网关便可以将流量从你的函数应用子网路由到 Internet。Once the deployment completes, the NAT gateway is ready to route traffic from your function app subnet to the Internet.

更新函数配置Update function configuration

现在,必须添加设置为 1 值的应用程序设置 WEBSITE_VNET_ROUTE_ALLNow, you must add an application setting WEBSITE_VNET_ROUTE_ALL set to a value of 1. 此设置会强制出站流量通过虚拟网络和关联的 NAT 网关。This setting forces outbound traffic through the virtual network and associated NAT gateway. 如果没有此设置,Internet 流量不会通过集成虚拟网络进行路由,你会看到相同的出站 IP。Without this setting, internet traffic isn't routed through the integrated virtual network, and you'll see the same outbound IPs.

  1. 在 Azure 门户中导航到你的函数应用,从左侧菜单中选择“配置”。Navigate to your function app in the Azure portal and select Configuration from the left-hand menu.

  2. 在“应用程序设置”下,选择“+ 新建应用程序设置”,然后使用以下值填充字段 :Under Application settings, select + New application setting and complete use the following values to fill out the fields:

    字段名称Field Name Value
    名称Name WEBSITE_VNET_ROUTE_ALLWEBSITE_VNET_ROUTE_ALL
    Value 11
  3. 选择“确定”以关闭“新建应用程序设置”对话框。Select OK to close the new application setting dialog.

  4. 选择“保存”,然后选择“继续”以保存设置 。Select Save and then Continue to save the settings.

函数应用现已配置为通过其关联的虚拟网络路由流量。The function app's now configured to route traffic through its associated virtual network.

验证新的出站 IPVerify new outbound IPs

重复上述步骤再次运行该函数。Repeat the steps earlier to run the function again. 现在,在函数输出中应会看到你在 NAT 中配置的出站 IP 地址。You should now see the outbound IP address that you configured in the NAT shown in the function output.

清理资源Clean up resources

你已创建了完成本教程所需的资源。You created resources to complete this tutorial. 你需要为这些资源付费,具体取决于你的帐户状态服务定价You'll be billed for these resources, depending on your account status and service pricing. 为了避免产生额外的成本,请在不再需要这些资源时将其删除。To avoid incurring extra costs, delete the resources when you know longer need them.

  1. 在 Azure 门户中转到“资源组”页。In the Azure portal, go to the Resource group page.

    若要从函数应用页转到该页,请选择“概览”选项卡,然后选择“资源组”下的链接。 To get to that page from the function app page, select the Overview tab and then select the link under Resource group.

    从函数应用页选择要删除的资源组。

    若要从仪表板转到该页,请选择“资源组”,然后选择用于本文的资源组。To get to that page from the dashboard, select Resource groups, and then select the resource group that you used for this article.

  2. 在“资源组”页中查看所包括的资源的列表,然后验证这些资源是否是要删除的。In the Resource group page, review the list of included resources, and verify that they're the ones you want to delete.

  3. 选择“删除资源组”,然后按说明操作。Select Delete resource group, and follow the instructions.

    可能需要数分钟才能删除完毕。Deletion may take a couple of minutes. 完成后会显示一个通知,持续数秒。When it's done, a notification appears for a few seconds. 也可以选择页面顶部的钟形图标来查看通知。You can also select the bell icon at the top of the page to view the notification.

后续步骤Next steps