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.
| Line | Purpose |
|---|---|
trigger: - main | Starts 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: self | Uses 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: Build | Groups jobs. A single stage is enough here, but stages let you add test or deploy stages later. |
pool: vmImage: ubuntu-latest | Runs the job on a Microsoft-hosted Ubuntu agent that already has Docker installed. |
task: Docker@2 | Version 2 of the built-in Docker task. |
command: build | Runs 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
Dockerfilein the repository that builds locally. Rundocker 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
- Commit the YAML above as
azure-pipelines.ymlin the root of the repository. - In Azure DevOps, go to Pipelines > New pipeline and select where the code is hosted.
- Select the repository, then choose Existing Azure Pipelines YAML file and point it at
/azure-pipelines.yml. - Click Run. Later pushes to
mainstart new runs automatically. - Open the run and the Build an image step. The log shows the
docker buildcommand 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)
containerRegistryandrepositorytogether give the full image name, for examplemyregistry.azurecr.io/myapp:1234. Set both on the build step so the push step finds the same image.prruns the build for pull requests intomain, so a broken Dockerfile is caught before merge. In Azure Repos Git, PR builds come from a branch policy rather than theprkeyword.- The
conditionskips the push for pull request builds, so unreviewed code never reaches the registry. buildContextsets the directory sent to Docker. The default**means the folder that contains the Dockerfile.- You can merge both steps into one with
command: buildAndPushif you do not need PR builds. Note thatbuildAndPushignores theargumentsinput. 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
| Symptom | Cause | Fix |
|---|---|---|
| Pipeline never starts after a push | The branch in trigger does not match, for example main vs master | Change trigger to your real default branch |
No Dockerfile matching **/Dockerfile was found | The file has a different name or case, such as dockerfile or Dockerfile.prod | Set dockerfile to the exact path |
| The wrong Dockerfile is built | The glob matches several Dockerfiles in a monorepo | Use an explicit path such as src/api/Dockerfile |
COPY failed / file not found during build | The build context is the Dockerfile's folder, not the repository root | Set buildContext to the directory your COPY paths are relative to |
| No hosted parallelism has been purchased or granted | The organization has no Microsoft-hosted parallel jobs | Request the free parallelism grant or use a self-hosted agent pool |
| Run waits with a permission request | First use of a service connection by this pipeline | Click Permit on the run, or grant pipeline access on the service connection |
unauthorized or denied on push | Service connection credentials expired or lack push rights | Recreate 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. Treatlatestas a convenience only. - Pin the agent image if builds must be reproducible.
ubuntu-latestmoves to newer Ubuntu releases over time. A specific image such asubuntu-22.04changes only when you choose. - Add a
.dockerignorefile 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
- More Azure tutorials
- More CI/CD tutorials
- CI/CD Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- How to Prepare Self-Paced for Microsoft Azure Certifications?
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals