教程:提交源代码时,在云中自动化容器映像生成Tutorial: Automate container image builds in the cloud when you commit source code

除了快速任务之外,ACR 任务还支持在将源代码提交到 Git 存储库时自动在云中生成 Docker 容器映像。In addition to a quick task, ACR Tasks supports automated Docker container image builds in the cloud when you commit source code to a Git repository. ACR 任务支持的 Git 上下文包括公共或专用 GitHub 或 Azure Repos。Supported Git contexts for ACR Tasks include public or private GitHub or Azure repos.


目前,ACR 任务不支持 GitHub Enterprise 存储库中的提交或拉取请求触发器。Currently, ACR Tasks doesn't support commit or pull request triggers in GitHub Enterprise repos.

在本教程中,在你将源代码提交到 Git 存储库时,ACR 任务会生成并推送在 Dockerfile 中指定的单一容器映像。In this tutorial, your ACR task builds and pushes a single container image specified in a Dockerfile when you commit source code to a Git repo. 要创建多步骤任务并让其使用 YAML 文件来定义相关步骤,以便在提交代码时生成、推送和测试(可选)多个容器,请参阅教程:提交源代码时在云中运行多步骤容器工作流To create a multi-step task that uses a YAML file to define steps to build, push, and optionally test multiple containers on code commit, see Tutorial: Run a multi-step container workflow in the cloud when you commit source code. 有关 ACR 任务的概述,请参阅使用 ACR 任务自动执行 OS 和框架修补For an overview of ACR Tasks, see Automate OS and framework patching with ACR Tasks

本教程的内容:In this tutorial:

  • 创建任务Create a task
  • 测试任务Test the task
  • 查看任务状态View task status
  • 使用代码提交触发任务Trigger the task with a code commit

本教程假设你已完成前面教程中的任务。This tutorial assumes you've already completed the steps in the previous tutorial. 如果尚未完成,请先完成前面教程先决条件部分中的步骤,再继续操作。If you haven't already done so, complete the steps in the Prerequisites section of the previous tutorial before proceeding.


在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

若要在本地使用 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.


获取示例代码Get sample code

本教程假定你已对示例存储库创建分支和克隆。This tutorial assumes you have forked and cloned the sample repository.

容器注册表Container registry

Azure 订阅中必须具有 Azure 容器注册表才能完成此教程。You must have an Azure container registry in your Azure subscription to complete this tutorial. 如果需要注册表,请参阅快速入门:使用 Azure CLI 创建容器注册表If you need a registry, see the Quickstart: Create a container registry using the Azure CLI.

创建 GitHub 个人访问令牌Create a GitHub personal access token

若要在向 Git 存储库提交内容时触发任务,ACR 任务需要用于访问存储库的个人访问令牌 (PAT)。To trigger a task on a commit to a Git repository, ACR Tasks need a personal access token (PAT) to access the repository. 如果还没有 PAT,请按照以下步骤在 GitHub 中生成一个:If you do not already have a PAT, follow these steps to generate one in GitHub:

  1. 导航到 GitHub 上的 PAT 创建页面 https://github.com/settings/tokens/newNavigate to the PAT creation page on GitHub at https://github.com/settings/tokens/new

  2. 输入令牌的简短说明,例如“ACR 任务演示”Enter a short description for the token, for example, "ACR Tasks Demo"

  3. 选择 ACR 的作用域以访问存储库。Select scopes for ACR to access the repo. 要像本教程一样访问公共存储库,请在“存储库”下方,启用“存储库:状态”和“public_repo” To access a public repo as in this tutorial, under repo, enable repo:status and public_repo

    GitHub 中个人访问令牌生成页面的屏幕截图


    若要生成 PAT 以访问专用 存储库,请选择完全存储库控制的作用域。To generate a PAT to access a private repo, select the scope for full repo control.

  4. 选择“生成令牌”按钮(可能会要求你确认密码) Select the Generate token button (you may be asked to confirm your password)

  5. 将生成的令牌复制并保存到安全位置(在后续部分定义任务时会使用此令牌)Copy and save the generated token in a secure location (you use this token when you define a task in the following section)

    GitHub 中已生成的个人访问令牌的屏幕截图

