English translation of the Chinese courseware. Check the linked official documentation for version-sensitive details.

Docker Hour 3: To the Cloud (Azure)

Push the production-ready myapp to ACR, deploy it to Azure Container Apps, practice troubleshooting in the cloud, and take the first step into Kubernetes
Azure Container AppsACR · Key Vault · Managed Rediskind v0.33 · AKSVerified against official docs · 2026-11
Learning objectives
  • Choose between ACI, Container Apps, AKS, App Service and VM + Docker for a given scenario.
  • Use ACR cloud builds, cleanup policies, tag locking, import and Artifact Cache.
  • Pull images without passwords using a user-assigned managed identity, deploy myapp to Container Apps, and configure probes, resources and scale rules.
  • Handle configuration and stateful dependencies with secrets, Key Vault references and managed Redis (or a TCP service inside the environment).
  • Work with revisions, traffic splitting, label URLs and rollbacks; troubleshoot cloud failures with system logs, console logs and KQL.
  • Map Compose concepts to Kubernetes and run the same image on kind and AKS.

1-hour schedule

#TimeModuleCore contentAnimation / interactiveLab
0Before classWarm-up & Azure setupReview network modes and volume backup; register resource providers; set variables—Local network/volume exercises
100–05Choosing a cloud container serviceACI / ACA / AKS / App Service / VM compared; ACA architecture (environment, revision, replica, Envoy, KEDA)Service selection wizardInstall extension, register providers
205–13ACR in depthTwo ways to push, ACR Tasks, purge, tag locking, import, Artifact Cache, Defenderpurge rule simulatorCloud build + cleanup walkthrough
313–24Deploy to Container Apps ⭐Environment, managed identity + AcrPull, ingress, CPU/memory combinations, probesDeployment animation + resource combination checkerDeploy myapp and open it over HTTPS
424–32Config, secrets & Redissecretref, Key Vault references, secret rotation, internal TCP service, Azure Managed Redis"When does a changed secret reach the container?" simulatorInternal Redis + Key Vault secret
532–40Revisions, traffic & scalingSingle/multiple revision mode, revision suffix, label URLs, traffic splitting, rollback, HTTP scale rulesTraffic splitting simulator10% canary + rollback + load-test scale-out
640–50Cloud troubleshooting labFour classes of local failures; image pull, architecture, port, probe, secret, OOM; system logs and KQL6 cloud failure drillsBreak things on purpose and fix them
750–57Moving on to KubernetesConcept mapping, k8s.yaml, kubectl, rolling update and rollback, AKS + attach-acrCompose → K8s mapperDeploy myapp to a kind cluster
857–60Cost, cleanup & self-checkBilling components, cleanup order, link to hour 5—Delete the resource group
—After classCheat sheet · Capstone labEnd to end: ACR → ACA (Key Vault + internal Redis) → canary → KQLFinal examCapstone lab

How this lesson builds on Lessons 1 and 2

Lesson 1
Networking, storage and ACR authentication (3-hour tokens, managed identity, ABAC) were covered there. The "before class" part of this lesson is only a quick review.
Lesson 2
Graceful shutdown, health checks, tagging policy, security hardening and the review script are applied directly in the cloud here: probes correspond to HEALTHCHECK, and revisions correspond to image tags.
Hour 5
Image CI pipelines, signing and supply chain, and automated release and rollback are left for hour 5. This lesson uses the Azure CLI by hand so that every step is easy to follow.
Cost warningThis lesson creates ACR, a Container Apps environment, Log Analytics, Key Vault, and optionally AKS and Azure Managed Redis, all of which incur charges. When you finish, run the cleanup commands in Module 8. AKS and Managed Redis are optional and billed by the hour, so delete them as soon as you are done.

Module 0 · Warm-up and Azure setup (before class)

A quick local review of networks and volumes; prepare the subscription, CLI extension and variables in the cloud
Before class ≈ 10 min
Prerequisites
  • You have completed Lessons 1 and 2; the Ubuntu VM has ~/myapp (Flask + Redis).
  • You have an Azure subscription, and your account has Owner or "Contributor + User Access Administrator" on a resource group (needed to create role assignments).
  • Azure CLI is installed on the VM (Lesson 1, Module 0) and az version works.

Warm-up 1: answer from memory

What does exit code 137 mean?

The process was killed by SIGKILL. Check .State.OOMKilled first; if it is false, it may be a stop timeout (a PID 1 signal-handling problem).

Why not use latest in production?

latest gets overwritten, so you cannot trace or roll back; deploy with SHA tags or digests.

Warm-up 2: network modes and volume backup (local)

ModeCharacteristicsUse when
Default bridgeNo container-name DNS, IP addresses onlyNot recommended
User-defined bridgeBuilt-in DNS (127.0.0.11), isolates different appsEveryday default
hostUses the host network directly, no port mapping; fully supported only on LinuxExtremely performance-sensitive workloads
noneLoopback onlyPure compute, security sandbox
docker run -d --name a nginx:alpine
docker run --rm alpine ping -c1 a                  # fails: bad address 'a'
docker network create appnet
docker run -d --name b --network appnet nginx:alpine
docker run --rm --network appnet alpine ping -c1 b # succeeds
docker run --rm --network none alpine ip addr      # only lo
docker network connect appnet a                    # handy when debugging: attach a running container to a network
docker run --rm --network appnet alpine ping -c1 a # now succeeds
docker rm -f a b; docker network rm appnet
# Volumes created by Compose carry the project prefix; check the actual volume name first
docker volume ls | grep redis
docker run --rm -v myapp_redis-data:/data:ro -v "$PWD":/backup alpine tar czf /backup/redis-data.tgz -C /data .
docker volume create redis-data-restored
docker run --rm -v redis-data-restored:/data -v "$PWD":/backup alpine tar xzf /backup/redis-data.tgz -C /data

For the underlying concepts see Lesson 1, Module 5 (networking) and Module 6 (storage).

Azure setup

az login --use-device-code                 # this lesson uses your user identity (not the VM's managed identity)
az account show -o table
az extension add --name containerapp --upgrade
az provider register --namespace Microsoft.App
az provider register --namespace Microsoft.OperationalInsights
az provider show -n Microsoft.App --query registrationState -o tsv   # wait for Registered

Shared variables (reload them in every new terminal)

SUFFIX=$RANDOM
cat > ~/hour3.env <<EOF
export RG=rg-docker-hour3
export LOC=canadacentral
export ACR=acrhour3${SUFFIX}
export ENV=cae-docker-lab
export APP=myapp
export ID_NAME=id-myapp
export KV=kv-hour3-${SUFFIX}
EOF
source ~/hour3.env; cat ~/hour3.env
az group create -n $RG -l $LOC -o table

ACR names must be globally unique (5–50 alphanumeric characters), and so must Key Vault names (3–24 characters). If az acr create says the name is taken, edit ~/hour3.env and source it again.

Module 1 · Choosing a cloud container service and the Container Apps architecture

00:00 – 05:00 · The same image can run on five Azure services. Which one should you pick?
5 minAzure Container AppsKEDA · Envoy · Dapr
Learning objectives
  • Explain the differences and typical use cases of ACI, Container Apps, AKS, App Service and VM + Docker.
  • Understand the Container Apps object model: environment → app → revision → replica.

What: five ways to run containers on Azure

ServiceWhat you manageScalingGood fitPoor fit
VM + Docker/ComposeOS, patches, Docker, high availabilityManualLegacy apps, full control, edge scenariosServices that need elasticity and high availability
Azure Container InstancesAlmost nothingNo built-in autoscalingShort tasks, batch jobs, temporary environmentsLong-running web services
Azure Container AppsImage and configurationKEDA event-driven, can scale to 0Microservices, APIs, background jobs; teams that don't want to operate KubernetesWorkloads that need direct access to the Kubernetes API, CRDs, DaemonSets
AKSCluster configuration, node pools, upgrades, add-onsHPA / KEDA / cluster autoscalerLarge platforms that need the full Kubernetes ecosystemSimple apps run by small teams (heavy operational burden)
App Service (containers)Image and configurationBy schedule/rulesTraditional web apps, existing App Service estatesMulti-service, event-driven scenarios

Why: the Container Apps architecture

  • Environment: the security and network boundary for a group of apps, sharing a virtual network and Log Analytics; apps in the same environment can reach each other by name. The default is a workload profiles environment with a Consumption profile.
  • App (Container App): one or more containers (main container + sidecars) plus configuration for ingress, secrets, registries and identity.
  • Revision: an immutable snapshot of properties.template (image, environment variables, resources, scale rules), much like an image tag is to an image.
  • Replica: a running instance of a revision; the count is driven by scale rules (KEDA) and can go down to 0.
  • Ingress: Envoy-based managed ingress that provides an HTTPS certificate and FQDN automatically and supports traffic splitting.

