在 VS Code 中试用

将容器化应用部署到 Azure

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

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

先决条件

创建应用程序镜像

如果你已有镜像,请跳过此步骤,然后继续执行将镜像推送到容器注册表步骤。

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

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

    Build container image

    你可以在 Build Image 命令的输出中找到镜像名称,在 Docker Explorer 的“镜像”面板中也可以找到相同内容。

    Build image output

将镜像推送到容器注册表

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

  1. 打开 Docker Explorer,然后在“注册表”组下选择 连接注册表... 图标并按照提示操作。选择提供程序 (Azure 或 Docker Hub) 并提供连接到注册表的凭据。

    Connect to Registry

  2. 现在,注册表将在“注册表”下可见。

    Registries

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

    • 若要在 Azure ACR 中创建注册表,请打开 Docker 视图的“注册表”部分,如果尚未登录 Azure,请登录 Azure,然后右键单击要使用的订阅,并选择创建注册表

    • 在上一节中生成的镜像将显示在 Docker Explorer 的“镜像”部分下。右键单击并选择标记...

      Tag image

    • 指定新名称 <your registry or username>/<image name>:<tag> 并完成标记操作。例如,对于名为 WebApp6 的 ACR,新的镜像名称将是 'webapp6.azurecr.io/webapp6:latest';对于 Docker Hub,将是 'myusername/webapp6:latest'。

  4. 镜像将显示在 Docker Explorer 中镜像标记指向的注册表下。选择此镜像,然后选择推送。如果尚未标记镜像,系统会提示你选择要推送到的注册表,并且会根据选择对镜像进行标记。

    Push image

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

    Refresh registry

将镜像部署到 Azure

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

  1. 在 Docker Explorer 中,导航到“注册表”下的镜像,右键单击标记,然后选择将镜像部署到 Azure App Service...将镜像部署到 Azure Container Apps...

    Deploy to Azure App Service

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

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

    Deployment complete notification

  4. 你还可以在 Visual Studio Code 的“输出”面板的 Docker 部分中看到结果。

    Deployment complete output

  5. 若要浏览已部署的网站,可以使用 Ctrl+click 在“输出”面板中打开 URL。你可能需要等待片刻,直到应用在 Azure 中上线。新的 App Service 或 Container App 也会出现在 Visual Studio Code 的 Azure 视图中,你可以在其中右键单击网站并选择浏览网站

    Web Application

后续步骤

继续阅读以了解更多信息

  • Azure 扩展 - VS Code Marketplace 中有数百个适用于 Azure 和云的扩展。
  • 部署到 Azure - 逐步了解如何将应用程序部署到 Azure。
  • 使用 MongoDB - 在 VS Code 中创建、管理和查询 MongoDB 数据库。