创建生成任务Create the build task

现已完成启用 ACR 任务以读取提交状态和在存储库中创建 Webhook 所需的步骤,接下来可以创建任务,以便在向存储库提交内容时触发容器映像生成。Now that you've completed the steps required to enable ACR Tasks to read commit status and create webhooks in a repository, you can create a task that triggers a container image build on commits to the repo.

首先,使用适用于环境的值填充这些 shell 环境变量。First, populate these shell environment variables with values appropriate for your environment. 此步骤并非必须执行的步骤,但它能让在此教程中执行多个 Azure CLI 命令更容易。This step isn't strictly required, but makes executing the multiline Azure CLI commands in this tutorial a bit easier. 如果未填充这些环境变量,则每当示例命令中出现每个值,都必须手动替换该值。If you don't populate these environment variables, you must manually replace each value wherever it appears in the example commands.

ACR_NAME=<registry-name>        # The name of your Azure container registry
GIT_USER=<github-username>      # Your GitHub user account name
GIT_PAT=<personal-access-token> # The PAT you generated in the previous section

现在,请执行以下 az acr task create 命令创建该任务:Now, create the task by executing the following az acr task create command:

az acr task create \
    --registry $ACR_NAME \
    --name taskhelloworld \
    --image helloworld:{{.Run.ID}} \
    --context https://github.com/$GIT_USER/acr-build-helloworld-node.git \
    --file Dockerfile \
    --git-access-token $GIT_PAT


在本地 PowerShell 环境中运行上述 CLI cmdlet 时,可能会在控制台上显示以下错误消息:az acr task create: 'utputformat' is not a valid value for '--output'. See 'az acr task create --help'.When you run the above CLI cmdlet on your local PowerShell environment , Maybe there are one following error message showed on your console: az acr task create: 'utputformat' is not a valid value for '--output'. See 'az acr task create --help'.

请替换以下项,然后再次运行 cmdlet。Please replace the following item and run your cmdlet again.

  • --image helloworld:{{.Run.ID}} 替换为 --image 'helloworld:{{.Run.ID}}'Replace --image helloworld:{{.Run.ID}} with --image 'helloworld:{{.Run.ID}}'


如果以前在预览期使用 az acr build-task 创建了任务,则需要使用 az acr task 命令重新创建这些任务。If you previously created tasks during the preview with the az acr build-task command, those tasks need to be re-created using the az acr task command.

此任务指定向 --context 指定的主分支存储库提交代码时,ACR 任务将根据该分支中的代码生成容器映像 。This task specifies that any time code is committed to the master branch in the repository specified by --context, ACR Tasks will build the container image from the code in that branch. 将使用存储库根目录中由 --file 指定的 Dockerfile 来生成映像。The Dockerfile specified by --file from the repository root is used to build the image. --image 参数为映像标记的版本部分指定参数化的 {{.Run.ID}} 值,确保生成映像与特定生成关联且被唯一标记。The --image argument specifies a parameterized value of {{.Run.ID}} for the version portion of the image's tag, ensuring the built image correlates to a specific build, and is tagged uniquely.