How / When: what runs underneath

Container Apps runs on Microsoft-managed Kubernetes, but you cannot see or operate the cluster. It wraps the most commonly used Kubernetes capabilities (Deployment, Service, Ingress, HPA/KEDA, Dapr) into a small set of parameters. When you need something beyond those parameters (custom CRDs, Operators, node-level control), consider AKS.

Container Apps environment cae-docker-lab (shared network boundary + Log Analytics) Envoy IngressHTTPS · FQDNTraffic splitting App myapp (identity, secrets, registry, ingress) Revision myapp--v11Replicas ×2 · 90% traffic Revision myapp--v12Replica ×1 · 10% traffic redis (internal TCP)Reachable only in the env KEDA scaling (HTTP/queue/CPU) Log Analytics (console/system) ACR (managed identity pull) Key Vault (secret references)
Figure 1-1 Environment → app → revision → replica

Service selection wizard

CommandDescription
az extension add --name containerapp --upgradeInstall/upgrade the Container Apps CLI extension
az provider register --namespace Microsoft.AppRegister the resource provider (Microsoft.OperationalInsights is also required)
az containerapp env list -o tableList environments
az containerapp list -g $RG -o tableList apps
az containerapp up --source .Build, push and deploy in one command (good for demos; this lesson goes step by step so you understand each part)

Lab 1: confirm the environment is ready (about 2 min)

source ~/hour3.env
az extension show -n containerapp --query version -o tsv
az provider show -n Microsoft.App --query registrationState -o tsv
az provider show -n Microsoft.OperationalInsights --query registrationState -o tsv
az group show -n $RG --query properties.provisioningState -o tsv
1.x.x
Registered
Registered
Succeeded

Case: an internal tools platform moves from VMs to Container Apps

A team ran 15 internal APIs with Compose on 3 VMs and spent a lot of time every month on patching, disks and certificates. After moving to Container Apps, the platform manages certificates and ingress; services scale down to 1 replica off-peak; every release creates a revision, and rolling back is just a traffic switch. Only one service that needs a custom Operator stayed on AKS.

A cautionary tale

Another 3-person team built an AKS cluster for one simple API and ended up spending 70% of their time on cluster upgrades, the Ingress Controller and certificate management. Lesson learned: start with the simplest managed service, and move to AKS only when you clearly need Kubernetes capabilities.

The subscription is not registered to use namespace 'Microsoft.App'

Run az provider register --namespace Microsoft.App and wait until the state is Registered (this can take a few minutes).

az containerapp: 'containerapp' is misspelled or not recognized

The CLI extension is not installed: az extension add --name containerapp --upgrade.

AuthorizationFailed (when creating a role assignment)

Your account lacks Microsoft.Authorization/roleAssignments/write; you need the Owner, User Access Administrator or Role Based Access Control Administrator role.

or score ≥ 70% on the Quiz

Module 2 · ACR in depth: cloud builds, cleanup, locking and caching

05:00 – 13:00 · Keep your registry under control, clean, and independent of Docker Hub
8 minACR Tasks · acr purgeArtifact Cache
Learning objectives
  • Master both ways to push: local build + push, and cloud builds with az acr build.
  • Define a cleanup policy with acr purge and protect release versions with tag locks.
  • Manage base images with az acr import and Artifact Cache to escape Docker Hub rate limits.
Lesson 1 recap Image references, how push/pull works, and authentication methods (3-hour tokens, managed identity, ABAC mode) are covered in Lesson 1, Module 8.

What: two ways to push

Local build + docker pushaz acr build (ACR Tasks)
Needs local DockerYesNo (the build context is uploaded and built in the cloud)
ArchitectureDefaults to the host architecture; on Apple Silicon you need --platform linux/amd64Defaults to linux/amd64; choose another with --platform
Best forDevelopment and debugging, multi-platform BuildxRestricted CI environments, machines where Docker can't be installed

Why: a registry needs governance

  • Cleanup: every build pushes a new tag, so after a few months storage cost and list noise grow large. acr purge (run inside az acr run) filters by name, deletes by age, can keep the latest N tags, and can delete untagged manifests.
  • Locking: az acr repository update --image myapp:1.4.2 --write-enabled false prevents a release tag from being overwritten; --delete-enabled false prevents deletion (including by purge).
  • Base images: az acr import does a one-time import; Artifact Cache rules pull and cache upstream images on demand (Docker Hub as a source requires a credential set, stored in Key Vault).
  • Scanning: with Microsoft Defender for Containers enabled, images pushed to ACR are scanned automatically.

How: SKUs and networking

SKUMain differences
BasicEntry level and learning; lower storage and throughput
StandardMost production scenarios
PremiumAdvanced features such as geo-replication, private endpoints and higher throughput

For exact per-SKU quotas and prices, see the official Azure pages.

When: permissions

Keep the admin account disabled in production; apps use a managed identity + AcrPull; CI uses AcrPush (or, in ABAC mode, the Container Registry Repository roles; see Lesson 1).

