Docker Hour 3: To the Cloud (Azure)
- 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
| # | Time | Module | Core content | Animation / interactive | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up & Azure setup | Review network modes and volume backup; register resource providers; set variables | — | Local network/volume exercises |
| 1 | 00–05 | Choosing a cloud container service | ACI / ACA / AKS / App Service / VM compared; ACA architecture (environment, revision, replica, Envoy, KEDA) | Service selection wizard | Install extension, register providers |
| 2 | 05–13 | ACR in depth | Two ways to push, ACR Tasks, purge, tag locking, import, Artifact Cache, Defender | purge rule simulator | Cloud build + cleanup walkthrough |
| 3 | 13–24 | Deploy to Container Apps ⭐ | Environment, managed identity + AcrPull, ingress, CPU/memory combinations, probes | Deployment animation + resource combination checker | Deploy myapp and open it over HTTPS |
| 4 | 24–32 | Config, secrets & Redis | secretref, Key Vault references, secret rotation, internal TCP service, Azure Managed Redis | "When does a changed secret reach the container?" simulator | Internal Redis + Key Vault secret |
| 5 | 32–40 | Revisions, traffic & scaling | Single/multiple revision mode, revision suffix, label URLs, traffic splitting, rollback, HTTP scale rules | Traffic splitting simulator | 10% canary + rollback + load-test scale-out |
| 6 | 40–50 | Cloud troubleshooting lab | Four classes of local failures; image pull, architecture, port, probe, secret, OOM; system logs and KQL | 6 cloud failure drills | Break things on purpose and fix them |
| 7 | 50–57 | Moving on to Kubernetes | Concept mapping, k8s.yaml, kubectl, rolling update and rollback, AKS + attach-acr | Compose → K8s mapper | Deploy myapp to a kind cluster |
| 8 | 57–60 | Cost, cleanup & self-check | Billing components, cleanup order, link to hour 5 | — | Delete the resource group |
| — | After class | Cheat sheet · Capstone lab | End to end: ACR → ACA (Key Vault + internal Redis) → canary → KQL | Final exam | Capstone lab |
How this lesson builds on Lessons 1 and 2
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.
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.
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.
Module 0 · Warm-up and Azure setup (before class)
- 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 versionworks.
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)
| Mode | Characteristics | Use when |
|---|---|---|
| Default bridge | No container-name DNS, IP addresses only | Not recommended |
| User-defined bridge | Built-in DNS (127.0.0.11), isolates different apps | Everyday default |
| host | Uses the host network directly, no port mapping; fully supported only on Linux | Extremely performance-sensitive workloads |
| none | Loopback only | Pure 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
- 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
| Service | What you manage | Scaling | Good fit | Poor fit |
|---|---|---|---|---|
| VM + Docker/Compose | OS, patches, Docker, high availability | Manual | Legacy apps, full control, edge scenarios | Services that need elasticity and high availability |
| Azure Container Instances | Almost nothing | No built-in autoscaling | Short tasks, batch jobs, temporary environments | Long-running web services |
| Azure Container Apps | Image and configuration | KEDA event-driven, can scale to 0 | Microservices, APIs, background jobs; teams that don't want to operate Kubernetes | Workloads that need direct access to the Kubernetes API, CRDs, DaemonSets |
| AKS | Cluster configuration, node pools, upgrades, add-ons | HPA / KEDA / cluster autoscaler | Large platforms that need the full Kubernetes ecosystem | Simple apps run by small teams (heavy operational burden) |
| App Service (containers) | Image and configuration | By schedule/rules | Traditional web apps, existing App Service estates | Multi-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.
Service selection wizard
| Command | Description |
|---|---|
az extension add --name containerapp --upgrade | Install/upgrade the Container Apps CLI extension |
az provider register --namespace Microsoft.App | Register the resource provider (Microsoft.OperationalInsights is also required) |
az containerapp env list -o table | List environments |
az containerapp list -g $RG -o table | List 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.
Module 2 · ACR in depth: cloud builds, cleanup, locking and caching
- Master both ways to push: local build + push, and cloud builds with
az acr build. - Define a cleanup policy with
acr purgeand protect release versions with tag locks. - Manage base images with
az acr importand Artifact Cache to escape Docker Hub rate limits.
What: two ways to push
| Local build + docker push | az acr build (ACR Tasks) | |
|---|---|---|
| Needs local Docker | Yes | No (the build context is uploaded and built in the cloud) |
| Architecture | Defaults to the host architecture; on Apple Silicon you need --platform linux/amd64 | Defaults to linux/amd64; choose another with --platform |
| Best for | Development and debugging, multi-platform Buildx | Restricted 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 insideaz 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 falseprevents a release tag from being overwritten;--delete-enabled falseprevents deletion (including by purge). - Base images:
az acr importdoes 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
| SKU | Main differences |
|---|---|
| Basic | Entry level and learning; lower storage and throughput |
| Standard | Most production scenarios |
| Premium | Advanced 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).
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).
| Command | Description |
|---|---|
az acr create -g $RG -n $ACR --sku Basic | Create 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 table | View cloud build history |
az acr run -r $ACR --cmd "acr purge --filter 'myapp:.*' --ago 30d --keep 20 --untagged --dry-run" /dev/null | Cleanup dry run (remove --dry-run to actually delete) |
az acr task create -r $ACR -n purge --cmd "acr purge …" --schedule "0 3 * * *" -c /dev/null | Scheduled cleanup task |
az acr repository update -n $ACR --image myapp:1.1 --write-enabled false --delete-enabled false | Lock a tag |
az acr import -n $ACR --source docker.io/library/python:3.13-slim -t base/python:3.13-slim | Import 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 table | List tags by time |
az acr show-usage -n $ACR -o table | Storage usage |
Lab 2: create ACR, push both ways, cleanup dry run (about 7 min)
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"
EOFsource ~/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
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
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
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.
Module 3 · Deploy to Azure Container Apps ⭐
- Create a Container Apps environment and a user-assigned managed identity, and grant it AcrPull.
- Deploy myapp with a single
az containerapp createand understand every parameter. - Choose a valid CPU/memory combination and configure startup/readiness/liveness probes.
What: four things a deployment needs
| Resource | Purpose | Command |
|---|---|---|
| Environment | Network and logging boundary for apps; creates a Log Analytics workspace by default | az containerapp env create |
| User-assigned managed identity | Pulls ACR images and reads Key Vault; its lifecycle is independent of the app, so it can be authorized before the app is created | az identity create |
| Role assignment | AcrPull for the identity on the ACR | az role assignment create |
| App | Image, ingress, resources, scaling, probes | az 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
| Parameter | Meaning |
|---|---|
--image | Image address in ACR (immutable tags recommended) |
--registry-server + --registry-identity | Pull the image with a managed identity instead of a password (you can also pass system) |
--ingress external|internal + --target-port | Whether 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 / --memory | Resources 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-replicas | Replica range; with min 0 the app scales to zero when idle (with cold starts) |
--env-vars | Environment 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).
Deployment flow animation
CPU / memory combination validator
| Command | Description |
|---|---|
az containerapp env create -g $RG -n $ENV -l $LOC | Create an environment (Log Analytics is created automatically) |
az identity create -g $RG -n $ID_NAME | Create a user-assigned managed identity |
az role assignment create --assignee-object-id … --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_ID | Grant pull permission |
az containerapp create … | Create the app (see the lab) |
az containerapp show -g $RG -n $APP --query properties.configuration.ingress.fqdn -o tsv | Get the FQDN |
az containerapp update -g $RG -n $APP --image … --cpu 1.0 --memory 2.0Gi | Update (creates a new revision) |
az containerapp show -g $RG -n $APP -o yaml > app.yaml | Export YAML; after editing, run az containerapp update --yaml app.yaml |
az containerapp replica list -g $RG -n $APP -o table | List replicas |
az containerapp exec -g $RG -n $APP --command sh | Open a shell in a running replica (troubleshooting) |
Lab 3: deploy myapp (about 10 min)
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
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.
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".
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.
Module 4 · Configuration, secrets and stateful dependencies (Redis)
- 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
| Source | Syntax | After a change |
|---|---|---|
| Plain environment variable | --env-vars KEY=value | Revision scope: creates a new revision |
| Container Apps secret | --secrets name=value + KEY=secretref:name | Application scope: no new revision; containers only see the new value after you restart the revision or deploy a new one |
| Key Vault reference | name=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
| Option | Notes | Best 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 availability | This lab, dev/test |
| Azure Managed Redis | Managed, 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 Redis | Being 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".
Simulator: after a change, when does the container see the new value?
| Command | Description |
|---|---|
az containerapp secret set -g $RG -n $APP --secrets name=value | Set/update a secret (no new revision) |
az containerapp secret set … --secrets name=keyvaultref:<URI>,identityref:$ID_ID | Key Vault reference |
az containerapp secret list -g $RG -n $APP -o table | List secret names |
az containerapp update … --set-env-vars KEY=secretref:name | Environment 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 6379 | Internal TCP app |
az keyvault create -g $RG -n $KV --enable-rbac-authorization true | Create 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)
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.
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
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
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.
- Manage secrets in Azure Container Apps (updated 2026-09-11)
- Ingress overview (TCP, internal/external) (updated 2026-10-22)
- Azure Cache for Redis retirement FAQ (updated 2026-08-18)
Module 5 · Revisions, traffic splitting, rollback and scaling
- 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 suffix | Secret values, revision mode, ingress, traffic splitting, labels, registry credentials, Dapr settings |
Why: three revision modes
| Mode | Behavior | Best 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 revision | Most services |
| multiple | Several revisions active at once; you split traffic and deactivate revisions manually | Canary, blue/green, A/B |
| Deployment labels (preview) | Organize revisions with labels such as dev/staging/prod; supports traffic splitting and simplified rollback | Release 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.
Traffic splitting simulator
| Command | Description |
|---|---|
az containerapp revision list -g $RG -n $APP -o table | List revisions (with traffic and status) |
az containerapp revision set-mode -g $RG -n $APP --mode multiple | Switch revision mode |
az containerapp update … --image … --revision-suffix v12 | Release a new revision with a given suffix |
az containerapp ingress traffic set -g $RG -n $APP --revision-weight $APP--v11=90 $APP--v12=10 | Split traffic by revision |
az containerapp revision label add -g $RG -n $APP --label green --revision $APP--v12 | Add a label (gets its own URL) |
az containerapp ingress traffic set … --label-weight blue=80 green=20 | Split 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 10 | HTTP concurrency scale rule |
Lab 5: canary, label, rollback, scale-out (about 8 min)
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
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.
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.2az 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
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.
Module 6 · Troubleshooting in practice: 4 local failures + 6 cloud failures
- 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
| Local | Container Apps | What to look at |
|---|---|---|
docker ps -a | az containerapp revision list / replica list | Status, restart count |
docker logs | az containerapp logs show --type console (default) | App stdout/stderr |
docker events | az containerapp logs show --type system | Platform events: image pull, startup, probe failures, restarts, OOM |
docker inspect | az containerapp show -o yaml | Effective configuration |
docker exec | az containerapp exec | Shell into a replica |
| — | Log Analytics: ContainerAppConsoleLogs_CL, ContainerAppSystemLogs_CL | Historical queries, aggregation, alerts |
| — | Portal: Log stream, Revisions, Diagnose and solve problems | Visual 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
Cloud failure drills (6 scenarios)
| Command | Description |
|---|---|
az containerapp logs show -g $RG -n $APP --follow | Stream console logs |
az containerapp logs show -g $RG -n $APP --type system --tail 50 | Platform events |
az containerapp logs show … --revision R --replica X --container C | Target a specific replica/container |
az containerapp revision show -g $RG -n $APP --revision R --query properties | Revision health and running state |
az containerapp exec -g $RG -n $APP --command sh | Shell into a replica |
az role assignment list --assignee $ID_PRINCIPAL --all -o table | Check the identity's roles |
az acr repository show-tags -n $ACR --repository myapp -o table | Confirm the tag exists |
docker buildx imagetools inspect $ACR.azurecr.io/myapp:TAG | Confirm the image platform |
Lab 6A: four local failures (about 4 min)
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
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
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'
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)
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.
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.
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).
| Symptom | Check first | Common causes |
|---|---|---|
| Revision Provisioning failed | System logs | Tag doesn't exist, no AcrPull, role not yet effective, invalid resource combination |
| Failed, exit code 137 | System logs + memory setting | OOM |
| exec format error | Console logs, imagetools | arm64 image |
| Running but 502/503/timeouts | Ingress configuration | Wrong target-port, listening on 127.0.0.1, weight sent to a bad revision |
| Activating for a long time | Probe events in system logs | Slow startup, wrong probe path/port |
| Broken functionality (hits=N/A) | exec in and test dependencies | Wrong secret value, wrong REDIS_HOST, internal ingress not TCP |
Module 7 · Moving on to Kubernetes: kind and AKS
- 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 / Compose | Container Apps | Kubernetes |
|---|---|---|
| Container | Container | Container in a Pod |
| Compose service | App | Deployment (runs and manages Pods) + Service (stable address) |
| Image tag / new version | Revision | ReplicaSet (one per Deployment version) |
| environment | --env-vars | ConfigMap |
| secrets | secrets / Key Vault references | Secret (or the Key Vault CSI driver) |
| healthcheck | Probes | startup / readiness / liveness Probe |
| --memory / --cpus | --cpu / --memory | resources.requests / limits |
| Named volume | Azure Files volume | PersistentVolumeClaim |
| restart policy | Handled by the platform | Controller maintains the replica count |
| ports | ingress | Service (ClusterIP/LoadBalancer) + Ingress / Gateway |
| --scale | Scale 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.
Compose → Kubernetes mapper
Click a Compose field on the left to highlight the matching Kubernetes configuration on the right.
| Command | Description |
|---|---|
kind create cluster --name lab / kind delete cluster --name lab | Create / delete a local cluster |
kind load docker-image myapp:1.1 --name lab | Load a local image into the nodes |
kubectl apply -f k8s.yaml | Declarative deployment |
kubectl get pods -o wide / kubectl get all | List resources |
kubectl describe pod <pod> | Events (most useful for troubleshooting) |
kubectl logs deploy/myapp / -f / --previous | Logs (--previous shows the last crash) |
kubectl port-forward svc/myapp 8080:80 | Forward to localhost for testing |
kubectl set image deploy/myapp web=myapp:1.2 + kubectl rollout status | Rolling update |
kubectl rollout undo deploy/myapp / rollout history | Rollback / history |
kubectl create secret generic myapp-secret --from-literal=REDIS_PASSWORD=xxx | Create a Secret |
kubectl exec -it deploy/myapp -- sh | Shell into the container |
kompose convert -f compose.yaml | Convert 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-keys | Create AKS and grant AcrPull |
az aks get-credentials -g $RG -n aks-lab | Get the kubeconfig |
Lab 7: deploy myapp on kind (about 7 min)
[ $(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
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).
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.
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
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
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.
Module 8 · Cost, cleanup and self-check
- 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).
| Resource | Billing model (summary) | How to reduce cost |
|---|---|---|
| Container Apps (Consumption) | Billed by replica vCPU-seconds, GiB-seconds and requests, with a monthly free grant | min-replicas 0 for non-user-facing services; right-sized resource combinations |
| Container Apps (Dedicated profiles) | Billed per node of the workload profile | Use only when you need dedicated hardware/GPUs |
| ACR | Daily charge per SKU + storage overage | Clean up with purge; use Basic for development |
| Log Analytics | Billed by data ingestion volume | Control log volume, set retention, sample |
| Key Vault | Billed per operation | Usually very low |
| AKS / Managed Redis | Billed hourly by node VM / instance size | Delete right after the lab |
For actual prices, check the Azure pricing pages and calculator; they vary by region and over time.
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
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.
Command cheat sheet (Hour 3)
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
myapp:2.0 with az acr build, and lock that tag.myapp:2.1: multiple-revision mode → smoke test via label URL → 10% canary → full rollout.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
| Topic | Verified finding | Source |
|---|---|---|
| CPU/memory combinations | From 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 acrPull | Containers |
| Secrets | keyvaultref/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 listSecrets | Manage secrets (2026-09-11) |
| Revisions | single / multiple / Deployment labels (preview); revision scope vs. application scope; up to 100 inactive revisions | Revisions |
| Traffic splitting | --revision-weight, --label-weight | Traffic splitting |
| Ingress | External TCP requires a VNet environment; internal TCP is reached by app name + port within the environment; port 36985 is reserved | Ingress overview (2026-10-22) |
| Probes | Default TCP probes; exec/gRPC not supported; HTTP 200–399 counts as success | Health probes |
| Logs | ContainerAppConsoleLogs_CL, ContainerAppSystemLogs_CL, ContainerAppHTTPLogs | Log monitoring (2026-06-04) |
| Redis | Azure Cache for Redis: Basic/Standard/Premium retire on 2028-09-30, Enterprise on 2027-03-31; Azure Managed Redis (clustered by default) is recommended | Retirement FAQ (2026-08-18) |
| ACR Artifact Cache | az acr cache create; Docker Hub as a source requires a credential set | Artifact cache CLI |
| kind | v0.33.0 install command; :latest images are pulled with Always by default | kind 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 catchesRedisError(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.