Overview and What You Will Learn
You deploy a container to AKS by building an image, pushing it to Azure Container Registry (ACR), creating a cluster that is allowed to pull from that registry, and running the image as a Kubernetes Deployment behind a Service of type LoadBalancer. This lab walks that whole path, from a few lines of source code to a public IP that answers requests.
By the end you will be able to:
- Build a container image inside ACR without installing Docker locally
- Create an AKS cluster with pull access to your registry already configured
- Write a Deployment manifest with replicas, health probes, and resource limits
- Expose the workload through an Azure Load Balancer and verify it with curl
- Roll out a change, roll it back, and diagnose the most common failures
RememberAKS nodes are normal Azure VMs and are billed while they exist. Run the cleanup step at the end of the lab.
Why This Matters in Production
Running one container is easy, but running a dozen interdependent services by hand means you must restart crashed processes, spread load, and roll out updates without dropping traffic. AKS takes over those jobs: it reschedules failed pods, scales replicas, and replaces versions gradually.
Picture a platform team at a company like Grab running separate cart, pricing, and promotions services. Each needs its own replicas and its own rollout schedule, and a crash in one must never take the others down. Kubernetes gives them that coordination, and ACR gives them a private, access-controlled place to keep the images.
Core Principles
Source code becomes a running, reachable service in five hops, and each hop is a separate object you can inspect. The image lives in ACR, the Deployment tells Kubernetes how many copies to run, and the Service gives those copies one stable address.
and Dockerfile"]:::person -->|az acr build| ACR[("Azure Container
Registry")]:::tool ACR -->|image pull| NODE["AKS node pool"]:::cloud NODE -->|runs| POD["cart-service pods"]:::cloud POD -->|selected by| SVC["Service
LoadBalancer"]:::app SVC -->|public IP| USER(["Internet users"]):::person classDef person fill:#EDE9FE,color:#1E293B classDef tool fill:#326CE5,color:#FFFFFF classDef cloud fill:#D1FAE5,color:#1E293B classDef app fill:#FFEDD5,color:#1E293B
Four ideas explain almost everything in this lab:
- Pod: The smallest runnable unit, holding one or more containers.
- Deployment: Keeps the desired number of identical pods running and performs rolling updates.
- Service: A stable virtual address in front of a changing set of pods, chosen by label selector.
- Registry attachment:
--attach-acrgrants the cluster's kubelet managed identity theAcrPullrole on the registry, so nodes pull images with no stored credentials.
Detailed Step-by-Step Practical Lab
Step 1: Prepare the tools. You need the Azure CLI signed in to a subscription where you can create resources and assign roles. Register the resource providers once, then install kubectl.
az loginaz provider register --namespace Microsoft.ContainerServiceaz provider register --namespace Microsoft.ContainerRegistryaz aks install-cliStep 2: Create the application. This tiny service answers on port 8080 and exposes a /healthz endpoint that Kubernetes probes will call later.
// server.js - minimal cart-service for the labconst http = require("http");const port = process.env.PORT || 8080; http.createServer((req, res) => { if (req.url === "/healthz") { res.writeHead(200); return res.end("ok"); } res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ service: "cart-service", version: process.env.APP_VERSION || "v1", pod: process.env.HOSTNAME }));}).listen(port, () => console.log("cart-service listening on " + port));FROM node:20-alpineWORKDIR /appCOPY server.js .ENV PORT=8080EXPOSE 8080USER nodeCMD ["node", "server.js"]Step 3: Create a resource group and a registry. Registry names must be globally unique, lowercase, and alphanumeric, so the commands below add a random suffix.
RG=rg-aks-lab-mumbaiACR_NAME=acrcartlab$RANDOM az group create --name $RG --location centralindiaaz acr create --resource-group $RG --name $ACR_NAME --sku BasicStep 4: Build the image inside ACR. az acr build uploads your folder, builds it in the cloud, and stores the result in the registry.
az acr build --registry $ACR_NAME --image cart-service:v1 .az acr repository show-tags --name $ACR_NAME --repository cart-serviceTipSome free or trial subscriptions do not allow ACR Tasks. If the build is rejected, build locally with
docker build, runaz acr login --name $ACR_NAME, and push the tagged image withdocker push.
Step 5: Create the cluster with the registry attached. Cluster creation takes several minutes. Two small nodes are enough for a lab.
az aks create \ --resource-group $RG \ --name aks-lab-mumbai \ --node-count 2 \ --node-vm-size Standard_D2s_v5 \ --attach-acr $ACR_NAME \ --generate-ssh-keysRemember
--attach-acrcreates a role assignment, so your account needs permission to assign roles (Owner or User Access Administrator) on the registry.
Step 6: Connect kubectl and verify registry access.
az aks get-credentials --resource-group $RG --name aks-lab-mumbaikubectl get nodes # Confirms the cluster can authenticate to and pull from the registryaz aks check-acr --resource-group $RG --name aks-lab-mumbai \ --acr $ACR_NAME.azurecr.ioStep 7: Write the Deployment and Service manifests. A manifest is repeatable and reviewable, unlike a one-off kubectl create command. The placeholder ACR_NAME is replaced when you apply it.
# cart-deployment.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: cart-service labels: app: cart-servicespec: replicas: 2 selector: matchLabels: app: cart-service strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 # never drop below desired capacity during a rollout maxSurge: 1 # add one extra pod at a time template: metadata: labels: app: cart-service spec: containers: - name: cart-service image: ACR_NAME.azurecr.io/cart-service:v1 ports: - containerPort: 8080 env: - name: APP_VERSION value: "v1" readinessProbe: # pod receives traffic only when this passes httpGet: path: /healthz port: 8080 initialDelaySeconds: 3 periodSeconds: 5 livenessProbe: # pod is restarted if this keeps failing httpGet: path: /healthz port: 8080 initialDelaySeconds: 10 periodSeconds: 10 resources: requests: cpu: 100m memory: 128Mi limits: cpu: 250m memory: 256MiThe Service goes in its own file. It selects pods by the app: cart-service label, so it finds the pods the Deployment creates.
# cart-service-svc.yamlapiVersion: v1kind: Servicemetadata: name: cart-servicespec: type: LoadBalancer selector: app: cart-service ports: - port: 80 # port the load balancer listens on targetPort: 8080 # port the container listens onStep 8: Apply the manifests and wait for a public IP.
sed "s/ACR_NAME/$ACR_NAME/" cart-deployment.yaml | kubectl apply -f -kubectl apply -f cart-service-svc.yaml kubectl get pods -l app=cart-servicekubectl get service cart-service --watch# Press Ctrl+C once EXTERNAL-IP shows an address instead of <pending>Step 9: Call the service. Repeat the request a few times and watch the pod field change as the load balancer spreads requests across replicas.
EXTERNAL_IP=$(kubectl get service cart-service \ -o jsonpath='{.status.loadBalancer.ingress[0].ip}') for i in 1 2 3 4; do curl -s http://$EXTERNAL_IP/; echo; doneStep 10: Roll out a change, then undo it. Changing the pod template triggers a rolling update. Because maxUnavailable is 0, the service keeps answering while pods are replaced.
kubectl set env deployment/cart-service APP_VERSION=v2kubectl rollout status deployment/cart-servicecurl -s http://$EXTERNAL_IP/ kubectl rollout undo deployment/cart-servicekubectl rollout status deployment/cart-serviceStep 11: Scale and clean up.
kubectl scale deployment cart-service --replicas=3kubectl get pods -l app=cart-service az group delete --name $RG --yes --no-waitProduction Best Practices & Common Pitfalls
- Pin image tags to a version or digest: Deploy
cart-service:v1, neverlatest, so a rollout or a node restart always runs exactly the image you tested. - Always set resource requests and limits: Without requests the scheduler cannot place pods sensibly, and without limits one noisy pod can starve its neighbours.
- Use readiness and liveness probes: Readiness keeps traffic away from pods that are still starting, and liveness restarts pods that have hung.
- Use an ingress controller for many services: A
LoadBalancerService creates one public IP per service, so route several HTTP services through one ingress instead. - Plan for scale and upgrades: Enable the Cluster Autoscaler once traffic patterns are known, and choose an upgrade channel so Kubernetes versions and node images do not fall behind.
- Harden before real traffic: Prefer a private cluster or authorised IP ranges for the API server, and use the Standard tier for the uptime SLA.
Common MistakeManaging ACR credentials by hand as Kubernetes image pull secrets. They expire or get misconfigured and cause confusing
ImagePullBackOfferrors. Attach the registry so the cluster's managed identity does the pulling.
Common MistakeGetting
targetPortwrong. If the Service forwards to a port the container does not listen on, the pod looks healthy but every request fails or times out.
SecurityNever put registry admin credentials or secrets in a manifest or image. Keep the ACR admin user disabled, and store application secrets in Azure Key Vault.
TipWhen a pod is not Running, run
kubectl describe pod <name>first. The Events section names the real cause, such as a failed image pull, insufficient CPU, or a failing probe.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
az acr build --registry <acr> --image app:v1 . |
Build an image inside ACR |
az aks create --attach-acr <acr> |
Create a cluster that can pull from the registry |
az aks check-acr --acr <acr>.azurecr.io |
Test cluster-to-registry connectivity |
az aks get-credentials |
Configure kubectl for the cluster |
kubectl get pods -o wide |
Show pod status and the node each pod runs on |
kubectl describe pod <name> |
Explain why a pod is not Running |
kubectl logs <pod> |
Read container output |
kubectl rollout undo deployment/<name> |
Revert to the previous version |
| Symptom | Likely cause |
|---|---|
ImagePullBackOff |
Wrong image name or tag, or the registry is not attached |
EXTERNAL-IP stays <pending> |
Public IP quota reached or a subnet or permission issue |
CrashLoopBackOff |
The app exits on start or a liveness probe keeps failing |
Pod Pending |
Not enough CPU or memory on the nodes for the requests |
| Service times out | targetPort does not match the container port |