部署最佳作法Deployment Best Practices

每個開發小組都有獨特的需求,可讓您在任何雲端服務上執行有效率的部署管線。Every development team has unique requirements that can make implementing an efficient deployment pipeline difficult on any cloud service. 本文介紹部署至 App Service 的三個主要元件:部署來源、組建管線和部署機制。This article introduces the three main components of deploying to App Service: deployment sources, build pipelines, and deployment mechanisms. 本文也涵蓋特定語言堆疊的一些最佳作法和秘訣。This article also covers some best practices and tips for specific language stacks.

部署元件Deployment Components

部署來源Deployment Source

部署來源是您應用程式程式碼的位置。A deployment source is the location of your application code. 針對生產應用程式,部署來源通常是由版本控制軟體(例如 GitHub、BitBucket 或 Azure Repos)所裝載的存放庫。For production apps, the deployment source is usually a repository hosted by version control software such as GitHub, BitBucket, or Azure Repos. 針對開發和測試案例,部署來源可能是 您本機電腦上的專案For development and test scenarios, the deployment source may be a project on your local machine. App Service 也支援 OneDrive 和 Dropbox 資料夾 作為部署來源。App Service also supports OneDrive and Dropbox folders as deployment sources. 雖然雲端資料夾可讓您輕鬆地開始使用 App Service,但通常不建議將此來源用於企業層級的生產應用程式。While cloud folders can make it easy to get started with App Service, it is not typically recommended to use this source for enterprise-level production applications.

組建管線Build Pipeline

一旦您決定部署來源之後,下一步就是選擇組建管線。Once you decide on a deployment source, your next step is to choose a build pipeline. 組建管線會從部署來源讀取您的原始程式碼,並執行一系列的步驟 (例如編譯器代碼、縮小 HTML 和 JavaScript、執行測試,以及封裝元件) ,讓應用程式處於可執行狀態。A build pipeline reads your source code from the deployment source and executes a series of steps (such as compiling code, minifying HTML and JavaScript, running tests, and packaging components) to get the application in a runnable state. 組建管線所執行的特定命令取決於您的語言堆疊。The specific commands executed by the build pipeline depend on your language stack. 這些作業可以在組建伺服器上執行,例如 Azure Pipelines,或在本機執行。These operations can be executed on a build server such as Azure Pipelines, or executed locally.

部署機制Deployment Mechanism

部署機制是用來將您的內建應用程式放入 web 應用程式之 /home/site/wwwroot 目錄的動作。The deployment mechanism is the action used to put your built application into the /home/site/wwwroot directory of your web app. /Wwwroot 目錄是由 web 應用程式的所有實例共用的已掛接儲存位置。The /wwwroot directory is a mounted storage location shared by all instances of your web app. 當部署機制將您的應用程式放在這個目錄時,您的實例會收到同步處理新檔案的通知。When the deployment mechanism puts your application in this directory, your instances receive a notification to sync the new files. App Service 支援下列部署機制:App Service supports the following deployment mechanisms:

  • Kudu 端點: Kudu 是開放原始碼開發人員生產力工具,可在 Windows App Service 中作為個別的進程執行,並作為 Linux App Service 的第二個容器。Kudu endpoints: Kudu is the open-source developer productivity tool that runs as a separate process in Windows App Service, and as a second container in Linux App Service. Kudu 會處理持續部署,並提供用於部署的 HTTP 端點,例如 zipdeploy。Kudu handles continuous deployments and provides HTTP endpoints for deployment, such as zipdeploy.
  • FTP 和 WebDeploy:使用您的 網站或使用者認證,您可以透過 FTP 或 WebDeploy 上傳檔案。FTP and WebDeploy: Using your site or user credentials, you can upload files via FTP or WebDeploy. 這些機制不會經過 Kudu。These mechanisms do not go through Kudu.

Azure Pipelines、Jenkins 和編輯器外掛程式等部署工具會使用其中一種部署機制。Deployment tools such as Azure Pipelines, Jenkins, and editor plugins use one of these deployment mechanisms.

使用部署位置Use deployment slots

可能的話,請在部署新的生產組建時使用 部署 位置。Whenever possible, use deployment slots when deploying a new production build. 使用標準 App Service 方案層或更高時,您可以將應用程式部署至預備環境、驗證變更,以及執行冒煙測試。When using a Standard App Service Plan tier or better, you can deploy your app to a staging environment, validate your changes, and do smoke tests. 當您準備好時,您可以交換預備和生產位置。When you are ready, you can swap your staging and production slots. 交換作業會會備妥必要的背景工作角色實例,以符合您的生產環境規模,從而消除停機時間。The swap operation warms up the necessary worker instances to match your production scale, thus eliminating downtime.

持續部署程式碼Continuously deploy code

如果您的專案已指定用於測試、QA 和預備環境的分支,則應該將每個分支援續部署到預備位置。If your project has designated branches for testing, QA, and staging, then each of those branches should be continuously deployed to a staging slot. (這就是所謂的 >gitflow 設計。 ) 這可讓您的專案關係人輕鬆地評估和測試已部署的分支。(This is known as the Gitflow design.) This allows your stakeholders to easily assess and test the deployed the branch.