Local / CIdocker push Source directoryaz acr build (uploads context) ACR myapp:1.1 · 1.2 · sha-xxxx (locked release tags 🔒) base/python:3.13-slim (import) cache: docker.io/library/* → hub/* Scheduled acr purge: old tags + untagged manifests Docker Hub, etc.import / cache rules ACA / AKSManaged identity + AcrPull

acr purge rule simulator

The repository has 30 myapp tags (one per day) and some untagged manifests. Adjust the parameters to see which ones would be deleted (equivalent to --dry-run).

CommandDescription
az acr create -g $RG -n $ACR --sku BasicCreate a registry
az acr build -r $ACR -t myapp:1.1 .Build in the cloud and push (linux/amd64 by default)
az acr build -r $ACR -t myapp:{{.Run.ID}} --platform linux/arm64 .Choose a platform; {{.Run.ID}} is a unique run ID
az acr task logs -r $ACR / az acr task list-runs -r $ACR -o tableView cloud build history
az acr run -r $ACR --cmd "acr purge --filter 'myapp:.*' --ago 30d --keep 20 --untagged --dry-run" /dev/nullCleanup dry run (remove --dry-run to actually delete)
az acr task create -r $ACR -n purge --cmd "acr purge …" --schedule "0 3 * * *" -c /dev/nullScheduled cleanup task
az acr repository update -n $ACR --image myapp:1.1 --write-enabled false --delete-enabled falseLock a tag
az acr import -n $ACR --source docker.io/library/python:3.13-slim -t base/python:3.13-slimImport a public image
az acr cache create -r $ACR -n hub-python -s docker.io/library/python -t hub/python -c <credential-set>Artifact Cache rule (Docker Hub requires a credential set)
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --detail -o tableList tags by time
az acr show-usage -n $ACR -o tableStorage usage

Lab 2: create ACR, push both ways, cleanup dry run (about 7 min)

Update app.py: support cloud Redis (password/TLS) and add /healthz
cd ~/myapp
cat > app.py <<'EOF'
import os, socket
from flask import Flask
import redis

app = Flask(__name__)
r = redis.Redis(
    host=os.getenv("REDIS_HOST", "redis"),
    port=int(os.getenv("REDIS_PORT", "6379")),
    password=os.getenv("REDIS_PASSWORD") or None,
    ssl=os.getenv("REDIS_SSL", "false").lower() == "true",
    socket_connect_timeout=1,
)
VERSION = os.getenv("APP_VERSION", "dev")

@app.route("/")
def index():
    try:
        hits = r.incr("hits")
    except redis.exceptions.RedisError:
        hits = "N/A (redis is not connected)"
    return f"[{VERSION}] Hello from {socket.gethostname()}, hits={hits}\n"

@app.route("/healthz")
def healthz():
    return "ok"
EOF
Create ACR. Option 1: local build + push
source ~/hour3.env
az acr create -g $RG -n $ACR --sku Basic -o table
az acr login -n $ACR
docker build --platform linux/amd64 -t $ACR.azurecr.io/myapp:1.0 .
docker push $ACR.azurecr.io/myapp:1.0
Option 2: cloud build
az acr build -r $ACR -t myapp:1.1 .
az acr repository show-tags -n $ACR --repository myapp --detail -o table
Queued a build with ID: ca1
…
Run ID: ca1 was successful after 45s
Lock the release tag, then do a cleanup dry run
az acr repository update -n $ACR --image myapp:1.1 --write-enabled false --delete-enabled false -o table
for i in 1 2 3; do az acr build -r $ACR -t myapp:tmp-$i --no-logs . ; done
az acr run -r $ACR --cmd "acr purge --filter 'myapp:tmp-.*' --ago 0d --keep 1 --untagged --dry-run" /dev/null
az acr run -r $ACR --cmd "acr purge --filter 'myapp:tmp-.*' --ago 0d --keep 1 --untagged" /dev/null
az acr repository show-tags -n $ACR --repository myapp -o tsv
Number of tags to be deleted: 2
…
1.0
1.1
tmp-3
Import a base image
az acr import -n $ACR --source docker.io/library/python:3.13-slim -t base/python:3.13-slim
az acr repository list -n $ACR -o table

Anonymous imports from Docker Hub are rate-limited too; if needed, add --username/--password (a Docker Hub access token).

Case 1: purge deleted an image still running in production

A cleanup rule of --ago 7d --keep 5 deleted a tag released two weeks earlier that was still running in production. Later, when a replica restarted, the image pull failed. Fix: always lock release tags (--delete-enabled false), and make purge filters match only temporary CI tags (such as sha-.* or pr-.*).

Case 2: Docker Hub rate limits broke scale-out

During a peak-time scale-out, nodes pulling python:3.13-slim hit toomanyrequests. Fix: change the FROM line of every Dockerfile to the base/ path or cache-rule path in ACR, and use Azure Policy to allow pulls only from the internal ACR.

az acr build: Error: failed to fetch … unauthorized / denied

The signed-in user has no push permission on the ACR, or the ACR has network rules enabled (ACR Tasks then needs "Allow trusted Microsoft services" or a dedicated agent pool).

The name is already in use / AlreadyInUse (creating ACR)

Registry names are globally unique; pick another name.

Changing a tag fails with "The operation is disallowed on this registry, repository or image"

The image is locked (write-enabled=false). If you really need to change it, unlock it first and record the reason for auditing.

acr purge deletes nothing

The filter regex doesn't match (format: repository:tag-regex), the tags are locked, or no tags meet the --ago window. Check with --dry-run first.

Note No verifiable video covering acr purge and Artifact Cache was found; this module relies on the official documentation.
or score ≥ 70% on the Quiz

Module 3 · Deploy to Azure Container Apps ⭐

13:00 – 24:00 · Passwordless pulls with managed identity, HTTPS ingress, resource combinations and health probes
11 minaz containerappCore of this lesson
Learning objectives
  • Create a Container Apps environment and a user-assigned managed identity, and grant it AcrPull.
  • Deploy myapp with a single az containerapp create and understand every parameter.
  • Choose a valid CPU/memory combination and configure startup/readiness/liveness probes.

What: four things a deployment needs

ResourcePurposeCommand
EnvironmentNetwork and logging boundary for apps; creates a Log Analytics workspace by defaultaz containerapp env create
User-assigned managed identityPulls ACR images and reads Key Vault; its lifecycle is independent of the app, so it can be authorized before the app is createdaz identity create
Role assignmentAcrPull for the identity on the ACRaz role assignment create
AppImage, ingress, resources, scaling, probesaz containerapp create

Why: why a user-assigned rather than a system-assigned identity

A system-assigned identity only exists after the app is created, but the image must be pulled while the app is being created: a chicken-and-egg problem. A user-assigned identity can be created and authorized first, then referenced when the app is created (--user-assigned + --registry-identity). The official docs also note that Key Vault references in the create command can only use a user-assigned identity.

How: key parameters

ParameterMeaning
--imageImage address in ACR (immutable tags recommended)
--registry-server + --registry-identityPull the image with a managed identity instead of a password (you can also pass system)
--ingress external|internal + --target-portWhether it is public; the port the app listens on inside the container (must match the app, which must listen on 0.0.0.0)
--cpu / --memoryResources per replica; must be a valid combination (e.g. 0.25/0.5Gi, 0.5/1.0Gi, 1.0/2.0Gi…, max 4.0/8.0Gi; Consumption-only environments are capped at 2 cores/4Gi)
--min-replicas / --max-replicasReplica range; with min 0 the app scales to zero when idle (with cold starts)
--env-varsEnvironment variables; secretref: references a secret (Module 4)

When: health probes

With ingress enabled, if you don't define probes the platform adds default TCP probes to the main container (startup probe: once per second, up to about 240 seconds; readiness probe: 3 s initial delay, every 5 s, failure threshold 48). Limits: only one probe of each type; exec probes are not supported (so the image HEALTHCHECK is not used); HTTP probes treat 200–399 as success. In production, explicitly configure HTTP probes pointing at /healthz (probes in the YAML).

User browserhttps://FQDN Envoy ingress443 → target 5000 Replica (myapp:1.1)gunicorn 0.0.0.0:50000.5 vCPU / 1.0Giprobes → /healthz id-myapp (UAMI)AcrPull @ ACR ACRmyapp:1.1 Pull: UAMI is exchanged for an ACR token

Deployment flow animation

CPU / memory combination validator

CommandDescription
az containerapp env create -g $RG -n $ENV -l $LOCCreate an environment (Log Analytics is created automatically)
az identity create -g $RG -n $ID_NAMECreate a user-assigned managed identity
az role assignment create --assignee-object-id … --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_IDGrant pull permission
az containerapp create …Create the app (see the lab)
az containerapp show -g $RG -n $APP --query properties.configuration.ingress.fqdn -o tsvGet the FQDN
az containerapp update -g $RG -n $APP --image … --cpu 1.0 --memory 2.0GiUpdate (creates a new revision)
az containerapp show -g $RG -n $APP -o yaml > app.yamlExport YAML; after editing, run az containerapp update --yaml app.yaml
az containerapp replica list -g $RG -n $APP -o tableList replicas
az containerapp exec -g $RG -n $APP --command shOpen a shell in a running replica (troubleshooting)

Lab 3: deploy myapp (about 10 min)

Environment and managed identity
source ~/hour3.env
az containerapp env create -g $RG -n $ENV -l $LOC -o table
az identity create -g $RG -n $ID_NAME -o table
ID_ID=$(az identity show -g $RG -n $ID_NAME --query id -o tsv)
ID_PRINCIPAL=$(az identity show -g $RG -n $ID_NAME --query principalId -o tsv)
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment create --assignee-object-id $ID_PRINCIPAL \
  --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_ID -o table
printf 'export ID_ID=%s\nexport ID_PRINCIPAL=%s\nexport ACR_ID=%s\n' "$ID_ID" "$ID_PRINCIPAL" "$ACR_ID" >> ~/hour3.env
Create the app (there is no Redis yet, so the page shows N/A)
az containerapp create -g $RG -n $APP --environment $ENV \
  --image $ACR.azurecr.io/myapp:1.1 \
  --user-assigned $ID_ID \
  --registry-server $ACR.azurecr.io --registry-identity $ID_ID \
  --target-port 5000 --ingress external \
  --cpu 0.5 --memory 1.0Gi \
  --min-replicas 1 --max-replicas 5 \
  --env-vars APP_VERSION=1.1 \
  --revision-suffix v11 -o table
FQDN=$(az containerapp show -g $RG -n $APP --query properties.configuration.ingress.fqdn -o tsv)
echo "export FQDN=$FQDN" >> ~/hour3.env
curl -s https://$FQDN/; curl -s https://$FQDN/healthz; echo
[1.1] Hello from myapp--v11-6d9f8c7b5-x2k4p, hits=N/A (redis is not connected)
ok

Role assignments can take a few minutes to take effect; if the first attempt fails to pull the image, wait and retry with az containerapp update -g $RG -n $APP --revision-suffix v11b.

Configure HTTP probes (export YAML → edit → update)
az containerapp show -g $RG -n $APP -o yaml > app.yaml
python3 - <<'EOF'
import yaml
d = yaml.safe_load(open("app.yaml"))
c = d["properties"]["template"]["containers"][0]
c["probes"] = [
  {"type": "Startup",   "httpGet": {"path": "/healthz", "port": 5000}, "periodSeconds": 2, "failureThreshold": 30},
  {"type": "Readiness", "httpGet": {"path": "/healthz", "port": 5000}, "periodSeconds": 5},
  {"type": "Liveness",  "httpGet": {"path": "/healthz", "port": 5000}, "periodSeconds": 10, "failureThreshold": 3},
]
d["properties"]["template"]["revisionSuffix"] = "v11p"
yaml.safe_dump(d, open("app.yaml", "w"), sort_keys=False)
EOF
az containerapp update -g $RG -n $APP --yaml app.yaml -o table
az containerapp revision list -g $RG -n $APP -o table

Requires PyYAML (sudo apt install -y python3-yaml). You can also configure this in the portal under "Containers → Health probes".

List replicas and run a command in the container
az containerapp replica list -g $RG -n $APP -o table
az containerapp exec -g $RG -n $APP --command "python -c 'import os;print(os.environ[\"APP_VERSION\"])'"

Case 1: cold starts and min-replicas

To save money, a team set --min-replicas 0, and the first request then took more than 10 seconds (image pull + startup + readiness). Set user-facing APIs to min-replicas ≥ 1 (critical services ≥ 2, in an environment spread across availability zones); only internal async jobs should scale to zero.

Case 2: probes kept a bad release out of production

One release's image was missing an environment variable: the app started but /healthz returned 500. Because an HTTP readiness probe was configured, the new revision never became ready, traffic was not switched in single-revision mode, and the old version in production was unaffected. Without explicit probes, the default TCP probe only checks that the port accepts connections, and the bad version would have received traffic.

Failed to provision revision … ImagePullBackOff / unauthorized

The managed identity lacks AcrPull, the role assignment hasn't taken effect yet, the image tag doesn't exist, or --registry-server is wrong. See the troubleshooting steps in Module 6.

InvalidContainerResources / The total requested CPU and memory resources … is invalid

CPU/memory is not a valid combination (e.g. 0.5 + 2Gi). Use values from the combination table, or check with the validator on the "Animation" tab.

FQDN returns upstream connect error / connection refused

--target-port doesn't match the app's listening port, or the app listens only on 127.0.0.1.

The revision stays in Activating / Provisioning

The startup or readiness probe is failing; look for probe failed messages in the system logs (Module 6) and increase failureThreshold if appropriate.

or score ≥ 70% on the Quiz

Module 4 · Configuration, secrets and stateful dependencies (Redis)

24:00 – 32:00 · Keep secrets in Key Vault and reference them instead of copying; hand state to a managed service
8 minsecretref · keyvaultrefAzure Managed Redis
Learning objectives
  • Tell environment variables, Container Apps secrets and Key Vault references apart, and know when each update takes effect.
  • Deploy an internal TCP service (Redis for the lab) in the same environment and understand how apps reach each other by name.
  • Know Azure Managed Redis for production and the Azure Cache for Redis retirement timeline.

What: three configuration sources

SourceSyntaxAfter a change
Plain environment variable--env-vars KEY=valueRevision scope: creates a new revision
Container Apps secret--secrets name=value + KEY=secretref:nameApplication scope: no new revision; containers only see the new value after you restart the revision or deploy a new one
Key Vault referencename=keyvaultref:<URI>,identityref:<UAMI ID>Without a version in the URI, the latest version is fetched within 30 minutes and active revisions that reference it are restarted automatically; with a version, you are fully in control

Secrets can also be mounted as files (--secret-volume-mount /mnt/secrets). Note: built-in roles such as Container Apps Contributor/Operator include listSecrets and can read secret values in plain text, so review them before assigning (official docs, updated 2026-09).

Why: Key Vault references beat storing values directly

  • Official guidance: "Avoid specifying the value of a secret directly in a production environment."
  • Centralized rotation, auditing and access control; the app holds only a reference. The identity needs the Key Vault Secrets User role on the vault.

How: where to run Redis

OptionNotesBest for
Internal TCP app in the environment (redis image)--ingress internal --transport tcp --target-port 6379; apps in the same environment connect to redis:6379. No durability guarantee, no high availabilityThis lab, dev/test
Azure Managed RedisManaged, highly available, TLS, supports Microsoft Entra ID authentication; cluster mode by default, so confirm client compatibility (or pick a suitable clustering policy)Production
Azure Cache for RedisBeing retired: Basic/Standard/Premium retire on 2028-09-30, Enterprise/Enterprise Flash on 2027-03-31 (official FAQ, updated 2026-08)Existing workloads only; plan a migration to Managed Redis

When: what the app has to do

Cloud Redis usually needs a password (or an Entra ID token) and TLS; use the port shown in the portal. Module 2 already changed app.py to read REDIS_HOST/PORT/PASSWORD/SSL, so the same image switches between local Redis, internal ACA Redis and Managed Redis by changing environment variables only - this is exactly "separating configuration from code".

Key Vaultredis-password (versioned) id-myapp (UAMI)Key Vault Secrets User App myapp secrets: redis-password = keyvaultref:… env: REDIS_PASSWORD = secretref:redis-password env: REDIS_HOST = redis (internal TCP) or Managed Redis host name + TLS redis (ACA internal TCP)lab only · requirepass Azure Managed Redisproduction · TLS · Entra ID

Simulator: after a change, when does the container see the new value?

CommandDescription
az containerapp secret set -g $RG -n $APP --secrets name=valueSet/update a secret (no new revision)
az containerapp secret set … --secrets name=keyvaultref:<URI>,identityref:$ID_IDKey Vault reference
az containerapp secret list -g $RG -n $APP -o tableList secret names
az containerapp update … --set-env-vars KEY=secretref:nameEnvironment variable that references a secret
az containerapp revision restart -g $RG -n $APP --revision <name>Restart a revision so it reads new secrets
az containerapp create … --ingress internal --transport tcp --target-port 6379 --exposed-port 6379Internal TCP app
az keyvault create -g $RG -n $KV --enable-rbac-authorization trueCreate a Key Vault in RBAC mode
az keyvault secret set --vault-name $KV -n redis-password --value …Write a secret

Lab 4: internal Redis + Key Vault secret (about 8 min)

Create a Key Vault and store the password
source ~/hour3.env
az keyvault create -g $RG -n $KV -l $LOC --enable-rbac-authorization true -o table
ME=$(az ad signed-in-user show --query id -o tsv)
KV_ID=$(az keyvault show -n $KV --query id -o tsv)
az role assignment create --assignee $ME --role "Key Vault Secrets Officer" --scope $KV_ID -o none
az role assignment create --assignee-object-id $ID_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" --scope $KV_ID -o none
sleep 30   # wait for the role assignments to take effect
REDIS_PW=$(openssl rand -hex 16)
az keyvault secret set --vault-name $KV -n redis-password --value "$REDIS_PW" -o none
KV_URI=$(az keyvault secret show --vault-name $KV -n redis-password --query id -o tsv | sed 's#/[^/]*$##')
echo "export KV_URI=$KV_URI" >> ~/hour3.env; echo $KV_URI

KV_URI has the version stripped (it looks like https://kv-…/secrets/redis-password), so it automatically follows the latest version.

Deploy Redis with internal TCP ingress (it also reads the password from Key Vault)
az acr import -n $ACR --source docker.io/library/redis:7-alpine -t base/redis:7-alpine
az containerapp create -g $RG -n redis --environment $ENV \
  --image $ACR.azurecr.io/base/redis:7-alpine \
  --user-assigned $ID_ID --registry-server $ACR.azurecr.io --registry-identity $ID_ID \
  --secrets "redis-password=keyvaultref:$KV_URI,identityref:$ID_ID" \
  --env-vars REDIS_PASSWORD=secretref:redis-password \
  --command "sh" --args "-c" "exec redis-server --requirepass \"\$REDIS_PASSWORD\"" \
  --ingress internal --transport tcp --target-port 6379 --exposed-port 6379 \
  --cpu 0.25 --memory 0.5Gi --min-replicas 1 --max-replicas 1 -o table
Point myapp at Redis
az containerapp secret set -g $RG -n $APP --secrets "redis-password=keyvaultref:$KV_URI,identityref:$ID_ID"
az containerapp update -g $RG -n $APP --revision-suffix v11r \
  --set-env-vars REDIS_HOST=redis REDIS_PORT=6379 REDIS_SSL=false REDIS_PASSWORD=secretref:redis-password -o table
curl -s https://$FQDN/; curl -s https://$FQDN/
[1.1] Hello from myapp--v11r-…, hits=1
[1.1] Hello from myapp--v11r-…, hits=2
(Optional, production option, billed hourly) Azure Managed Redis

Create an Azure Managed Redis instance in the portal (pick the smallest size), note the host name, port (as shown in the portal) and access key (or configure Entra ID authentication), store the key in Key Vault, then:

az keyvault secret set --vault-name $KV -n redis-password --value "<Managed Redis access key>" -o none
az containerapp update -g $RG -n $APP --revision-suffix v11amr \
  --set-env-vars REDIS_HOST=<host name> REDIS_PORT=<port> REDIS_SSL=true

Managed Redis uses cluster mode by default, so confirm that your redis-py client usage is compatible with the chosen clustering policy; delete the instance as soon as you are done.

Case 1: key rotation causes an outage

The security team rotated the Redis key in Key Vault, but the app's secret reference used a versioned URI. Redis switched to the new key while the app kept the old one, and every request failed authentication. Improvement: reference the unversioned URI (auto-updated within 30 minutes, with a revision restart), and use "dual-key rotation" (move the app to the secondary key first, then regenerate the primary key).

Case 2: the Operator role could read secrets

On-call engineers were given the Container Apps Operator role on the assumption that it could only restart apps; an audit found that its wildcard permissions include listSecrets, which exposes every secret in plain text. Improvement: create a custom role without listSecrets (the official docs provide an example).

Key Vault reference: Authentication failed / RBAC permission denied

The identity lacks the Key Vault Secrets User role, the role has not taken effect yet, or the identity is not assigned to the app (--user-assigned).

The secret was updated but the app still uses the old value

Changing a Container Apps secret does not create a new revision: run az containerapp revision restart or deploy a new revision. Key Vault references can take up to 30 minutes to sync.

hits=N/A, logs show NOAUTH Authentication required / Connection refused

The password is not passed in (check the secretref: name), REDIS_HOST/PORT is wrong, or the Redis app's ingress is not TCP. Use az containerapp exec -n $APP --command sh and test the connection from Python.

System assigned identity can't be used with the create command

At create time, Key Vault references can only use a user-assigned identity; alternatively create the app first, enable the system identity, grant it access, then add the secret with secret set.

Note No verifiable video covering Key Vault references and Managed Redis was found.
or score ≥ 70% on the Quiz

Module 5 · Revisions, traffic splitting, rollback and scaling

32:00 – 40:00 · Every release can be canaried, rolled back and scaled elastically
8 minsingle / multiple / labels(preview)KEDA HTTP rule
Learning objectives
  • Distinguish revision-scope (template) changes from application-scope (configuration) changes.
  • Run a 90/10 canary, test through a label URL and roll back in seconds in multiple-revision mode.
  • Configure an HTTP concurrency scale rule and watch replicas change under load.

What: which changes create a new revision

Revision scope (creates a new revision)Application scope (no new revision, applies to all revisions)
Image, container settings, environment variables, resources, scale rules, revision suffixSecret values, revision mode, ingress, traffic splitting, labels, registry credentials, Dapr settings

Why: three revision modes

ModeBehaviorBest for
single (default)Once the new revision is ready it takes all traffic and the old one is deactivated automatically; if the update fails, traffic stays on the old revisionMost services
multipleSeveral revisions active at once; you split traffic and deactivate revisions manuallyCanary, blue/green, A/B
Deployment labels (preview)Organize revisions with labels such as dev/staging/prod; supports traffic splitting and simplified rollbackRelease flows managed by environment labels

Revision names follow <app name>--<suffix>; up to 100 inactive revisions are kept (configurable), they are not billed and can be reactivated at any time. Revision states include Provisioning, Running, Degraded and Failed (for example exit code 137).

How: label URLs

After you add a label (for example green) to a revision, that revision gets its own URL (of the form <app>---green.<environment domain>; check the az containerapp show output for the exact value). Testers can hit it directly without taking production traffic. A label can be moved to another revision and the URL stays the same.

When: scale rules

  • Default HTTP rule: scales on concurrent requests (set it with --scale-rule-http-concurrency).
  • Other KEDA rules: Service Bus/Storage queue length, Event Hubs, Kafka, CPU/memory, cron and more.
  • Scale rules are revision-scoped: changing them creates a new revision.
Canary release in four steps (multiple mode) ① Deploy v12v11=100% · v12=0% ② Test via label greenopen the ---green URL ③ 10% canarywatch errors and latency ④ Full rollout / rollbackv12=100% or v11=100% Rollback just changes traffic weights (application scope): seconds, no redeploy Rollback in single mode: update back to the previous image tag (creates a new revision)

Traffic splitting simulator

CommandDescription
az containerapp revision list -g $RG -n $APP -o tableList revisions (with traffic and status)
az containerapp revision set-mode -g $RG -n $APP --mode multipleSwitch revision mode
az containerapp update … --image … --revision-suffix v12Release a new revision with a given suffix
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $APP--v11=90 $APP--v12=10Split traffic by revision
az containerapp revision label add -g $RG -n $APP --label green --revision $APP--v12Add a label (gets its own URL)
az containerapp ingress traffic set … --label-weight blue=80 green=20Split traffic by label
az containerapp revision deactivate / activate / restart --revision …Deactivate / activate / restart a revision
az containerapp update … --scale-rule-name http --scale-rule-type http --scale-rule-http-concurrency 10HTTP concurrency scale rule

Lab 5: canary, label, rollback, scale-out (about 8 min)

Switch to multiple-revision mode and release v12 (0% traffic at first)
source ~/hour3.env
cd ~/myapp && az acr build -r $ACR -t myapp:1.2 --no-logs .
az containerapp revision set-mode -g $RG -n $APP --mode multiple
OLD=$(az containerapp revision list -g $RG -n $APP --query "[?properties.active].name | [-1]" -o tsv); echo $OLD
az containerapp update -g $RG -n $APP --image $ACR.azurecr.io/myapp:1.2 \
  --set-env-vars APP_VERSION=1.2 --revision-suffix v12 -o none
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $OLD=100 $APP--v12=0 -o table
Test v12 internally through the label URL
az containerapp revision label add -g $RG -n $APP --label green --revision $APP--v12 -o none
az containerapp show -g $RG -n $APP --query "properties.configuration.ingress.traffic" -o json
GREEN=$(echo $FQDN | sed "s/^$APP\./$APP---green./"); curl -s https://$GREEN/
[1.2] Hello from myapp--v12-…, hits=3

For the exact label URL format, go by az containerapp show or "Revision management" in the portal.

10% canary and version distribution
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $OLD=90 $APP--v12=10 -o none
for i in $(seq 50); do curl -s https://$FQDN/ | cut -d']' -f1; done | sort | uniq -c
     45 [1.1
      5 [1.2
Rollback in seconds / full rollout
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $OLD=100 $APP--v12=0 -o none   # rollback
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $APP--v12=100 -o none          # full rollout
az containerapp revision deactivate -g $RG -n $APP --revision $OLD
HTTP scale rule + load test
az containerapp update -g $RG -n $APP --revision-suffix v12s \
  --min-replicas 1 --max-replicas 5 \
  --scale-rule-name http --scale-rule-type http --scale-rule-http-concurrency 5 -o none
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $APP--v12s=100 -o none
seq 3000 | xargs -P 50 -I{} curl -s -o /dev/null https://$FQDN/ &
sleep 45; az containerapp replica list -g $RG -n $APP --revision $APP--v12s --query "length(@)"
wait

Expect the replica count to grow from 1 to several; a few minutes after the load test ends it scales back to min-replicas.

Case: automated canary releases

The team built this into its pipeline: deploy a new revision (0% traffic) → run smoke tests against the label URL → send 10% of traffic and watch for 15 minutes (Application Insights error rate, P95 latency) → automatically promote or roll back. Rollback only changes weights, so mean time to recovery dropped from 20 minutes to under 1 minute. Hour 5 turns this into an image CI pipeline with automated canary and rollback.

Counter-example: "rolling back" in single-revision mode

An on-call engineer tried to roll back by running traffic set in single mode and got an error. In single mode you roll back by running az containerapp update with the old image tag - which is why images must use immutable tags and old tags must not be removed by purge (the locks from Module 2).

traffic set fails: revision mode is single

Run az containerapp revision set-mode --mode multiple first.

Traffic weights must add up to 100

All weights in --revision-weight must sum to 100.

Error rate rises once the new revision gets traffic, yet the revision shows Running

The default TCP probe only checks the port; configure an HTTP readiness probe and smoke-test through the label URL before a full rollout.

Replicas don't increase during a load test

Traffic is going to an old revision without the scale rule, max-replicas is too small, or the concurrency threshold is too high. Make sure the revision that has the rule is receiving traffic.

or score ≥ 70% on the Quiz

Module 6 · Troubleshooting in practice: 4 local failures + 6 cloud failures

40:00 – 50:00 · Read the logs first, then change the configuration
10 minSystem logs · Console logs · KQL
Learning objectives
  • Locally: use the four-step method "ps -a → logs → inspect → exec" to pinpoint OOM, wrong listen address, restart loops and network isolation.
  • In the cloud: tell system logs from console logs, and use the CLI, the portal and KQL to diagnose image pull, architecture, port, probe, secret and OOM problems.

Local vs. cloud tools

LocalContainer AppsWhat to look at
docker ps -aaz containerapp revision list / replica listStatus, restart count
docker logsaz containerapp logs show --type console (default)App stdout/stderr
docker eventsaz containerapp logs show --type systemPlatform events: image pull, startup, probe failures, restarts, OOM
docker inspectaz containerapp show -o yamlEffective configuration
docker execaz containerapp execShell into a replica
—Log Analytics: ContainerAppConsoleLogs_CL, ContainerAppSystemLogs_CLHistorical queries, aggregation, alerts
—Portal: Log stream, Revisions, Diagnose and solve problemsVisual view

KQL examples (from the official docs)

ContainerAppSystemLogs_CL
| where ContainerAppName_s == 'myapp'
| project Time=TimeGenerated, Revision=RevisionName_s, Message=Log_s
| order by Time desc
| take 50
ContainerAppConsoleLogs_CL
| where ContainerAppName_s == 'myapp' and Log_s has "Traceback"
| project TimeGenerated, RevisionName_s, ContainerGroupName_g, Log_s
# Run KQL from the CLI
WS=$(az containerapp env show -g $RG -n $ENV --query properties.appLogsConfiguration.logAnalyticsConfiguration.customerId -o tsv)
az monitor log-analytics query --workspace $WS --analytics-query "ContainerAppSystemLogs_CL | take 20" -o table
Revision state?revision list Provisioning failed→ system logs: pull/arch/resources Failed / Degraded→ console logs + exit code/probes Running, but errors → target-port / 0.0.0.0 / traffic weights / secret values / dependencies (test via exec)

Cloud failure drills (6 scenarios)

CommandDescription
az containerapp logs show -g $RG -n $APP --followStream console logs
az containerapp logs show -g $RG -n $APP --type system --tail 50Platform events
az containerapp logs show … --revision R --replica X --container CTarget a specific replica/container
az containerapp revision show -g $RG -n $APP --revision R --query propertiesRevision health and running state
az containerapp exec -g $RG -n $APP --command shShell into a replica
az role assignment list --assignee $ID_PRINCIPAL --all -o tableCheck the identity's roles
az acr repository show-tags -n $ACR --repository myapp -o tableConfirm the tag exists
docker buildx imagetools inspect $ACR.azurecr.io/myapp:TAGConfirm the image platform

Lab 6A: four local failures (about 4 min)

OOM
docker run --name oom --memory 20m --memory-swap 20m python:3.13-slim python -c "a = ' ' * 200_000_000"
docker inspect oom --format 'ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}'; docker rm oom
ExitCode=137 OOMKilled=true
Port is mapped but unreachable
docker build -q -t myapp:local ~/myapp
docker run -d --name bad -p 5001:5000 myapp:local gunicorn -b 127.0.0.1:5000 app:app
curl -s localhost:5001 || echo "Connection failed: the app only listens on 127.0.0.1"; docker rm -f bad
Restart loop: read the logs first
docker run -d --name loop --restart unless-stopped myapp:local gunicorn -b 0.0.0.0:5000 wrong:app
sleep 5; docker ps --filter name=loop --format '{{.Status}}'
docker logs loop 2>&1 | grep -m1 ModuleNotFoundError; docker rm -f loop
Restarting (3) 1 second ago
ModuleNotFoundError: No module named 'wrong'
Containers on different networks
docker network create net1; docker network create net2
docker run -d --name redis --network net1 redis:7-alpine
docker run -d --name web --network net2 -p 5000:5000 -e REDIS_HOST=redis myapp:local
sleep 2; curl -s localhost:5000                   # hits=N/A
docker network connect net1 web; curl -s localhost:5000   # hits=1
docker rm -f web redis; docker network rm net1 net2

Lab 6B: break and fix things on Container Apps (about 6 min)

Wrong image tag
source ~/hour3.env
az containerapp update -g $RG -n $APP --image $ACR.azurecr.io/myapp:9.9 --revision-suffix bad1 -o none
az containerapp revision list -g $RG -n $APP --query "[].{name:name,health:properties.healthState,state:properties.runningState}" -o table
az containerapp logs show -g $RG -n $APP --type system --tail 20 | grep -iE "pull|manifest|error" | tail -5

In multiple-revision mode, a failed new revision does not affect existing traffic. Fix: az containerapp revision deactivate --revision $APP--bad1.

Wrong target-port
az containerapp ingress update -g $RG -n $APP --target-port 8080 -o none
curl -s -o /dev/null -w "%{http_code}\n" https://$FQDN/         # not 200
az containerapp ingress update -g $RG -n $APP --target-port 5000 -o none
curl -s https://$FQDN/

Ingress is application-scoped, so the change applies to all revisions immediately.

Architecture mismatch (common for Apple Silicon users)
docker buildx build --platform linux/arm64 -t $ACR.azurecr.io/myapp:arm-only --push ~/myapp
az containerapp update -g $RG -n $APP --image $ACR.azurecr.io/myapp:arm-only --revision-suffix bad2 -o none
sleep 60; az containerapp logs show -g $RG -n $APP --revision $APP--bad2 --tail 5
az containerapp revision deactivate -g $RG -n $APP --revision $APP--bad2
exec /usr/local/bin/docker-entrypoint.sh: exec format error

To build arm64 on an amd64 VM you first need QEMU installed as in Lesson 2 (tonistiigi/binfmt). The fix is to build an amd64 or multi-platform image, or use az acr build.

Case: one KQL alert uncovers "invisible" restarts

The service looked healthy, but users occasionally hit 502s. Querying the system logs showed one revision restarting a dozen times an hour: memory grew slowly until the container was OOM-killed (exit code 137). The team configured Log Analytics alerts on restart count / OOM, raised memory from 1Gi to 2Gi, and fixed a cache that had no size limit. For systematic metrics and alerting, see the Prometheus & Grafana course (Chinese).

SymptomCheck firstCommon causes
Revision Provisioning failedSystem logsTag doesn't exist, no AcrPull, role not yet effective, invalid resource combination
Failed, exit code 137System logs + memory settingOOM
exec format errorConsole logs, imagetoolsarm64 image
Running but 502/503/timeoutsIngress configurationWrong target-port, listening on 127.0.0.1, weight sent to a bad revision
Activating for a long timeProbe events in system logsSlow startup, wrong probe path/port
Broken functionality (hits=N/A)exec in and test dependenciesWrong secret value, wrong REDIS_HOST, internal ingress not TCP
or score ≥ 70% on the Quiz

Module 7 · Moving on to Kubernetes: kind and AKS

50:00 – 57:00 · Same image, different orchestrator
7 minkind v0.33.0AKS --attach-acr
Learning objectives
  • Map Compose/ACA concepts to Deployment, Service, ConfigMap, Secret, Probe and Resources.
  • Deploy myapp + redis to a local kind cluster and perform a rolling update and rollback.
  • Understand how AKS pulls ACR images via --attach-acr.

Concept mapping

Docker / ComposeContainer AppsKubernetes
ContainerContainerContainer in a Pod
Compose serviceAppDeployment (runs and manages Pods) + Service (stable address)
Image tag / new versionRevisionReplicaSet (one per Deployment version)
environment--env-varsConfigMap
secretssecrets / Key Vault referencesSecret (or the Key Vault CSI driver)
healthcheckProbesstartup / readiness / liveness Probe
--memory / --cpus--cpu / --memoryresources.requests / limits
Named volumeAzure Files volumePersistentVolumeClaim
restart policyHandled by the platformController maintains the replica count
portsingressService (ClusterIP/LoadBalancer) + Ingress / Gateway
--scaleScale rules (KEDA)replicas / HPA / KEDA

Why: kind

kind (Kubernetes IN Docker) runs each Kubernetes node as a Docker container, which makes it ideal for local learning and CI tests. Images must be loaded into the nodes with kind load docker-image or pulled from a registry. As the official docs note, the :latest tag defaults to imagePullPolicy: Always, so loaded images may be ignored; use explicit tags or IfNotPresent.

How: rolling updates

Changing a Deployment's image creates a new ReplicaSet and replaces Pods gradually according to maxSurge/maxUnavailable. Only Pods that pass the readinessProbe receive traffic, and kubectl rollout undo switches back to the previous ReplicaSet.

When: AKS

az aks create … --attach-acr $ACR grants AcrPull to the cluster's kubelet identity. For an existing cluster use az aks update --attach-acr. AKS bills by node VM, so delete it right after the lab.

Service myappport 80 → 5000 Deployment myapp (replicas: 2) ReplicaSet v1.1Pod · Pod ReplicaSet v1.2rolling out envFrom: ConfigMap myapp-config · Secret myapp-secret readiness/liveness → /healthz · requests/limits Service redisDeployment redis

Compose → Kubernetes mapper

Click a Compose field on the left to highlight the matching Kubernetes configuration on the right.

CommandDescription
kind create cluster --name lab / kind delete cluster --name labCreate / delete a local cluster
kind load docker-image myapp:1.1 --name labLoad a local image into the nodes
kubectl apply -f k8s.yamlDeclarative deployment
kubectl get pods -o wide / kubectl get allList resources
kubectl describe pod <pod>Events (most useful for troubleshooting)
kubectl logs deploy/myapp / -f / --previousLogs (--previous shows the last crash)
kubectl port-forward svc/myapp 8080:80Forward to localhost for testing
kubectl set image deploy/myapp web=myapp:1.2 + kubectl rollout statusRolling update
kubectl rollout undo deploy/myapp / rollout historyRollback / history
kubectl create secret generic myapp-secret --from-literal=REDIS_PASSWORD=xxxCreate a Secret
kubectl exec -it deploy/myapp -- shShell into the container
kompose convert -f compose.yamlConvert Compose to K8s manifests (a starting point; needs manual polishing)
az aks create -g $RG -n aks-lab --node-count 1 --attach-acr $ACR --generate-ssh-keysCreate AKS and grant AcrPull
az aks get-credentials -g $RG -n aks-labGet the kubeconfig

Lab 7: deploy myapp on kind (about 7 min)

Install kind and kubectl, create a cluster
[ $(uname -m) = x86_64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.33.0/kind-linux-amd64
chmod +x ./kind && sudo mv ./kind /usr/local/bin/kind
sudo az aks install-cli        # installs kubectl (snap or the official binary also work)
kind create cluster --name lab
kubectl get nodes
Load the image
cd ~/myapp
docker build -q -t myapp:1.1 .
kind load docker-image myapp:1.1 --name lab || {
  docker image save --platform linux/amd64 myapp:1.1 -o /tmp/myapp.tar && kind load image-archive /tmp/myapp.tar --name lab; }

With the containerd image store, if kind load docker-image fails with an error such as content digest not found, use docker image save --platform + kind load image-archive instead (the command above falls back automatically).

Write and apply k8s.yaml
apiVersion: v1
kind: ConfigMap
metadata: { name: myapp-config }
data:
  REDIS_HOST: redis
  APP_VERSION: "1.1"
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: redis }
spec:
  replicas: 1
  selector: { matchLabels: { app: redis } }
  template:
    metadata: { labels: { app: redis } }
    spec:
      containers:
        - name: redis
          image: redis:7-alpine
          ports: [{ containerPort: 6379 }]
---
apiVersion: v1
kind: Service
metadata: { name: redis }
spec:
  selector: { app: redis }
  ports: [{ port: 6379 }]
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp }
spec:
  replicas: 2
  selector: { matchLabels: { app: myapp } }
  template:
    metadata: { labels: { app: myapp } }
    spec:
      securityContext: { runAsNonRoot: true }
      containers:
        - name: web
          image: myapp:1.1
          imagePullPolicy: IfNotPresent
          ports: [{ containerPort: 5000 }]
          envFrom: [{ configMapRef: { name: myapp-config } }]
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits:   { cpu: 500m, memory: 256Mi }
          readinessProbe: { httpGet: { path: /healthz, port: 5000 }, initialDelaySeconds: 3, periodSeconds: 5 }
          livenessProbe:  { httpGet: { path: /healthz, port: 5000 }, initialDelaySeconds: 10, periodSeconds: 10 }
          securityContext:
            allowPrivilegeEscalation: false
            capabilities: { drop: ["ALL"] }
---
apiVersion: v1
kind: Service
metadata: { name: myapp }
spec:
  selector: { app: myapp }
  ports: [{ port: 80, targetPort: 5000 }]
cat > k8s.yaml      # paste the content above, then Ctrl+D
kubectl apply -f k8s.yaml
kubectl rollout status deploy/myapp
kubectl port-forward svc/myapp 8080:80 & sleep 2
curl -s localhost:8080; curl -s localhost:8080

runAsNonRoot requires the image to run as non-root (the Lesson 1 5B Dockerfile uses USER appuser). If the image's USER is a name rather than a numeric UID, Kubernetes cannot verify it and refuses to start the container. In that case use a numeric UID in the image (for example USER 10001:10001 from the Lesson 2 capstone lab), or set runAsUser: 10001 in the Pod.

Rolling update and rollback
sed -i 's/Hello from/Hi from/' app.py; docker build -q -t myapp:1.2 . && kind load docker-image myapp:1.2 --name lab
kubectl set image deploy/myapp web=myapp:1.2 && kubectl rollout status deploy/myapp
curl -s localhost:8080
kubectl rollout undo deploy/myapp && kubectl rollout status deploy/myapp
kubectl rollout history deploy/myapp
sed -i 's/Hi from/Hello from/' app.py
(Optional, billed hourly) AKS
source ~/hour3.env
az aks create -g $RG -n aks-lab --node-count 1 --attach-acr $ACR --generate-ssh-keys
az aks get-credentials -g $RG -n aks-lab
sed "s#image: myapp:1.1#image: $ACR.azurecr.io/myapp:1.1#" k8s.yaml | kubectl apply -f -
kubectl get pods -w
az aks delete -g $RG -n aks-lab --yes --no-wait      # delete as soon as you're done
Clean up
kill %1 2>/dev/null; kind delete cluster --name lab

Case: when to move from ACA to AKS

A team started with every service on Container Apps. A year later they needed a data platform component that depends on an Operator (custom resources) and a node-level security agent that requires a DaemonSet. These went beyond what ACA offers, so they introduced AKS for just those workloads; the remaining APIs stayed on ACA. The fundamentals (images, probes, resource settings, non-root) carried over directly, which is exactly why the first two lessons stress standardizing images and configuration.

ErrImagePull / ImagePullBackOff (kind)

The image was not loaded into the kind nodes, or :latest is used so it always pulls from a remote registry. Load the image and set imagePullPolicy: IfNotPresent.

CreateContainerConfigError: container has runAsNonRoot and image has non-numeric user

The image USER is a name. Switch to a numeric UID, or set runAsUser in the Pod.

CrashLoopBackOff

Use kubectl logs --previous to see the output of the last crash, and kubectl describe pod to see the exit code and OOMKilled.

Pod Running but 0/1 Ready

The readinessProbe is failing: wrong path/port or the app isn't ready yet. The Events in kubectl describe pod show Readiness probe failed.

or score ≥ 70% on the Quiz

Module 8 · Cost, cleanup and self-check

57:00 – 60:00 · Delete it when you're done, so the lab doesn't turn into a bill
3 minCost
Learning objectives
  • Know how each resource in this lesson is billed and where the main costs come from.
  • Clean up all resources completely, keeping only what you need for hour 5 (ACR and the Container Apps environment).
ResourceBilling model (summary)How to reduce cost
Container Apps (Consumption)Billed by replica vCPU-seconds, GiB-seconds and requests, with a monthly free grantmin-replicas 0 for non-user-facing services; right-sized resource combinations
Container Apps (Dedicated profiles)Billed per node of the workload profileUse only when you need dedicated hardware/GPUs
ACRDaily charge per SKU + storage overageClean up with purge; use Basic for development
Log AnalyticsBilled by data ingestion volumeControl log volume, set retention, sample
Key VaultBilled per operationUsually very low
AKS / Managed RedisBilled hourly by node VM / instance sizeDelete right after the lab

For actual prices, check the Azure pricing pages and calculator; they vary by region and over time.

AKS / Managed RedisMost expensive: delete now ACA replicas / ACR SKUAccrues over time Log AnalyticsBy log volume az group deleteDeletes everything at once
NoteThis module has no animation. Go straight to the cleanup in the "Lab" tab and check yourself in the "Quiz" tab.
az resource list -g $RG -o table            # confirm before deleting
az group delete -n $RG --yes --no-wait
az keyvault list-deleted -o table            # Key Vault uses soft delete by default
az keyvault purge -n $KV                     # permanently delete if needed (irreversible)

Lab 8: Cleanup

Hour 5 builds on thisHour 5 reuses this lesson's ACR and Container Apps environment (and hour 4's ECR and ECS). If you plan to start hour 5 right away, keep the resource group and delete only the hourly-billed resources such as AKS and Managed Redis; if you already deleted them, hour 5's setup gives minimal rebuild steps.
source ~/hour3.env
az aks delete -g $RG -n aks-lab --yes --no-wait 2>/dev/null
az resource list -g $RG -o table
# When you no longer need it:
az group delete -n $RG --yes --no-wait

Case: the weekend bill

After a training session, attendees didn't delete their AKS clusters and Premium ACRs, and a month later the bill was several hundred dollars. Improvement: tag lab resource groups with expires, delete expired resource groups with Azure Automation / a scheduled job, and set budget alerts on the subscription.

Re-creating a Key Vault with the same name fails: already exists (soft deleted)

Key Vault uses soft delete by default. Restore it with az keyvault recover -n $KV, or delete it permanently with az keyvault purge (if purge protection is not enabled).

Resource group deletion is slow

Deleting an ACA environment or AKS takes several minutes to over ten minutes. Use --no-wait and check later with az group exists -n $RG.

or score ≥ 70% in the "Quiz" tab

Command cheat sheet (Hour 3)

Azure CLI containerapp extension · ACR · Key Vault · kind/kubectl · AKS

Setup

az extension add --name containerapp --upgrade
az provider register --namespace Microsoft.App
az provider register --namespace Microsoft.OperationalInsights
source ~/hour3.env

ACR

az acr create -g $RG -n $ACR --sku Basic
az acr build -r $ACR -t myapp:1.1 .
az acr repository show-tags -n $ACR --repository myapp --detail -o table
az acr repository update -n $ACR --image myapp:1.1 --write-enabled false --delete-enabled false
az acr run -r $ACR --cmd "acr purge --filter 'myapp:sha-.*' --ago 30d --keep 20 --untagged --dry-run" /dev/null
az acr import -n $ACR --source docker.io/library/redis:7-alpine -t base/redis:7-alpine

Environment · identity · deployment

az containerapp env create -g $RG -n $ENV -l $LOC
az identity create -g $RG -n $ID_NAME
az role assignment create --assignee-object-id $ID_PRINCIPAL --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_ID
az containerapp create -g $RG -n $APP --environment $ENV --image $ACR.azurecr.io/myapp:1.1 \
  --user-assigned $ID_ID --registry-server $ACR.azurecr.io --registry-identity $ID_ID \
  --target-port 5000 --ingress external --cpu 0.5 --memory 1.0Gi --min-replicas 1 --max-replicas 5
az containerapp show -g $RG -n $APP --query properties.configuration.ingress.fqdn -o tsv
az containerapp show -g $RG -n $APP -o yaml > app.yaml; az containerapp update -g $RG -n $APP --yaml app.yaml

Configuration and secrets

az containerapp secret set -g $RG -n $APP --secrets "redis-password=keyvaultref:$KV_URI,identityref:$ID_ID"
az containerapp update -g $RG -n $APP --set-env-vars REDIS_PASSWORD=secretref:redis-password
az containerapp revision restart -g $RG -n $APP --revision <rev>
az containerapp create … --ingress internal --transport tcp --target-port 6379 --exposed-port 6379

Revisions · traffic · scaling

az containerapp revision list -g $RG -n $APP -o table
az containerapp revision set-mode -g $RG -n $APP --mode multiple
az containerapp update -g $RG -n $APP --image … --revision-suffix v12
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $APP--v11=90 $APP--v12=10
az containerapp revision label add -g $RG -n $APP --label green --revision $APP--v12
az containerapp revision deactivate -g $RG -n $APP --revision $APP--v11
az containerapp update … --scale-rule-name http --scale-rule-type http --scale-rule-http-concurrency 10

Troubleshooting

az containerapp logs show -g $RG -n $APP --follow
az containerapp logs show -g $RG -n $APP --type system --tail 50
az containerapp replica list -g $RG -n $APP -o table
az containerapp exec -g $RG -n $APP --command sh
az monitor log-analytics query --workspace $WS --analytics-query "ContainerAppSystemLogs_CL | take 20" -o table

Kubernetes

kind create cluster --name lab; kind load docker-image myapp:1.1 --name lab
kubectl apply -f k8s.yaml; kubectl get pods -o wide; kubectl describe pod <pod>
kubectl logs deploy/myapp --previous; kubectl port-forward svc/myapp 8080:80
kubectl set image deploy/myapp web=myapp:1.2; kubectl rollout status deploy/myapp; kubectl rollout undo deploy/myapp
az aks create -g $RG -n aks-lab --node-count 1 --attach-acr $ACR --generate-ssh-keys

Cleanup

az aks delete -g $RG -n aks-lab --yes --no-wait
kind delete cluster --name lab
az group delete -n $RG --yes --no-wait

Capstone lab + final exam

Complete an end-to-end cloud release from scratch
After class ≈ 40 min
TaskIn a new resource group, using only the CLI:
Create an ACR, build myapp:2.0 with az acr build, and lock that tag.
Create the environment, a user-assigned identity (AcrPull + Key Vault Secrets User), and a Key Vault holding the Redis password.
Deploy an internal TCP Redis and myapp (external ingress, 0.5/1.0Gi, HTTP probe /healthz, min 1 / max 5, HTTP concurrency scale rule).
Release myapp:2.1: multiple-revision mode → smoke test via label URL → 10% canary → full rollout.
Use KQL to query the last 30 minutes of system logs and find the creation and ready events for every revision.
Deploy the same image to kind and perform one rolling update and rollback.
Delete all resources.
Acceptance checklist

Open-ended self-check

1. Why is a custom bridge network better than the default bridge?

It has built-in DNS, so containers can reach each other by name (the default bridge only offers IPs, which change); it also isolates different apps, and containers can be connected/disconnected at runtime.

2. On Azure, how do you let an app pull ACR images securely?

A user-assigned managed identity + AcrPull (Repository Reader in ABAC mode) with --registry-identity; don't enable the admin account and don't store passwords.

3. A new Container Apps release is broken. How do you roll back quickly?

In multiple-revision mode, shift traffic back to the previous healthy revision (an application-scope operation, takes seconds); in single-revision mode, run update again with the old image tag.

4. A container is stuck in Restarting. What is the first step?

Read the logs first (docker logs / az containerapp logs show), then the exit code, to tell whether it is an application error, a wrong command, or OOM.

5. Which two Kubernetes resources does a Compose service map to?

A Deployment (runs and manages the Pods) and a Service (stable access address).

6. After changing a Container Apps secret, why does the app still use the old value?

Secrets are application-scoped and do not create a new revision; you must restart the revision or deploy a new one. An unversioned Key Vault reference syncs within 30 minutes and restarts automatically.

7. Why should the probe point to /healthz rather than / ?

"/" increments the Redis counter and depends on Redis; a health check should be cheap and check only the app itself. Container Apps doesn't support exec probes, and the image's HEALTHCHECK is not used.

Final exam (12 questions)

Sources and versions

Verified on: 2026-11-14
TopicVerified findingSource
CPU/memory combinationsFrom 0.25/0.5Gi, in steps of 0.25 vCPU : 0.5Gi up to 4.0/8.0Gi; Consumption-only environments are capped at 2 cores/4Gi; pulling with a managed identity requires acrPullContainers
Secretskeyvaultref/identityref syntax; unversioned references update within 30 minutes and restart the revision; changing a secret does not create a new revision; roles such as Operator include listSecretsManage secrets (2026-09-11)
Revisionssingle / multiple / Deployment labels (preview); revision scope vs. application scope; up to 100 inactive revisionsRevisions
Traffic splitting--revision-weight, --label-weightTraffic splitting
IngressExternal TCP requires a VNet environment; internal TCP is reached by app name + port within the environment; port 36985 is reservedIngress overview (2026-10-22)
ProbesDefault TCP probes; exec/gRPC not supported; HTTP 200–399 counts as successHealth probes
LogsContainerAppConsoleLogs_CL, ContainerAppSystemLogs_CL, ContainerAppHTTPLogsLog monitoring (2026-06-04)
RedisAzure Cache for Redis: Basic/Standard/Premium retire on 2028-09-30, Enterprise on 2027-03-31; Azure Managed Redis (clustered by default) is recommendedRetirement FAQ (2026-08-18)
ACR Artifact Cacheaz acr cache create; Docker Hub as a source requires a credential setArtifact cache CLI
kindv0.33.0 install command; :latest images are pulled with Always by defaultkind Quick Start

Relationship to docker-hour3-cloud-azure.ch.md

This lesson covers all 6 sections of that file (warm-up, networking and storage, ACR, Container Apps, hands-on troubleshooting, Kubernetes and self-check). Updates and additions:

  • Updated: region defaults to canadacentral (changeable); nginx:1.27 → nginx:alpine, python:3.12 → 3.13; the Redis section adds the Azure Cache for Redis retirement dates and cluster-mode considerations for Managed Redis; kind installation pinned to v0.33.0.
  • Corrected: probes now point to the newly added /healthz (the original pointed to "/", which increments the Redis counter and depends on Redis); app.py catches RedisError (the original caught only ConnectionError, so an authentication failure caused a 500); the OOM demo also sets --memory-swap.
  • Added: service selection, ACA architecture, ACR cloud builds/locks/purge rules/import/cache, user-assigned vs. system-assigned identities, CPU/memory combinations, default probes, Key Vault reference and rotation behavior, internal TCP Redis, revision scope vs. application scope, label URLs, HTTP scaling and load testing, system logs and KQL, cloud failure drills, securityContext in k8s.yaml, the fallback for loading images into kind with the containerd image store, cost and cleanup.

Video verification notes

Verified: TechWorld with Nana "Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]" (X48VuDVv0do, 3:36:55, 2020-11-06) and "Kubernetes Crash Course for Absolute Beginners [NEW]" (s_o8dwzRlu4, about 1 h 11 min); Microsoft Reactor "Kubernetes-Free Microservices: The Azure Container Apps Advantage" (Nom9JtjZ8Js, 2025-04-04, duration not verified). No verifiable videos were found on ACR governance or Key Vault references.

Known limitations

  • Lab commands are written from the official documentation and were not run one by one against a real subscription; expected outputs are examples.
  • The exact label URL format depends on CLI/portal output; Deployment labels mode is a preview feature.
  • No specific prices are listed; refer to the Azure pricing pages.