教學課程:使用 Azure Container Registry 工作在雲端中建置和部署容器映像Tutorial: Build and deploy container images in the cloud with Azure Container Registry Tasks

ACR 工作是 Azure Container Registry 內的一組功能,可在 Azure 中提供精簡而有效率的 Docker 容器映像組建。ACR Tasks is a suite of features within Azure Container Registry that provides streamlined and efficient Docker container image builds in Azure. 在本文中,您將了解如何使用 ACR 工作的快速工作功能。In this article, you learn how to use the quick task feature of ACR Tasks.

「內部迴圈」開發週期是在認可至原始檔控制之前撰寫程式碼、建置和測試應用程式的反覆程序。The "inner-loop" development cycle is the iterative process of writing code, building, and testing your application before committing to source control. 快速工作可將您的內部迴圈延伸至雲端,讓您能夠進行建置成功驗證,並將成功建置的映像自動推送至容器登錄。A quick task extends your inner-loop to the cloud, providing you with build success validation and automatic pushing of successfully built images to your container registry. 您的映像依原生狀態會建置在雲端中接近您的登錄之處,因此有助於快速部署。Your images are built natively in the cloud, close to your registry, enabling faster deployment.

您的所有 Dockerfile 專業知識都可直接轉移至 ACR 工作。All your Dockerfile expertise is directly transferrable to ACR Tasks. 您不需要變更 Dockerfile,而是需要變更您所執行的命令,即可使用 ACR 工作在雲端中進行建置。You don't have to change your Dockerfiles to build in the cloud with ACR Tasks, just the command you run.

本教學課程是一個系列的第一部分:In this tutorial, part one of a series:

  • 取得範例應用程式的原始程式碼Get the sample application source code
  • 在 Azure 中建置容器映像Build a container image in Azure
  • 將容器部署至 Azure 容器執行個體Deploy a container to Azure Container Instances

在後續的教學課程中,您將了解如何將 ACR 工作工作用於程式碼認可和基礎映像更新的自動化容器映像建置。In subsequent tutorials, you learn to use ACR Tasks for automated container image builds on code commit and base image update. ACR 工作也可執行多步驟工作,使用 YAML 檔案來定義相關步驟,以建置、推送並選擇性地測試多個容器。ACR Tasks can also run multi-step tasks, using a YAML file to define steps to build, push, and optionally test multiple containers.

開啟 Azure Cloud ShellOpen Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,並且會透過瀏覽器來使用。Azure Cloud Shell is an interactive shell environment hosted in Azure and used through your browse. Azure Cloud Shell 可讓您使用 bashPowerShell 殼層來執行各種可與 Azure 服務搭配運作的工具。Azure Cloud Shell allows you to use either bash or PowerShell shells to run a variety of tools to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文的內容,而不必在本機環境上安裝任何工具。Azure Cloud Shell comes pre-installed with the commands to allow you to run the content of this article without having to install anything on your local environment.

若要在 Azure Cloud Shell 上執行本文所包含的任何程式碼,請開啟 Cloud Shell 工作階段、使用某個程式碼區塊上的 [複製] 按鈕來複製程式碼,然後使用 Ctrl+Shift+V (在 Windows 和 Linux 上) 或 Cmd+Shift+V (在 macOS 上) 將程式碼貼到 Cloud Shell 工作階段中。To run any code contained in this article on Azure Cloud Shell, open a Cloud Shell session, use the Copy button on a code block to copy the code, and paste it into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS. 貼上的文字不會自動執行,因此請按 Enter 來執行程式碼。Pasted text is not automatically executed, so press Enter to run code.

您可以使用下列方式來啟動 Azure Cloud Shell:You can launch Azure Cloud Shell with:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 這__不會__自動將文字複製到 Cloud Shell。This doesn't automatically copy text to Cloud Shell. Azure Cloud Shell 的試試看範例
在瀏覽器中開啟 Azure Cloud ShellOpen Azure Cloud Shell in your browser. <a href="https://shell.azure.com" title="啟動 Azure Cloud Shell
選取 Azure 入口網站右上角功能表上的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

如果您想要在本機使用 Azure CLI,您必須安裝 Azure CLI 2.0.46 版或更新版本,並使用 az login 登入。If you'd like to use the Azure CLI locally, you must have Azure CLI version 2.0.46 or later installed and logged in with az login. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級 CLI,請參閱安裝 Azure CLIIf you need to install or upgrade the CLI, see Install Azure CLI.

