将容器化应用部署到 Azure

在本指南中,您将学习如何

  • 为您的应用程序创建一个容器镜像。
  • 将镜像推送到容器注册表。
  • 将镜像部署到 Azure App Service 或 Azure Container Apps。

先决条件

创建应用程序镜像

如果您已经拥有镜像,请跳过此步骤,直接进入 将镜像推送到容器注册表 步骤。

  1. 在 VS Code 中打开应用程序文件夹。

  2. 打开命令面板 (⇧⌘P (Windows, Linux Ctrl+Shift+P)),并使用 Container Images: Build Image... 命令来构建镜像。

    Build container image

    您可以在“构建镜像 (Build Image)”命令的输出中找到镜像名称,也可以在 Container Explorer 的 Images 面板中找到它。

    Build image output

将镜像推送到容器注册表

在将镜像部署到 App Service 或 Container App 之前,必须先将镜像上传到容器注册表。该镜像可以上传到 Azure 容器注册表 (ACR)Docker Hub

  1. 打开 Container Explorer,在 Registries 组下选择 Connect Registry... 图标,并按照提示操作。选择提供商(Azure 或 Docker Hub)并提供凭据以连接到注册表。

    Connect to Registry

  2. 现在,注册表将显示在 Registries 下。

    Registries

  3. 您可以选择为镜像打标签 (Tag)。为了将镜像上传到注册表,镜像需要使用注册表名称进行打标签,以便 docker push 命令将其上传到正确的注册表。

    • 若要在 Azure ACR 中创建注册表,请打开 Container Explorer 的 Registries 部分,登录 Azure(如果尚未登录),然后右键点击您要使用的订阅,并选择 Create Registry

    • 在上一步构建的镜像将出现在 Container Explorer 的 Images 部分下。右键点击并选择 Tag...

      Tag image

    • 指定新名称 <您的注册表或用户名>/<镜像名称>:<标签> 并完成打标签操作。例如,名为 WebApp6 的 ACR 的新镜像名称为 'webapp6.azurecr.io/webapp6:latest',而对于 Docker Hub,则为 'myusername/webapp6:latest'。

  4. 镜像将显示在 Container Explorer 中镜像标签指向的注册表下。选择该镜像并选择 Push。如果镜像尚未打标签,系统将提示您选择要推送到的注册表,并根据您的选择为镜像打上标签。

    Push image

  5. 推送命令完成后,刷新镜像推送到的注册表节点,上传的镜像就会显示出来。

    Refresh registry

将镜像部署到 Azure

在上一节中,镜像已被推送到远程容器注册表。现在将其部署到 Azure App Service 或 Azure Container Apps。

  1. 在 Container Explorer 中,导航到 Registries 下的镜像,右键点击标签,然后选择 Deploy Image To Azure App Service...Deploy Image to Azure Container Apps...

    Deploy to Azure App Service

  2. 出现提示时,为 App Service 或 Container App 提供相应的值。

    • New web app name(新 Web 应用名称):该名称在 Azure 中必须是唯一的。
    • Resource group(资源组):选择现有的资源组或创建新资源组。
    • App Service plan(应用服务计划):选择现有的应用服务计划或创建新的。 (应用服务计划定义了托管网站的物理资源;对于本教程,您可以使用基础版或免费版计划层级)。
  3. 部署完成后,Visual Studio Code 会显示一条包含网站 URL 的通知。

    Deployment complete notification

  4. 您还可以在 Visual Studio Code 的输出面板 (Output panel) 的 Container Tools 部分查看结果。

    Deployment complete output

  5. 要浏览已部署的网站,您可以使用 Ctrl+点击 在输出面板中打开 URL。您可能需要稍等片刻,直到应用在 Azure 中上线。新的 App Service 或 Container App 也会出现在 Visual Studio Code 的 Azure 视图中,您可以在那里右键点击网站并选择 Browse Website

    Web Application

后续步骤

继续阅读以了解更多信息

  • Azure 扩展 - VS Code Marketplace 包含数百个用于 Azure 和云的扩展。
  • 部署到 Azure - 逐步了解如何将您的应用程序部署到 Azure。
  • 使用 MongoDB - 在 VS Code 内创建、管理和查询 MongoDB 数据库。
© . This site is unofficial and not affiliated with Microsoft.