MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Azure Devops Pipeline YAML Example

This page shows a minimal Azure Pipelines YAML file that builds a Docker image with the Docker@2 task on a Microsoft-hosted Ubuntu agent each time code is pushed to main. The sections below the example explain each line and show how to run the pipeline. They also cover how to push the image to a container registry, how to fix the most common errors, and which practices keep the pipeline secure.

Build a Docker image


What the example pipeline does, line by line

The azure-pipelines.yml above is the starter template Azure DevOps offers when you choose the Docker: Build an image option. It has one stage, one job and one step. It builds the image but does not publish it anywhere.

LinePurpose
trigger: - mainStarts a run on every push to the main branch. If your default branch is master, change this or the pipeline will never trigger.
resources: - repo: selfUses the repository that holds the YAML file. Pipelines check out self anyway, so you can remove this block.
variables: tag: '$(Build.BuildId)'Sets the image tag to the numeric run ID, which is unique for every run in the project.
stages / stage: BuildGroups jobs. A single stage is enough here, but stages let you add test or deploy stages later.
pool: vmImage: ubuntu-latestRuns the job on a Microsoft-hosted Ubuntu agent that already has Docker installed.
task: Docker@2Version 2 of the built-in Docker task.
command: buildRuns docker build only. Nothing is pushed.
dockerfile: '**/Dockerfile'A glob that finds a file named Dockerfile anywhere in the repository.
tags: | $(tag)One tag per line. Here the only tag is the build ID.

Note: With command: build and no registry, the image only exists on the hosted agent. It is deleted when the job finishes. That is fine for checking that the Dockerfile builds, but you need the push version further down to deploy anything.

Prerequisites

  • An Azure DevOps organization and project, with the code in Azure Repos or GitHub.
  • A Dockerfile in the repository that builds locally. Run docker build -t myapp:test . before you commit.
  • Parallel jobs available for Microsoft-hosted agents. New organizations may need to request the free grant or register a self-hosted agent.
  • If you want to push the image: a container registry such as Azure Container Registry (ACR) or Docker Hub, and permission to create service connections in the project.

Create and run the pipeline

  1. Commit the YAML above as azure-pipelines.yml in the root of the repository.
  2. In Azure DevOps, go to Pipelines > New pipeline and select where the code is hosted.
  3. Select the repository, then choose Existing Azure Pipelines YAML file and point it at /azure-pipelines.yml.
  4. Click Run. Later pushes to main start new runs automatically.
  5. Open the run and the Build an image step. The log shows the docker build command and each Dockerfile layer, and ends with the step succeeding.

Build and push the image to a container registry

To produce an image you can deploy, create a Docker Registry service connection under Project settings > Service connections > New service connection > Docker Registry. For ACR, choose Azure Container Registry and select your subscription and registry. Note the connection name, then use it in the pipeline below.

trigger:
  branches:
    include:
    - main

pr:
  branches:
    include:
    - main

variables:
  dockerRegistryServiceConnection: 'acr-connection'   # service connection name
  imageRepository: 'myapp'                            # repository inside the registry
  dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile'
  tag: '$(Build.BuildId)'

stages:
- stage: Build
  displayName: Build and push image
  jobs:
  - job: Build
    pool:
      vmImage: ubuntu-latest
    steps:
    - task: Docker@2
      displayName: Build image
      inputs:
        command: build
        containerRegistry: $(dockerRegistryServiceConnection)
        repository: $(imageRepository)
        dockerfile: $(dockerfilePath)
        buildContext: '$(Build.SourcesDirectory)'
        tags: |
          $(tag)

    - task: Docker@2
      displayName: Push image
      condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
      inputs:
        command: push
        containerRegistry: $(dockerRegistryServiceConnection)
        repository: $(imageRepository)
        tags: |
          $(tag)Code language: PHP (php)
  • containerRegistry and repository together give the full image name, for example myregistry.azurecr.io/myapp:1234. Set both on the build step so the push step finds the same image.
  • pr runs the build for pull requests into main, so a broken Dockerfile is caught before merge. In Azure Repos Git, PR builds come from a branch policy rather than the pr keyword.
  • The condition skips the push for pull request builds, so unreviewed code never reaches the registry.
  • buildContext sets the directory sent to Docker. The default ** means the folder that contains the Dockerfile.
  • You can merge both steps into one with command: buildAndPush if you do not need PR builds. Note that buildAndPush ignores the arguments input. Use separate steps if you need options such as --build-arg.

After a run on main, confirm the tag reached ACR:

az acr repository show-tags --name myregistry --repository myapp --output table

Common errors and fixes