永遠不應針對您的生產位置啟用持續部署。Continuous deployment should never be enabled for your production slot. 相反地,您的生產分支 (通常會將主要) 部署到非生產位置。Instead, your production branch (often main) should be deployed onto a non-production slot. 當您準備好釋出基底分支時,請將它交換到生產位置。When you are ready to release the base branch, swap it into the production slot. 切換至生產環境(而不是部署到生產環境)可避免停機時間,並可讓您再次交換以復原變更。Swapping into production—instead of deploying to production—prevents downtime and allows you to roll back the changes by swapping again.

此圖顯示開發、預備和主要分支之間的流程,以及部署至的位置。

持續部署容器Continuously deploy containers

針對來自 Docker 或其他容器登錄的自訂容器,將映射部署到預備位置,並交換至生產環境以防止停機。For custom containers from Docker or other container registries, deploy the image into a staging slot and swap into production to prevent downtime. 自動化比程式碼部署更為複雜,因為您必須將映射推送至容器登錄,並更新 webapp 上的映射標記。The automation is more complex than code deployment because you must push the image to a container registry and update the image tag on the webapp.

針對您想要部署到位置的每個分支,設定自動化,以在每次認可至分支時執行下列動作。For each branch you want to deploy to a slot, set up automation to do the following on each commit to the branch.

  1. 建立並標記映射Build and tag the image. 在組建管線中,使用 git 認可識別碼、時間戳記或其他可識別的資訊來標記映射。As part of the build pipeline, tag the image with the git commit ID, timestamp, or other identifiable information. 最好不要使用預設的「最新」標記。It’s best not to use the default “latest” tag. 否則,很難追蹤目前部署的程式碼,這使得偵錯工具更難進行。Otherwise, it’s difficult to trace back what code is currently deployed, which makes debugging far more difficult.
  2. 推送標記的映射Push the tagged image. 一旦建立並標記映射,管線就會將映射推送至容器登錄。Once the image is built and tagged, the pipeline pushes the image to our container registry. 在下一個步驟中,部署位置會從容器登錄中提取標記的映射。In the next step, the deployment slot will pull the tagged image from the container registry.
  3. 使用新的映射標記更新部署 位置。Update the deployment slot with the new image tag. 更新此屬性時,網站會自動重新開機並提取新的容器映射。When this property is updated, the site will automatically restart and pull the new container image.

插槽使用量視覺效果

常見的自動化架構有下列範例。There are examples below for common automation frameworks.

使用 Azure DevOpsUse Azure DevOps

App Service 透過部署中心 內建容器的持續傳遞App Service has built-in continuous delivery for containers through the Deployment Center. Azure 入口網站中流覽至您的應用程式,然後選取 [部署] 底下的 [部署中心]。Navigate to your app in the Azure portal and select Deployment Center under Deployment. 請依照指示來選取您的儲存機制和分支。Follow the instructions to select your repository and branch. 這會設定 DevOps 組建和發行管線,以在新的認可推送至您選取的分支時,自動建立、標記及部署您的容器。This will configure a DevOps build and release pipeline to automatically build, tag, and deploy your container when new commits are pushed to your selected branch.

使用 GitHub ActionsUse GitHub Actions

您也可以 使用 GitHub Actions自動化容器部署。You can also automate your container deployment with GitHub Actions. 下列工作流程檔案將會使用認可識別碼來建立並標記容器、將其推送至容器登錄,以及使用新的映射標籤更新指定的網站位置。The workflow file below will build and tag the container with the commit ID, push it to a container registry, and update the specified site slot with the new image tag.

name: Build and deploy a container image to Azure Web Apps

on:
  push:
    branches:
    - <your-branch-name>

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@main

    -name: Authenticate using a Service Principal
      uses: azure/actions/login@v1
      with:
        creds: ${{ secrets.AZURE_SP }}

    - uses: azure/container-actions/docker-login@v1
      with:
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}

    - name: Build and push the image tagged with the git commit hash
      run: |
        docker build . -t contoso/demo:${{ github.sha }}
        docker push contoso/demo:${{ github.sha }}

    - name: Update image tag on the Azure Web App
      uses: azure/webapps-container-deploy@v1
      with:
        app-name: '<your-webapp-name>'
        slot-name: '<your-slot-name>'
        images: 'contoso/demo:${{ github.sha }}'

使用其他自動化提供者Use other automation providers

先前所列的步驟適用于其他自動化公用程式,例如 CircleCI 或 Travis CI。The steps listed earlier apply to other automation utilities such as CircleCI or Travis CI. 不過,您必須使用 Azure CLI,在最後一個步驟中使用新的映射標籤來更新部署位置。However, you need to use the Azure CLI to update the deployment slots with new image tags in the final step. 若要在您的自動化腳本中使用 Azure CLI,請使用下列命令來產生服務主體。To use the Azure CLI in your automation script, generate a Service Principal using the following command.

az ad sp create-for-rbac --name "myServicePrincipal" --role contributor \
   --scopes /subscriptions/{subscription}/resourceGroups/{resource-group} \
   --sdk-auth