成功的 az acr task create 命令的输出应如下所示:Output from a successful az acr task create command is similar to the following:

  "agentConfiguration": {
    "cpu": 2
  "creationDate": "2018-09-14T22:42:32.972298+00:00",
  "id": "/subscriptions/<Subscription ID>/resourceGroups/myregistry/providers/Microsoft.ContainerRegistry/registries/myregistry/tasks/taskhelloworld",
  "location": "chinanorth",
  "name": "taskhelloworld",
  "platform": {
    "architecture": "amd64",
    "os": "Linux",
    "variant": null
  "provisioningState": "Succeeded",
  "resourceGroup": "myregistry",
  "status": "Enabled",
  "step": {
    "arguments": [],
    "baseImageDependencies": null,
    "contextPath": "https://github.com/gituser/acr-build-helloworld-node",
    "dockerFilePath": "Dockerfile",
    "imageNames": [
    "isPushEnabled": true,
    "noCache": false,
    "type": "Docker"
  "tags": null,
  "timeout": 3600,
  "trigger": {
    "baseImageTrigger": {
      "baseImageTriggerType": "Runtime",
      "name": "defaultBaseimageTriggerName",
      "status": "Enabled"
    "sourceTriggers": [
        "name": "defaultSourceTriggerName",
        "sourceRepository": {
          "branch": "master",
          "repositoryUrl": "https://github.com/gituser/acr-build-helloworld-node",
          "sourceControlAuthProperties": null,
          "sourceControlType": "GitHub"
        "sourceTriggerEvents": [
        "status": "Enabled"
  "type": "Microsoft.ContainerRegistry/registries/tasks"

测试生成任务Test the build task

现已创建一个用于定义生成的任务。You now have a task that defines your build. 若要测试生成管道,请执行 az acr task run 命令手动触发生成:To test the build pipeline, trigger a build manually by executing the az acr task run command:

az acr task run --registry $ACR_NAME --name taskhelloworld

默认情况下,执行此命令时,az acr task run 命令会将日志流式传输到控制台。By default, the az acr task run command streams the log output to your console when you execute the command.

2018/09/17 22:51:00 Using acb_vol_9ee1f28c-4fd4-43c8-a651-f0ed027bbf0e as the home volume
2018/09/17 22:51:00 Setting up Docker configuration...
2018/09/17 22:51:02 Successfully set up Docker configuration
2018/09/17 22:51:02 Logging in to registry: myregistry.azurecr.cn
2018/09/17 22:51:03 Successfully logged in
2018/09/17 22:51:03 Executing step: build
2018/09/17 22:51:03 Obtaining source code and scanning for dependencies...
2018/09/17 22:51:05 Successfully obtained source code and scanned for dependencies
Sending build context to Docker daemon  23.04kB
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
 ---> 5f574fcf5816
Step 3/5 : RUN cd /src && npm install
 ---> Running in b1bca3b5f4fc
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.078s
Removing intermediate container b1bca3b5f4fc
 ---> 44457db20dac
Step 4/5 : EXPOSE 80
 ---> Running in 9e6f63ec612f
Removing intermediate container 9e6f63ec612f
 ---> 74c3e8ea0d98
Step 5/5 : CMD ["node", "/src/server.js"]
 ---> Running in 7382eea2a56a
Removing intermediate container 7382eea2a56a
 ---> e33cd684027b
Successfully built e33cd684027b
Successfully tagged myregistry.azurecr.cn/helloworld:da2
2018/09/17 22:51:11 Executing step: push
2018/09/17 22:51:11 Pushing image: myregistry.azurecr.cn/helloworld:da2, attempt 1
The push refers to repository [myregistry.azurecr.cn/helloworld]
4a853682c993: Preparing
4a853682c993: Pushed
da2: digest: sha256:c24e62fd848544a5a87f06ea60109dbef9624d03b1124bfe03e1d2c11fd62419 size: 1366
2018/09/17 22:51:21 Successfully pushed image: myregistry.azurecr.cn/helloworld:da2
2018/09/17 22:51:21 Step id: build marked as successful (elapsed time in seconds: 7.198937)
2018/09/17 22:51:21 Populating digests for step id: build...
2018/09/17 22:51:22 Successfully populated digests for step id: build
2018/09/17 22:51:22 Step id: push marked as successful (elapsed time in seconds: 10.180456)
The following dependencies were found:
- image:
    registry: myregistry.azurecr.cn
    repository: helloworld
    tag: da2
    digest: sha256:c24e62fd848544a5a87f06ea60109dbef9624d03b1124bfe03e1d2c11fd62419
    registry: registry.hub.docker.com
    repository: library/node
    tag: 9-alpine
    digest: sha256:8dafc0968fb4d62834d9b826d85a8feecc69bd72cd51723c62c7db67c6dec6fa
    git-head-revision: 68cdf2a37cdae0873b8e2f1c4d80ca60541029bf

Run ID: da2 was successful after 27s

使用命令触发生成Trigger a build with a commit

通过手动运行任务对其进行测试后,可通过更改源代码手动触发该任务。Now that you've tested the task by manually running it, trigger it automatically with a source code change.

首先,确保你位于包含存储库的本地克隆的目录中:First, ensure you're in the directory containing your local clone of the repository:

cd acr-build-helloworld-node

接下来执行以下命令,创建新文件,并将其提交和推送给你在 GitHub 上的存储库分支:Next, execute the following commands to create, commit, and push a new file to your fork of the repo on GitHub:

echo "Hello World!" > hello.txt
git add hello.txt
git commit -m "Testing ACR Tasks"
git push origin master

执行 git push 命令时可能需要提供 GitHub 凭据。You may be asked to provide your GitHub credentials when you execute the git push command. 提供 GitHub 用户名并输入之前为密码创建的个人访问令牌 (PAT)。Provide your GitHub username, and enter the personal access token (PAT) that you created earlier for the password.

Username for 'https://github.com': <github-username>
Password for 'https://githubuser@github.com': <personal-access-token>

将提交推送至存储库后,ACR 任务所创建的 Webhook 便会在 Azure 容器注册表中触发并启动一个生成。Once you've pushed a commit to your repository, the webhook created by ACR Tasks fires and kicks off a build in Azure Container Registry. 显示当前正在运行的任务的日志,以验证和监视生成进度:Display the logs for the currently running task to verify and monitor the build progress:

az acr task logs --registry $ACR_NAME

输出结果类似于以下内容,显示当前执行(或最近执行)的任务:Output is similar to the following, showing the currently executing (or last-executed) task:

Showing logs of the last created run.
Run ID: da4


Run ID: da4 was successful after 38s

生成列表List builds

若要查看 ACR 任务对注册表完成的任务运行列表,请运行 az acr task list-runs 命令:To see a list of the task runs that ACR Tasks has completed for your registry, run the az acr task list-runs command:

az acr task list-runs --registry $ACR_NAME --output table

该命令产生的输出应如下所示。Output from the command should appear similar to the following. 将显示 ACR 任务已执行的运行,并在最近执行的任务的 TRIGGER 列中显示“Git Commit”:The runs that ACR Tasks has executed are displayed, and "Git Commit" appears in the TRIGGER column for the most recent task:

RUN ID    TASK             PLATFORM    STATUS     TRIGGER     STARTED               DURATION
--------  --------------  ----------  ---------  ----------  --------------------  ----------
da4       taskhelloworld  Linux       Succeeded  Git Commit  2018-09-17T23:03:45Z  00:00:44
da3       taskhelloworld  Linux       Succeeded  Manual      2018-09-17T22:55:35Z  00:00:35
da2       taskhelloworld  Linux       Succeeded  Manual      2018-09-17T22:50:59Z  00:00:32
da1                       Linux       Succeeded  Manual      2018-09-17T22:29:59Z  00:00:57

后续步骤Next steps

在本教程中,我们已了解如何在向 Git 存储库提交源代码时,使用一个任务在 Azure 中自动触发容器映像生成。In this tutorial, you learned how to use a task to automatically trigger container image builds in Azure when you commit source code to a Git repository. 请转到下一教程来了解如何创建任务,用于在更新容器映像的基础映像时触发生成。Move on to the next tutorial to learn how to create tasks that trigger builds when a container image's base image is updated.