Azure Devops 使用部署任务将 Docker 镜像部署到 ACR

41次阅读
没有评论

问题描述

在使用 Azure Devops 管道时,希望通过管道将 Docker 镜像部署到 Azure 容器注册表(Azure Container Registry)。用户已经编写了一个脚本,可以成功运行,但是他想使用部署任务来在不同的环境中运行管道。然而,当他将脚本更新为部署任务后,运行管道时出现了错误。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

在部署任务中,需要显式地检出源代码,因为部署任务不会自动克隆源代码仓库。你可以在任务中使用 checkout: self 来检出源代码。部署任务只支持一个检出步骤。
以下是在 Azure Devops 管道中如何实现的步骤:
1. 在你的 .yml 文件中,将 checkout: self 添加到部署任务的步骤中。
2. 确保 dockerfilePath 的路径正确。
下面是一个示例 .yml 文件:

trigger:
- master
variables:
  # Container registry service connection established during pipeline creation
  dockerRegistryServiceConnection: 'some_id'
  imageRepository: 'worker'
  containerRegistry: 'microcontainerapptest.azurecr.io'
  dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile'
  tag: '$(Build.BuildId)'
  # Agent VM image name
  vmImageName: 'ubuntu-latest'
stages:
- stage: Build
  displayName: Build and push stage
  jobs:
  - deployment:
    displayName: Build docker image
    environment: $(DEPLOY_ENVIRONMENT)
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: Docker@2
            displayName: Build and push an image to container registry
            inputs:
              command: buildAndPush
              repository: $(imageRepository)
              dockerfile: $(dockerfilePath)
              containerRegistry: $(dockerRegistryServiceConnection)
              tags: |
                $(tag)

在上面的示例中,我们在部署任务的步骤中添加了 checkout: self 来检出源代码。确保 dockerfilePath 的路径正确。

方案2

如果方案1 无法解决问题,可以尝试手动指定 Dockerfile 的路径。
如果在部署任务中使用 checkout: self 仍然无法解决问题,你可以尝试手动指定 Dockerfile 的路径。
以下是一个示例 .yml 文件:

trigger:
- master
variables:
  # Container registry service connection established during pipeline creation
  dockerRegistryServiceConnection: 'some_id'
  imageRepository: 'worker'
  containerRegistry: 'microcontainerapptest.azurecr.io'
  dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile'
  tag: '$(Build.BuildId)'
  # Agent VM image name
  vmImageName: 'ubuntu-latest'
stages:
- stage: Build
  displayName: Build and push stage
  jobs:
  - deployment:
    displayName: Build docker image
    environment: $(DEPLOY_ENVIRONMENT)
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: Docker@2
            displayName: Build and push an image to container registry
            inputs:
              command: buildAndPush
              repository: $(imageRepository)
              dockerfile: $(Build.SourcesDirectory)/Dockerfile
              containerRegistry: $(dockerRegistryServiceConnection)
              tags: |
                $(tag)

在上面的示例中,我们手动指定了 Dockerfile 的路径为 $(Build.SourcesDirectory)/Dockerfile
请注意,如果你的 Dockerfile 不在默认的路径下,你需要根据实际情况修改 dockerfilePath 的值。

正文完