在您的腳本中,使用來登入 az login --service-principal ,並提供主體的資訊。In your script, log in using az login --service-principal, providing the principal’s information. 然後,您可以使用 az webapp config container set 設定容器名稱、標記、登錄 URL 和登錄密碼。You can then use az webapp config container set to set the container name, tag, registry URL, and registry password. 以下是一些實用的連結,可讓您用來建立容器 CI 進程。Below are some helpful links for you to construct your container CI process.

Language-Specific 考慮Language-Specific Considerations

JavaJava

使用 Kudu zipdeploy/ API 部署 JAR 應用程式,並針對 WAR 應用程式使用 wardeploy/Use the Kudu zipdeploy/ API for deploying JAR applications, and wardeploy/ for WAR apps. 如果您使用 Jenkins,您可以直接在部署階段使用這些 Api。If you are using Jenkins, you can use those APIs directly in your deployment phase. 如需詳細資訊,請參閱這篇文章For more information, see this article.

節點Node

根據預設,Kudu 會執行節點應用程式 () 的組建步驟 npm installBy default, Kudu executes the build steps for your Node application (npm install). 如果您使用的是組建服務(例如 Azure DevOps),則 Kudu 組建是不必要的。If you are using a build service such as Azure DevOps, then the Kudu build is unnecessary. 若要停用 Kudu 組建,請建立應用程式設定, SCM_DO_BUILD_DURING_DEPLOYMENT 並將值設定為 falseTo disable the Kudu build, create an app setting, SCM_DO_BUILD_DURING_DEPLOYMENT, with a value of false.

.NET.NET

根據預設,Kudu 會執行 .NET 應用程式 () 的組建步驟 dotnet buildBy default, Kudu executes the build steps for your .NET application (dotnet build). 如果您使用的是組建服務(例如 Azure DevOps),則 Kudu 組建是不必要的。If you are using a build service such as Azure DevOps, then the Kudu build is unnecessary. 若要停用 Kudu 組建,請建立應用程式設定, SCM_DO_BUILD_DURING_DEPLOYMENT 並將值設定為 falseTo disable the Kudu build, create an app setting, SCM_DO_BUILD_DURING_DEPLOYMENT, with a value of false.

其他部署考慮Other Deployment Considerations

本機快取Local Cache

Azure App Service 的內容儲存在 Azure 儲存體中,並且會持久顯示為內容共用。Azure App Service content is stored on Azure Storage and is surfaced up in a durable manner as a content share. 不過,有些應用程式只需要高效能、唯讀的內容存放區,才能以高可用性執行。However, some apps just need a high-performance, read-only content store that they can run with high availability. 這些應用程式可利用 本機快取來獲益。These apps can benefit from using local cache. 不建議將本機快取用於內容管理網站,例如 WordPress。Local cache is not recommended for content management sites such as WordPress.

請一律使用本機快取搭配 部署 位置,以避免停機。Always use local cache in conjunction with deployment slots to prevent downtime. 如需搭配使用這些功能的詳細資訊,請參閱 這一節See this section for information on using these features together.

高 CPU 或記憶體High CPU or Memory

如果您的 App Service 方案使用超過90% 的可用 CPU 或記憶體,則基礎虛擬機器可能會在處理您的部署時發生問題。If your App Service Plan is using over 90% of available CPU or memory, the underlying virtual machine may have trouble processing your deployment. 發生這種情況時,請暫時擴大您的實例計數,以執行部署。When this happens, temporarily scale up your instance count to perform the deployment. 部署完成後,您可以將實例計數傳回先前的值。Once the deployment has finished, you can return the instance count to its previous value.

如需最佳做法的詳細資訊,請造訪 App Service 診斷 ,以找出您的資源專屬的可行最佳作法。For more information on best practices, visit App Service Diagnostics to find out actionable best practices specific to your resource.

  • Azure 入口網站中流覽至您的 Web 應用程式。Navigate to your Web App in the Azure portal.
  • 在左側導覽中,按一下 [ 診斷並解決問題 ],即可開啟 App Service 診斷。Click on Diagnose and solve problems in the left navigation, which opens App Service Diagnostics.
  • 選擇 最佳作法 首頁圖格。Choose Best Practices homepage tile.
  • 按一下 [ 可用性] 的最佳作法 & 效能最佳做法,以最佳 設定來查看應用程式目前的狀態,以瞭解這些最佳做法。Click Best Practices for Availability & Performance or Best Practices for Optimal Configuration to view the current state of your app in regards to these best practices.

您也可以使用此連結來直接開啟資源的 App Service 診斷: https://ms.portal.azure.com/?websitesextension_ext=asd.featurePath%3Ddetectors%2FParentAvailabilityAndPerformance#@microsoft.onmicrosoft.com/resource/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/troubleshootYou can also use this link to directly open App Service Diagnostics for your resource: https://ms.portal.azure.com/?websitesextension_ext=asd.featurePath%3Ddetectors%2FParentAvailabilityAndPerformance#@microsoft.onmicrosoft.com/resource/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/troubleshoot.