必要條件Prerequisites

GitHub 帳戶GitHub account

https://github.com 上建立帳戶 (如果您還沒有帳戶)。Create an account on https://github.com if you don't already have one. 本教學課程系列會使用 GitHub 存放庫來示範使用 ACR 工作的自動化映像建置。This tutorial series uses a GitHub repository to demonstrate automated image builds in ACR Tasks.

派生範例存放庫Fork sample repository

接著,請使用 GitHub UI 將範例存放庫派生到您的 GitHub 帳戶中。Next, use the GitHub UI to fork the sample repository into your GitHub account. 在本教學課程中,您會從存放庫中的來源建置容器映像,而在下一個教學課程中,您會將認可推送至該存放庫的分支,以開始進行自動化工作。In this tutorial, you build a container image from the source in the repo, and in the next tutorial, you push a commit to your fork of the repo to kick off an automated task.

派生此存放庫: https://github.com/Azure-Samples/acr-build-helloworld-nodeFork this repository: https://github.com/Azure-Samples/acr-build-helloworld-node

GitHub 中的 [分支] 按鈕 (醒目提示) 的螢幕擷取畫面

複製您的分支Clone your fork

在您派生存放庫後,請複製您的分支,並進入包含本機複本的目錄。Once you've forked the repo, clone your fork and enter the directory containing your local clone.

使用 git 複製存放庫,並將 <your-github-username> 取代為您的 GitHub 使用者名稱:Clone the repo with git, replace <your-github-username> with your GitHub username:

git clone https://github.com/<your-github-username>/acr-build-helloworld-node

進入包含原始程式碼的目錄:Enter the directory containing the source code:

cd acr-build-helloworld-node

Bash 殼層Bash shell

本教學課程系列中的命令採用 Bash 殼層適用的格式。The commands in this tutorial series are formatted for the Bash shell. 如果您想要使用 PowerShell、命令提示字元或其他殼層,您可能需要據以調整行接續符號和環境變數格式。If you prefer to use PowerShell, Command Prompt, or another shell, you may need to adjust the line continuation and environment variable format accordingly.

使用 ACR 工作在 Azure 中進行建置Build in Azure with ACR Tasks

現在,您已將原始程式碼提取至電腦,接著請依照下列步驟建立容器登錄,並使用 ACR 工作來建置容器映像。Now that you've pulled the source code down to your machine, follow these steps to create a container registry and build the container image with ACR Tasks.

為了方便執行範例命令,在這一系列的教學課程中,將會使用殼層環境變數。To make executing the sample commands easier, the tutorials in this series use shell environment variables. 請執行下列命令以設定 ACR_NAME 變數。Execute the following command to set the ACR_NAME variable. 請將 <registry-name> 取代為新容器登錄的唯一名稱。Replace <registry-name> with a unique name for your new container registry. 登錄名稱在 Azure 內必須是唯一的,且包含 5-50 個英數字元。The registry name must be unique within Azure, and contain 5-50 alphanumeric characters. 您在本教學課程中建立的其他資源將以此名稱為基礎,因此,您只需要修改第一個變數,即此變數。The other resources you create in the tutorial are based on this name, so you should need to modify only this first variable.

ACR_NAME=<registry-name>

在填入容器登錄環境變數後,您現在應該可以複製並貼上教學課程中的其餘命令,而不需編輯的任何值。With the container registry environment variable populated, you should now be able to copy and paste the remainder of the commands in the tutorial without editing any values. 請執行下列命令,以建立資源群組和容器登錄:Execute the following commands to create a resource group and container registry:

RES_GROUP=$ACR_NAME # Resource Group name

az group create --resource-group $RES_GROUP --location eastus
az acr create --resource-group $RES_GROUP --name $ACR_NAME --sku Standard --location eastus

現在您已具有登錄,接著請使用 ACR 工作,從範例程式碼建置容器映像。Now that you have a registry, use ACR Tasks to build a container image from the sample code. 請執行 az acr build 命令以執行快速工作Execute the az acr build command to perform a quick task:

az acr build --registry $ACR_NAME --image helloacrtasks:v1 .

