Skip to main content

Deploying Containers to Azure Kubernetes Service

Build an image, push it to Azure Container Registry, create an AKS cluster wired to ACR, and expose the deployment through a load balancer.

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
Remember

AKS 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.

flowchart TD SRC["Source code
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-acr grants the cluster's kubelet managed identity the AcrPull role 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.

Bash
az login
az provider register --namespace Microsoft.ContainerService
az provider register --namespace Microsoft.ContainerRegistry
az aks install-cli

Step 2: Create the application. This tiny service answers on port 8080 and exposes a /healthz endpoint that Kubernetes probes will call later.

JAVASCRIPT
// server.js - minimal cart-service for the lab
const 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));
Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY server.js .
ENV PORT=8080
EXPOSE 8080
USER node
CMD ["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.

Bash
RG=rg-aks-lab-mumbai
ACR_NAME=acrcartlab$RANDOM
az group create --name $RG --location centralindia
az acr create --resource-group $RG --name $ACR_NAME --sku Basic

Step 4: Build the image inside ACR. az acr build uploads your folder, builds it in the cloud, and stores the result in the registry.

Bash
az acr build --registry $ACR_NAME --image cart-service:v1 .
az acr repository show-tags --name $ACR_NAME --repository cart-service
Tip

Some free or trial subscriptions do not allow ACR Tasks. If the build is rejected, build locally with docker build, run az acr login --name $ACR_NAME, and push the tagged image with docker push.

Step 5: Create the cluster with the registry attached. Cluster creation takes several minutes. Two small nodes are enough for a lab.

Bash
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-keys
Remember

--attach-acr creates 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.

Bash
az aks get-credentials --resource-group $RG --name aks-lab-mumbai
kubectl get nodes
# Confirms the cluster can authenticate to and pull from the registry
az aks check-acr --resource-group $RG --name aks-lab-mumbai \
--acr $ACR_NAME.azurecr.io

Step 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.

YAML
# cart-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: cart-service
labels:
app: cart-service
spec:
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: 256Mi

The Service goes in its own file. It selects pods by the app: cart-service label, so it finds the pods the Deployment creates.

YAML
# cart-service-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: cart-service
spec:
type: LoadBalancer
selector:
app: cart-service
ports:
- port: 80 # port the load balancer listens on
targetPort: 8080 # port the container listens on

Step 8: Apply the manifests and wait for a public IP.

Bash
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-service
kubectl 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.

Bash
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; done

Step 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.

Bash
kubectl set env deployment/cart-service APP_VERSION=v2
kubectl rollout status deployment/cart-service
curl -s http://$EXTERNAL_IP/
kubectl rollout undo deployment/cart-service
kubectl rollout status deployment/cart-service

Step 11: Scale and clean up.

Bash
kubectl scale deployment cart-service --replicas=3
kubectl get pods -l app=cart-service
az group delete --name $RG --yes --no-wait

Production Best Practices & Common Pitfalls

  • Pin image tags to a version or digest: Deploy cart-service:v1, never latest, 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 LoadBalancer Service 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 Mistake

Managing ACR credentials by hand as Kubernetes image pull secrets. They expire or get misconfigured and cause confusing ImagePullBackOff errors. Attach the registry so the cluster's managed identity does the pulling.

Common Mistake

Getting targetPort wrong. If the Service forwards to a port the container does not listen on, the pod looks healthy but every request fails or times out.

Security

Never 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.

Tip

When 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

Explore More in Azure Compute Services

All 6 Topics

Frequently Asked Questions

Is Deploying Containers to Azure Kubernetes Service free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Deploying Containers to Azure Kubernetes Service topic cover?

Build an image, push it to Azure Container Registry, create an AKS cluster wired to ACR, and expose the deployment through a load balancer.

Found a mistake, an outdated step or a broken link?