SymptomCauseFix
Pipeline never starts after a pushThe branch in trigger does not match, for example main vs masterChange trigger to your real default branch
No Dockerfile matching **/Dockerfile was foundThe file has a different name or case, such as dockerfile or Dockerfile.prodSet dockerfile to the exact path
The wrong Dockerfile is builtThe glob matches several Dockerfiles in a monorepoUse an explicit path such as src/api/Dockerfile
COPY failed / file not found during buildThe build context is the Dockerfile's folder, not the repository rootSet buildContext to the directory your COPY paths are relative to
No hosted parallelism has been purchased or grantedThe organization has no Microsoft-hosted parallel jobsRequest the free parallelism grant or use a self-hosted agent pool
Run waits with a permission requestFirst use of a service connection by this pipelineClick Permit on the run, or grant pipeline access on the service connection
unauthorized or denied on pushService connection credentials expired or lack push rightsRecreate or update the service connection and check its role on the registry

Best practices and security notes

  • Never put registry passwords in YAML. Use a service connection, or a secret variable for non-Docker credentials.
  • Use immutable tags for deployments. $(Build.BuildId) or the commit SHA $(Build.SourceVersion) lets you trace a running container back to a build. Treat latest as a convenience only.
  • Pin the agent image if builds must be reproducible. ubuntu-latest moves to newer Ubuntu releases over time. A specific image such as ubuntu-22.04 changes only when you choose.
  • Add a .dockerignore file so .git, local build output and secrets are not sent in the build context.
  • Restrict service connections. Do not grant access to all pipelines, and add approvals on environments that deploy to production.
  • Scan images for vulnerabilities before they reach production, either with your registry's scanning feature or with a scanner step in the pipeline.

Correction to the original example

The YAML above is valid and runs as written. The documentation link in its header comment uses the old docs.microsoft.com domain, which now redirects to learn.microsoft.com. The resources: - repo: self block is a leftover from older templates and is not needed. Most importantly, readers should know that command: build never publishes the image. Use the build-and-push version in this article when the image needs to be deployed.

Frequently asked questions

What is the difference between build and buildAndPush in the Docker@2 task?

build runs only docker build, so the image stays on the agent. buildAndPush builds the image and pushes every listed tag to the registry in the service connection. Unlike build, it ignores the arguments input.

Where does the image go if I only use command: build?

It stays in the local Docker cache of the hosted agent, and that cache is deleted when the job ends. Add a push or buildAndPush step with a containerRegistry service connection to keep the image.

How do I tag the image with the Git commit SHA?

Add $(Build.SourceVersion) as a line under tags. You can list it next to $(Build.BuildId) so each image has both tags.

Can I use docker commands directly instead of the Docker@2 task?

Yes. Microsoft-hosted Ubuntu agents have Docker installed, so a script step running docker build works. You then have to log in to the registry yourself. The Docker@2 task handles login through the service connection and adds pipeline metadata labels.

Why does my Azure Pipelines YAML not trigger on push?

Usually the branch named under trigger does not match the branch you pushed to. Also check that the pipeline points at the right YAML file, and that triggers are not overridden in the pipeline's UI settings.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Azure DevOps Pipelines Fundamental Tutorials

Here is an in-depth, step-by-step tutorial on Azure DevOps Pipelines that covers everything from the fundamentals to advanced concepts. This guide is designed to help you understand…

Read More

GitLab Tutorials: Example of .gitlab-ci.yml

.gitlab-ci.yml file to run with Docker runner Build a Docker image with CI/CD and push to the GitLab registry Rajesh Kumar I’m Rajesh Kumar, a DevOps, SRE,…

Read More

Azure Pipeline to Deploy into AKS

This page shows how an Azure DevOps YAML pipeline deploys NGINX to an Azure Kubernetes Service (AKS) cluster. It uses the AzureCLI@2 task, an Azure Resource Manager…

Read More

Gitlab – Complete Details of .gitlab-ci.yml

GitLab builds every pipeline from one entry-point configuration file, .gitlab-ci.yml by default, but that file can pull in any number of other YAML files with the include…

Read More

Docker Tutorials: Docker Image – Example and Sample Programs of Dockerfile

This page collects sample Dockerfiles that build an Ubuntu-based Apache image and show how CMD, ENTRYPOINT, EXPOSE, ARG, ENV, COPY and USER behave. Below the examples you…

Read More

Kubernetes: Pull an Image from a Private Registry using Yaml and Helm File

Kubernetes pulls images from a private registry using a kubernetes.io/dockerconfigjson Secret. A Pod references that Secret through imagePullSecrets, either directly or through its ServiceAccount. This page shows…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x