az acr build 命令的輸出如下。Output from the az acr build command is similar to the following. 您可以檢視上傳至 Azure 的原始程式碼 (「內容」),以及 ACR 工作在雲端中執行之 docker build 作業的詳細資料。You can see the upload of the source code (the "context") to Azure, and the details of the docker build operation that the ACR task runs in the cloud. 由於 ACR 工作會使用 docker build 建置您的映像,因此您無須對 Dockerfile 進行任何變更,即可立即開始使用 ACR 工作。Because ACR tasks use docker build to build your images, no changes to your Dockerfiles are required to start using ACR Tasks immediately.

$ az acr build --registry $ACR_NAME --image helloacrtasks:v1 .
Packing source code into tar file to upload...
Sending build context (4.813 KiB) to ACR...
Queued a build with build ID: da1
Waiting for build agent...
2018/08/22 18:31:42 Using acb_vol_01185991-be5f-42f0-9403-a36bb997ff35 as the home volume
2018/08/22 18:31:42 Setting up Docker configuration...
2018/08/22 18:31:43 Successfully set up Docker configuration
2018/08/22 18:31:43 Logging in to registry: myregistry.azurecr.io
2018/08/22 18:31:55 Successfully logged in
Sending build context to Docker daemon   21.5kB
Step 1/5 : FROM node:9-alpine
9-alpine: Pulling from library/node
Digest: sha256:8dafc0968fb4d62834d9b826d85a8feecc69bd72cd51723c62c7db67c6dec6fa
Status: Image is up to date for node:9-alpine
 ---> a56170f59699
Step 2/5 : COPY . /src
 ---> 88087d7e709a
Step 3/5 : RUN cd /src && npm install
 ---> Running in e80e1263ce9a
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN helloworld@1.0.0 No repository field.

up to date in 0.1s
Removing intermediate container e80e1263ce9a
 ---> 26aac291c02e
Step 4/5 : EXPOSE 80
 ---> Running in 318fb4c124ac
Removing intermediate container 318fb4c124ac
 ---> 113e157d0d5a
Step 5/5 : CMD ["node", "/src/server.js"]
 ---> Running in fe7027a11787
Removing intermediate container fe7027a11787
 ---> 20a27b90eb29
Successfully built 20a27b90eb29
Successfully tagged myregistry.azurecr.io/helloacrtasks:v1
2018/08/22 18:32:11 Pushing image: myregistry.azurecr.io/helloacrtasks:v1, attempt 1
The push refers to repository [myregistry.azurecr.io/helloacrtasks]
6428a18b7034: Preparing
c44b9827df52: Preparing
172ed8ca5e43: Preparing
8c9992f4e5dd: Preparing
8dfad2055603: Preparing
c44b9827df52: Pushed
172ed8ca5e43: Pushed
8dfad2055603: Pushed
6428a18b7034: Pushed
8c9992f4e5dd: Pushed
v1: digest: sha256:b038dcaa72b2889f56deaff7fa675f58c7c666041584f706c783a3958c4ac8d1 size: 1366
2018/08/22 18:32:43 Successfully pushed image: myregistry.azurecr.io/helloacrtasks:v1
2018/08/22 18:32:43 Step ID acb_step_0 marked as successful (elapsed time in seconds: 15.648945)
The following dependencies were found:
- image:
    registry: myregistry.azurecr.io
    repository: helloacrtasks
    tag: v1
    digest: sha256:b038dcaa72b2889f56deaff7fa675f58c7c666041584f706c783a3958c4ac8d1
  runtime-dependency:
    registry: registry.hub.docker.com
    repository: library/node
    tag: 9-alpine
    digest: sha256:8dafc0968fb4d62834d9b826d85a8feecc69bd72cd51723c62c7db67c6dec6fa
  git: {}

Run ID: da1 was successful after 1m9.970148252s

在輸出結尾附近,ACR 工作會顯示它為您的映像探索到的相依性。Near the end of the output, ACR Tasks displays the dependencies it's discovered for your image. 這可讓 ACR 工作在基底映像更新時自動執行映像建置,例如,在使用作業系統或架構修補程式更新基底映像時。This enables ACR Tasks to automate image builds on base image updates, such as when a base image is updated with OS or framework patches. 您將在本教學課程系列後續的內容中了解 ACR 工作對基底映像更新的支援。You learn about ACR Tasks support for base image updates later in this tutorial series.

部署至 Azure 容器執行個體Deploy to Azure Container Instances

ACR 工作依預設會自動將已建置的映像順利推送至登錄,讓您能夠立即從登錄加以部署。ACR tasks automatically push successfully built images to your registry by default, allowing you to deploy them from your registry immediately.

