Use Azure Container Registry Build Tasks to Build and Push Container Images

Table of Contents

Introduction

As well as storing your container images in Azure Container Registry, you can also leverage the acr build command to use ACR to build the image as well. This is especially useful for CI/CD pipelines running in a container where Docker in Docker isn’t available. acr build executes the build process entirely in Azure’s cloud infrastructure, eliminating the need to run docker locally.

Prerequisites

  • az cli installed
  • An Azure Container Registry where you have the AcrPush and Reader (or greater) role assigned to you

How To

Create a working directory

Create yourself a directory called acr-build-demo in your home directory and change into it: mkdir ~/acr-build-demo && cd ~/acr-build-demo

Create Dockerfile

Within the folder you just created, create a Dockerfile with the following content:

FROM nginx:alpine

EXPOSE 80

This will create a container that just uses the nginx:alpine image as a base and does nothing else, which is fine for a quick test.

Build the image using ACR build tasks

Run the following command to build your image and store it in your ACR:

az acr build -t acr-build-demo:latest -r <my_container_registry> .

The arguments here mean:

  • -t: the name and tag you want the image to have in the registry
  • -r: the name of the container registry you are pushing to
  • .: the . at the end tells acr build to upload the current folder as the build context: it will use the Dockerfile in the current directory to build the image

You’ll see the build logs streamed to your terminal.

Verification

As well as building the container on the ACR, we can actually run it! Use the following command to verify that your image has been stored and can start up successfully using acr run:

az acr run -r <my_container_registry> --cmd '$Registry/acr-build-demo:latest' /dev/null

Check the logs streamed to your terminal and verify that the container starts.

Here’s a quick explanation of what that az acr run command is doing:

  • -r: the registry to use
  • --cmd: The image you want to run. $Registry is an environment variable available on the ACR that contains the registry url.
  • /dev/null: Pass nothing as the build context - we just want to run the image, not build anything