在本節中,您會建立 Azure Key Vault 和服務主體,然後使用服務主體的認證將容器部署至 Azure 容器執行個體 (ACI)。In this section, you create an Azure Key Vault and service principal, then deploy the container to Azure Container Instances (ACI) using the service principal's credentials.

設定登錄驗證Configure registry authentication

所有生產案例均應使用服務主體來存取 Azure 容器登錄。All production scenarios should use service principals to access an Azure container registry. 服務主體可讓您針對容器映像提供角色型存取控制。Service principals allow you to provide role-based access control to your container images. 例如,您可以設定服務主體具有僅限提取登錄的存取權。For example, you can configure a service principal with pull-only access to a registry.

建立金鑰保存庫Create a key vault

如果您在 Azure Key Vault 中還沒有保存庫,使用 Azure CLI 以下列命令建立一個。If you don't already have a vault in Azure Key Vault, create one with the Azure CLI using the following commands.

AKV_NAME=$ACR_NAME-vault

az keyvault create --resource-group $RES_GROUP --name $AKV_NAME

建立服務主體並儲存認證Create a service principal and store credentials

您現在需要建立服務主體,並將它的認證儲存在金鑰保存庫中。You now need to create a service principal and store its credentials in your key vault.

使用 az ad sp create-for-rbac 命令建立服務主體,並使用 az keyvault secret set 將服務主體的密碼儲存在保存庫中:Use the az ad sp create-for-rbac command to create the service principal, and az keyvault secret set to store the service principal's password in the vault:

# Create service principal, store its password in AKV (the registry *password*)
az keyvault secret set \
  --vault-name $AKV_NAME \
  --name $ACR_NAME-pull-pwd \
  --value $(az ad sp create-for-rbac \
                --name $ACR_NAME-pull \
                --scopes $(az acr show --name $ACR_NAME --query id --output tsv) \
                --role acrpull \
                --query password \
                --output tsv)

在前面的命令中,--role 引數設定服務主體具有 acrpull 角色,授與主體僅限提取登錄的存取權。The --role argument in the preceding command configures the service principal with the acrpull role, which grants it pull-only access to the registry. 若要同時授與發送和提取存取權,請將 --role 引數變更為 acrpush。To grant both push and pull access, change the --role argument to acrpush.

接下來,在保存庫中儲存服務主體的 appId,也就是您傳遞給 Azure Container Registry 進行驗證的使用者名稱Next, store the service principal's appId in the vault, which is the username you pass to Azure Container Registry for authentication:

# Store service principal ID in AKV (the registry *username*)
az keyvault secret set \
    --vault-name $AKV_NAME \
    --name $ACR_NAME-pull-usr \
    --value $(az ad sp show --id http://$ACR_NAME-pull --query appId --output tsv)

您已建立 Azure Key Vault,並在其中儲存兩個祕密:You've created an Azure Key Vault and stored two secrets in it:

  • $ACR_NAME-pull-usr:服務主體識別碼,用來作為容器登錄使用者名稱$ACR_NAME-pull-usr: The service principal ID, for use as the container registry username.
  • $ACR_NAME-pull-pwd:服務主體密碼,用來作為容器登錄密碼$ACR_NAME-pull-pwd: The service principal password, for use as the container registry password.

現在,當您或應用程式和服務從登錄提取映像時,您可以依名稱參考這些祕密。You can now reference these secrets by name when you or your applications and services pull images from the registry.

使用 Azure CLI 部署容器Deploy a container with Azure CLI

現在,服務主體認證已儲存 Azure Key Vault 密碼,應用程式和服務可以使用它們來存取您的私人登錄。Now that the service principal credentials are stored as Azure Key Vault secrets, your applications and services can use them to access your private registry.

執行下列 az container create 命令來部署容器執行個體。Execute the following az container create command to deploy a container instance. 此命令會使用儲存在 Azure Key Vault 中的服務主體認證向您的容器登錄進行驗證。The command uses the service principal's credentials stored in Azure Key Vault to authenticate to your container registry.

az container create \
    --resource-group $RES_GROUP \
    --name acr-tasks \
    --image $ACR_NAME.azurecr.io/helloacrtasks:v1 \
    --registry-login-server $ACR_NAME.azurecr.io \
    --registry-username $(az keyvault secret show --vault-name $AKV_NAME --name $ACR_NAME-pull-usr --query value -o tsv) \
    --registry-password $(az keyvault secret show --vault-name $AKV_NAME --name $ACR_NAME-pull-pwd --query value -o tsv) \
    --dns-name-label acr-tasks-$ACR_NAME \
    --query "{FQDN:ipAddress.fqdn}" \
    --output table

--dns-name-label 值在 Azure 內必須是唯一的,因此,上述命令會將您容器登錄的名稱附加至容器的 DNS 名稱標籤。The --dns-name-label value must be unique within Azure, so the preceding command appends your container registry's name to the container's DNS name label. 命令的輸出會顯示容器的完整網域名稱 (FQDN),例如:The output from the command displays the container's fully qualified domain name (FQDN), for example:

$ az container create \
>     --resource-group $RES_GROUP \
>     --name acr-tasks \
>     --image $ACR_NAME.azurecr.io/helloacrtasks:v1 \
>     --registry-login-server $ACR_NAME.azurecr.io \
>     --registry-username $(az keyvault secret show --vault-name $AKV_NAME --name $ACR_NAME-pull-usr --query value -o tsv) \
>     --registry-password $(az keyvault secret show --vault-name $AKV_NAME --name $ACR_NAME-pull-pwd --query value -o tsv) \
>     --dns-name-label acr-tasks-$ACR_NAME \
>     --query "{FQDN:ipAddress.fqdn}" \
>     --output table
FQDN
----------------------------------------------
acr-tasks-myregistry.eastus.azurecontainer.io

請記下容器的 FQDN,您將下一節用到。Take note of the container's FQDN, you'll use it in the next section.

驗證部署Verify the deployment

若要查看容器的啟動程序,請使用 az container attach 命令:To watch the startup process of the container, use the az container attach command:

az container attach --resource-group $RES_GROUP --name acr-tasks

az container attach 輸出會先顯示容器在提取映像和啟動時的狀態,然後將本機主控台的 STDOUT 和 STDERR 繫結至容器的 STDOUT 和 STDERR。The az container attach output first displays the container's status as it pulls the image and starts, then binds your local console's STDOUT and STDERR to that of the container's.

$ az container attach --resource-group $RES_GROUP --name acr-tasks
Container 'acr-tasks' is in state 'Running'...
(count: 1) (last timestamp: 2018-08-22 18:39:10+00:00) pulling image "myregistry.azurecr.io/helloacrtasks:v1"
(count: 1) (last timestamp: 2018-08-22 18:39:15+00:00) Successfully pulled image "myregistry.azurecr.io/helloacrtasks:v1"
(count: 1) (last timestamp: 2018-08-22 18:39:17+00:00) Created container
(count: 1) (last timestamp: 2018-08-22 18:39:17+00:00) Started container

Start streaming logs:
Server running at http://localhost:80

Server running at http://localhost:80 出現時,請瀏覽至容器在您瀏覽器中的 FQDN,以查看執行中的應用程式。When Server running at http://localhost:80 appears, navigate to the container's FQDN in your browser to see the running application. FQDN 應已顯示在您在上一節中執行的 az container create 命令所產生的輸出中。The FQDN should have been displayed in the output of the az container create command you executed in the previous section.

呈現在瀏覽器中的範例應用程式的螢幕擷取畫面

若要從容器將您的主控台中斷連結,請點按 Control+CTo detach your console from the container, hit Control+C.

清除資源Clean up resources

使用 az container delete 命令停止容器執行個體:Stop the container instance with the az container delete command:

az container delete --resource-group $RES_GROUP --name acr-tasks

若要移除您在本教學課程中建立的所有資源 (包括容器登錄、金鑰保存庫和服務主體),請發出下列命令。To remove all resources you've created in this tutorial, including the container registry, key vault, and service principal, issue the following commands. 不過,本系列的下一個教學課程將會使用這些資源,因此如果您要直接移至下一個教學課程,可以選擇加以保留。These resources are used in the next tutorial in the series, however, so you might want to keep them if you move on directly to the next tutorial.

az group delete --resource-group $RES_GROUP
az ad sp delete --id http://$ACR_NAME-pull

後續步驟Next steps

現在,您已使用快速工作測試您的內部迴圈,接下來請設定您將原始程式碼認可至 Git 存放庫時用來觸發容器映像建置的建置工作Now that you've tested your inner loop with a quick task, configure a build task to trigger container images builds when you commit source code to a Git repository: