Docker Hour 1: Core Fundamentals

For Senior Cloud Engineers: from internals straight to hands-on work on an Ubuntu Azure VM and ACR integration
Docker Engine 29.9.3Compose v5.xUbuntu 24.04 / 26.04 LTSVerified against official docs · 2026-11
Overall learning objectives
  • Draw the full call chain of docker run from the CLI down to runc, and explain what namespaces / cgroups do.
  • Understand image layering, content addressing and the build cache, and write production-ready multi-stage Dockerfiles.
  • Diagnose container networking (bridge, DNS, port publishing) and storage (volume / bind / tmpfs) issues.
  • Orchestrate multi-service stacks with Compose; push images to Azure Container Registry and pull them on a VM using a managed identity.
  • Master a reusable troubleshooting workflow.

1-hour schedule

#TimeModuleCore contentAnimation / interactionLab (Azure VM)
0Before classSetupCreate an Ubuntu VM with az CLI and install Docker from the official apt repository—Install + hello-world
100–06Docker architectureCLI → REST API → dockerd → containerd → shim → runc; namespaces, cgroups v2Step-by-step animation of the docker run call chaindocker info, inspect the process tree
206–12ImagesOCI images, layers, digests, containerd image store, copy-on-writeLayering + CoW demopull / history / inspect
312–19ContainersLifecycle, PID 1 and signals, exit codes, resource limits, restart policiesClickable state machineResource limits and reproducing OOM
419–28Dockerfile and BuildKitInstruction semantics, cache invalidation, multi-stage builds, cache mounts, non-rootBuild cache simulatorBuild a Python API image
528–36NetworkingNetwork drivers, embedded DNS, port publishing and iptablesPacket path animationUser-defined networks and service-to-service access
636–42Storage (volumes)volume / bind / tmpfs, lifecycle, backup and restoreWhere data goes after a container is removedPostgres persistence and backup
742–50Docker ComposeCompose spec, naming rules, healthcheck dependencies, profiles, watchStartup order animationweb + api + db three-service stack
850–60Registry · ACR · TroubleshootingTags vs digests, push/pull, ACR authentication, troubleshooting methodsPush flow animation + troubleshooting decision treePush to ACR, pull on the VM with a managed identity
—After classCheat sheet · Capstone labEnd to end: build → scan → push → deployFinal quizCapstone lab

How to use this course

10 tabs in every module
Concepts · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Audio narration · Videos
Progress
A quiz score ≥ 70% or clicking "Mark this module complete" counts toward progress. Progress is saved in this browser (if the browser blocks local storage, it is cleared on refresh).
Audio narration
The "Audio" tab reads the script aloud using the browser's built-in English speech synthesis (Web Speech API, en-US). Systems without an English voice show a notice; the full script remains readable or can be fed to a TTS tool.
Version noteStarting with Docker Engine 29, fresh installs use the containerd image store by default. Hosts upgraded from older versions may still use the classic overlay2 storage driver, so the output of docker info and docker image ls will differ. The "Expected output" in this course is based on a fresh 29.x install on Ubuntu 24.04; column names may vary slightly between minor versions.

Module 0 · Setup (complete before class)

Create an Ubuntu VM on Azure and install Docker Engine from Docker's official apt repository
Before class ≈ 10 minUbuntu 24.04 LTS
Prerequisites
  • Azure CLI is installed on your machine and you have run az login; your subscription has permission to create resource groups, VMs and ACR.
  • Officially supported Ubuntu 64-bit versions: 26.10, 26.04 LTS, 24.04 LTS, 22.04 LTS (source: docs.docker.com/engine/install/ubuntu, page dated 2026-10-12).
  • Recommended VM size: 2 vCPU / 4 GiB or more (e.g. Standard_B2s), so you can complete the build and OOM labs.
No Azure environment?Most labs (Modules 1–7) can also be done in Docker Desktop (Windows/Mac) on your machine, in Docker Engine on any Linux, or in the browser-based Play with Docker (labs.play-with-docker.com). If docker version shows both the Client and Server sections, your environment is ready. Steps involving /sys/fs/cgroup, iptables or managed identity require a Linux VM.

Step 1: Create the lab VM

RG=rg-docker-lab
LOC=canadacentral
az group create -n $RG -l $LOC

az vm create -g $RG -n vm-docker \
  --image Ubuntu2404 \
  --size Standard_B2s \
  --admin-username azureuser \
  --generate-ssh-keys \
  --public-ip-sku Standard

# note the publicIpAddress
az vm show -d -g $RG -n vm-docker --query publicIps -o tsv
Security adviceDo not use az vm open-port to expose lab ports to the whole internet. An SSH tunnel is enough to reach container ports: ssh -L 8080:localhost:8080 azureuser@<IP>, then browse to http://localhost:8080 on your machine. If you really must open a port, restrict the source address with az network nsg rule create --source-address-prefixes <your-IP>/32.

Step 2: Remove conflicting packages (required by the official docs)

for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do
  sudo apt-get remove -y $pkg
done

Step 3: Add Docker's official apt repository (deb822 format, the current official method)

# Add Docker's official GPG key:
sudo apt update
sudo apt install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources:
sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
sudo apt update

Step 4: Install Engine, CLI, containerd, and the Buildx and Compose plugins

sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
sudo systemctl status docker --no-pager
sudo docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
...
Hello from Docker!
This message shows that your installation appears to be working correctly.

Step 5: Post-install configuration

sudo usermod -aG docker $USER
newgrp docker            # or log out of SSH and log back in
docker version
docker compose version
docker buildx version
sudo systemctl enable docker.service containerd.service
Security noteMembers of the docker group are effectively root on the host: anyone who can access /var/run/docker.sock can mount the entire host filesystem with -v /:/host. In production, control group membership or use Rootless mode.
FirewallPer the official docs: when using ufw or firewalld, ports published by Docker bypass those firewall rules; Docker is only compatible with iptables-nft and iptables-legacy. To filter traffic to published ports, add rules to the DOCKER-USER chain. On Azure, the NSG still applies outside the VM.

Optional: Install Azure CLI (used on the VM in Module 8)

curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
az version
Self-check

Module 1 · Docker architecture and internals

00:00 – 06:00 · Follow a single docker run through the whole call chain
6 minEngine 29.xcgroup v2
Learning objectives
  • Describe the responsibilities of the Docker CLI, dockerd, containerd, shim and runc, and how they communicate.
  • Explain what a container really is: an ordinary Linux process isolated by namespaces and limited by cgroups, not a lightweight VM.
  • Call the Engine API directly over the Unix socket, and find the container process in the host process tree.

Quick concept map (30-second review)

ConceptIn one sentenceAnalogySee
ImageA read-only application package template containing code, dependencies and runtime environmentClass / installation discModule 2
ContainerA running instance of an image; essentially an isolated processObject (instance)Module 3
DockerfileThe script that builds an imageRecipeModule 4
NetworkLets containers communicate with each otherLANModule 5
VolumeKeeps data after a container is removedExternal hard driveModule 6
ComposeDeclares multiple services in one YAML fileOrchestra scoreModule 7
RegistryStores and distributes images: Docker Hub, Azure ACR, AWS ECR, GCP Artifact RegistryGitHubModule 8
Two key insights① A container is not a VM: it shares the same kernel as the host and is essentially an isolated process, so it starts in seconds or less. ② Containers are disposable by default: when you remove a container, data written inside it is lost too, so important data must go in a volume.

What: what Docker is

Docker Engine is a client/server application: the Docker CLI (docker) talks to the dockerd daemon over a REST API. On Linux the default channel is the Unix socket /var/run/docker.sock; TCP+TLS or SSH (DOCKER_HOST=ssh://user@host) can also be configured. dockerd manages high-level objects such as images, networks, volumes and builds (BuildKit), and hands container lifecycle off to containerd.

Why: why so many layers

ComponentResponsibilityInterfaceWhy it is separate
docker CLIParses commands, calls the APIHTTP REST (Engine API)One CLI can manage multiple remote Engines via docker context
dockerdImage management, networking (libnetwork), volumes, BuildKit, API serverREST server; gRPC clientProvides developer-facing high-level abstractions
containerdContainer/task lifecycle, content store, snapshottergRPC (/run/containerd/containerd.sock)CNCF graduated project, also used directly by Kubernetes (CRI)
containerd-shim-runc-v2One shim per container: holds stdio, reaps the exit codettrpcDecouples containers from dockerd/containerd so containers keep running when the daemon restarts (with live-restore)
runcOCI runtime: creates namespaces and cgroups per config.json, then execs the user processCLI (OCI Runtime Spec)Exits after creation; not long-running

How: the three kernel pillars

Namespaces (isolate what a process "sees")
pid, net, mnt, uts, ipc, user, cgroup. PID 1 inside the container is just an ordinary PID on the host.
cgroups v2 (limit how much it "can use")
memory.max, cpu.max, pids.max, io.max. --memory and --cpus ultimately write to these files. Engine 29 has deprecated cgroup v1.
Union FS / Snapshotter (filesystem)
Read-only image layers + one writable layer (overlayfs), provided by the containerd snapshotter or the overlay2 driver.

When: when to use Docker Engine and when not to

  • Good fit: development and CI builds, single-host or small-scale services, edge nodes, integration test environments built with Compose.
  • Not a direct fit: large-scale orchestration (use AKS/Kubernetes, whose node runtime is containerd, bypassing dockerd); strong multi-tenant isolation (consider Kata/gVisor or VM-level isolation).
Tip for K8s usersThere is no dockerd on AKS nodes; crictl talks to containerd directly. But OCI images built with Docker work identically on both.

Architecture diagram: Docker Engine components

Client docker CLI docker compose docker buildx REST API docker.sock dockerd (Docker daemon) Images Networks Volumes BuildKit builder libnetwork / iptables Registry Docker Hub Azure ACR GHCR / Harbor pull/push gRPC containerd.sock containerd content store · snapshotter · tasks shim (runc-v2) shim (runc-v2) Container A (nginx) Container B (postgres) runc exits after create Linux Kernel namespaces pid · net · mnt · uts · ipc · user cgroups v2 memory · cpu · pids · io overlayfs · netfilter seccomp · AppArmor · capabilities /var/lib/docker volumes/ containers/ (logs) network/ /var/lib/containerd content / snapshots (containerd image store)
Figure 1-1 Docker Engine architecture: the CLI is just an API client; containerd + runc actually run the containers

Flowchart: how a container process is born

docker runParse arguments POST createImage / network / mounts POST startdockerd→containerd shim startsOne per container runc createns + cgroup + exec PID 1 runningrunc exits, shim owns it
Figure 1-2 docker run = create + start; if the image is not local, it is pulled first

Step-by-step animation: the full call chain of docker run -d -p 8080:80 nginx

Click "Play" for an automatic walkthrough, or use "Next" to step through it. The highlighted box is the component currently at work; the terminal below shows the corresponding API call or kernel operation.

docker CLI dockerd Registry bridge + iptables containerd shim runc nginxPID 1 (in container)
Ready. Click "Play".
$ docker run -d -p 8080:80 nginx

Core commands and flags

CommandPurposeKey flags / notes
docker versionShows Client/Server versions and API version--format '{{.Server.Version}}'
docker infoEngine-wide info: storage driver, cgroup, runtimes, registry mirrors-f '{{.CgroupVersion}}'
docker context ls / useSwitch the target Engine (local, remote over SSH)docker context create vm1 --docker host=ssh://azureuser@IP
docker system dfDisk usage of images, containers, volumes and build cache-v shows details
docker system eventsReal-time event stream (create/start/die/oom)--filter event=oom --since 10m
systemctl status docker containerdCheck daemon statusjournalctl -u docker -f shows daemon logs
docker version --format 'Client={{.Client.Version}} Server={{.Server.Version}} API={{.Server.APIVersion}}'
docker info --format 'Driver={{.Driver}} Cgroup={{.CgroupDriver}}/v{{.CgroupVersion}} Runtime={{.DefaultRuntime}}'
Client=29.9.3 Server=29.9.3 API=1.5x
Driver=overlayfs Cgroup=systemd/v2 Runtime=runc
NoteA fresh Engine 29 install uses the containerd image store, and docker info shows Storage Driver: overlayfs and driver-type: io.containerd.snapshotter.v1; hosts upgraded from older versions usually still show overlay2.

Lab 1: See through a container (about 4 minutes, run on the Azure VM)

Call the Engine API directly to prove the CLI is just an HTTP client:
curl -s --unix-socket /var/run/docker.sock http://localhost/version | python3 -m json.tool | head -20
{
    "Platform": { "Name": "Docker Engine - Community" },
    ...
    "Version": "29.9.3",
    "ApiVersion": "1.5x",
    "MinAPIVersion": "1.40",
    "Os": "linux",
    "Arch": "amd64",
    ...
Start a container and find it in the host process tree:
docker run -d --name web -p 8080:80 nginx:alpine
ps -ef --forest | grep -B1 -A3 "containerd-shim" | grep -v grep
root   2301     1  ... /usr/bin/containerd-shim-runc-v2 -namespace moby -id 9f3c... -address /run/containerd/containerd.sock
root   2325  2301  ...  \_ nginx: master process nginx -g daemon off;
101    2370  2325  ...      \_ nginx: worker process

Notice: nginx's parent process is the shim, not dockerd; runc has already exited. The containerd namespace is named moby.

Inspect namespaces and cgroup:
PID=$(docker inspect -f '{{.State.Pid}}' web)
sudo lsns -p $PID
cat /proc/$PID/cgroup
docker exec web ps          # inside the container, nginx is PID 1
        NS TYPE   NPROCS   PID USER COMMAND
4026532xxx mnt         3  2325 root nginx: master process ...
4026532xxx uts         3  2325 root ...
4026532xxx pid         3  2325 root ...
4026532xxx net         3  2325 root ...
0::/system.slice/docker-9f3c....scope
PID   USER     TIME  COMMAND
    1 root      0:00 nginx: master process nginx -g daemon off;
View it from containerd's perspective (Docker uses the moby namespace):
sudo ctr -n moby containers ls
sudo ctr -n moby tasks ls
Clean up:
docker rm -f web

Case 1: Upgrading Docker Engine without service interruption

Scenario: a single-host API gateway runs in Docker on a VM, and the security team requires monthly patching and Engine upgrades.

Approach: enable "live-restore": true in /etc/docker/daemon.json. Because container processes are owned by the shim, containers keep running while dockerd restarts.

{
  "live-restore": true,
  "log-driver": "local",
  "log-opts": { "max-size": "20m", "max-file": "5" },
  "default-address-pools": [ { "base": "10.200.0.0/16", "size": 24 } ]
}
sudo systemctl reload docker   # live-restore takes effect on reload; some other settings require restart
docker info | grep -i "live restore"
Limitationslive-restore does not work in Swarm mode; major-version upgrades that involve a containerd upgrade still need a planned maintenance window.

Case 2: Address conflicts on corporate networks

The default bridge uses 172.17.0.0/16, and Compose networks are allocated sequentially from 172.18 onward. These can overlap with corporate VNet or ExpressRoute ranges, causing "the container runs but can't reach certain internal systems". Use default-address-pools to reserve non-conflicting ranges up front (as in the config above).

Case 3: The risk of mounting docker.sock into CI runners

Mounting /var/run/docker.sock into a CI job container hands root on the runner host to every pipeline. Alternatives: Rootless Docker, a remote BuildKit builder, or az acr build (ACR Tasks, cloud builds; see Module 8).

Common errors and fixes

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Cause: dockerd is not running, or DOCKER_HOST / the context points to the wrong address.

sudo systemctl status docker
sudo journalctl -u docker --since "10 min ago" --no-pager | tail -50
docker context ls; echo $DOCKER_HOST
sudo dockerd --validate --config-file /etc/docker/daemon.json   # validate daemon.json syntax

A broken daemon.json (JSON syntax errors, duplicate keys) is the most common reason the daemon fails to start.

permission denied while trying to connect to the Docker daemon socket

Cause: the current user is not in the docker group, or has not logged in again after being added.

id -nG | grep -w docker || sudo usermod -aG docker $USER
newgrp docker
Error response from daemon: client version 1.xx is too old. Minimum supported API version is 1.xx

Cause: Engine 29.0 raised the minimum API version (v1.44), and 29.3.0 relaxed it back to v1.40. Older SDKs, CI tools or plugins may fail as a result.

Fix: upgrade the client or SDK; as a temporary workaround you can configure the minimum API version on the daemon (see the Engine 29 release notes), but complete the upgrade as soon as possible.

or score ≥ 70% on the Quiz

Module 2 · Images: layers, content addressing and copy-on-write

06:00 – 12:00 · Understand an image's "physical structure" to truly master the build cache, image size and pull speed
6 minOCI Image Speccontainerd image store (default on fresh v29 installs)
Learning objectives
  • Describe the three kinds of OCI image objects: Image Index → Manifest → Config + Layers.
  • Distinguish a tag (mutable pointer) from a digest (immutable content hash), and pin images by digest in production.
  • Explain overlayfs lowerdir / upperdir / merged, copy-up and whiteouts, and why "deleting files in a later layer does not make the image smaller".

What: an image is a set of content-addressed blobs

ObjectContentsIdentifier
Image Index (multi-arch list)Lists the manifest for each platform (linux/amd64, linux/arm64…)sha256:… (the digest you usually pull by is this one)
ManifestPoints to one config and an ordered list of layerssha256:…
ConfigENV, CMD, ENTRYPOINT, WORKDIR, USER, history, rootfs diff_idsThe Image ID is usually computed from it or from the manifest (depends on the storage backend)
LayerA filesystem changeset (tar + gzip/zstd)Compressed digest (for transfer) / diff_id (after decompression)

Why: why layers and content addressing

  • Deduplication: a hundred images based on python:3.13-slim store the base layers only once on disk and in the registry; push shows Layer already exists.
  • Verifiability: a digest is the SHA-256 of the content, so any tampering changes the digest. This is the foundation of image signing and supply-chain security.
  • Caching: each build instruction produces a layer, and unchanged layers are reused directly (covered in detail in Module 4).

How: the container's runtime filesystem (overlayfs)

Read: lookup goes top-down; the first layer containing the file wins.
First write: copy-up - the whole file is copied from the read-only layer to the writable layer (upperdir) and then modified. Writing large files (such as database files) in the container layer is slow, which is why you need volumes.
Delete: a whiteout file is created in the upper layer to "mask" the lower file; the lower data still exists.
That is why RUN apt-get install … and RUN rm -rf /var/lib/apt/lists/* must be in the same RUN; otherwise the deletion does not reduce image size.

When: storage backend changes in Engine 29

Starting with Engine 29, fresh installs use the containerd image store by default (official release notes: "The containerd image store is now the default for fresh installs"; this does not apply to daemons with userns-remap enabled). What changes:

  • You can store multi-platform images and attestations (SBOM, provenance) locally. docker image save/load accepts multiple --platform values.
  • Both compressed blobs and unpacked snapshots are kept, so disk usage may be higher than with overlay2.
  • docker image ls shows a tree view by default, listing each platform variant.

OCI image object graph

Tagnginx:alpine (mutable) Image Indexsha256:ab12… (immutable)multi-platform entry Manifestlinux/amd64 Manifestlinux/arm64 Config (ENV/CMD/USER…) Layer 3 sha256:9c… Layer 2 sha256:4e… Layer 1 (alpine base) sha256:1f… arm64 config + layers docker pull nginx:alpine → resolve tag to index digest → pick manifest for local platform → download only missing layers
Figure 2-1 tag → index → manifest → config + layers

overlayfs union mount

merged (the root / the container sees) upperdir · container writable layer (copied-up files, whiteouts) lowerdir 3 · COPY app/ (read-only) lowerdir 2 · RUN apk add … (read-only) lowerdir 1 · alpine base layer (read-only, shared by many images) container removed → lostimage layers → never change copy-on-writecontent-addressed, shared One image can start N containers: N separate upperdirs sharing the same lowerdirs
Figure 2-2 Container filesystem = read-only image layers + one writable layer

Interactive demo: layer sharing and copy-on-write (CoW)

Click the buttons in order and watch how layers are reused, copied and masked.

Image nginx:alpine / container
Image myapp
Waiting for an action…

Core commands and flags

CommandPurposeCommon flags
docker pull IMAGE[:TAG|@DIGEST]Pull an image--platform linux/arm64, -q
docker image lsList local images (tree view by default in Engine 29)--digests, -f dangling=true, --format '{{.Repository}}:{{.Tag}}'
docker image inspectShow config, layers, architecture-f '{{.Architecture}} {{.Config.Cmd}}'
docker image historyWhich instruction produced each layer, and layer sizes--no-trunc, --format '{{.Size}}\t{{.CreatedBy}}'
docker buildx imagetools inspectInspect a remote index/manifest without downloading the image--raw, --format '{{json .Manifest}}'
docker tag SRC TARGETAdd another name for the same image (no data copied)—
docker image rm / rmiRemove a tag or an image-f
docker image pruneRemove dangling images-a removes all unused images, --filter until=168h
docker image save / loadExport/import a tar (air-gapped environments)-o file.tar, --platform (v29 accepts multiple)
# show nginx:alpine's supported platforms and index digest (no pull needed)
docker buildx imagetools inspect nginx:alpine | head -20
Name:      docker.io/library/nginx:alpine
MediaType: application/vnd.oci.image.index.v1+json
Digest:    sha256:<64 hex characters>

Manifests:
  Name:        docker.io/library/nginx:alpine@sha256:...
  MediaType:   application/vnd.oci.image.manifest.v1+json
  Platform:    linux/amd64
  ...
  Platform:    linux/arm64/v8
  ...

Lab 2: take an image apart (about 5 min)

Pull the image and pin it by digest
docker pull nginx:alpine
docker image ls --digests nginx
DIGEST=$(docker image inspect nginx:alpine -f '{{index .RepoDigests 0}}'); echo $DIGEST
docker pull $DIGEST        # pull by digest: always the same result
Inspect the layers and config
docker image history nginx:alpine --format 'table {{.Size}}\t{{.CreatedBy}}' | head
docker image inspect nginx:alpine -f '{{json .RootFS.Layers}}' | python3 -m json.tool
docker image inspect nginx:alpine -f 'User={{.Config.User}} Cmd={{.Config.Cmd}} Entrypoint={{.Config.Entrypoint}}'
Cmd=[nginx -g daemon off;] Entrypoint=[/docker-entrypoint.sh]
Prove that "deleting files in a later layer does not reduce size"
mkdir -p ~/lab2 && cd ~/lab2
cat > Dockerfile.bad <<'EOF'
FROM alpine:3.22
RUN dd if=/dev/zero of=/big bs=1M count=50
RUN rm /big
EOF
cat > Dockerfile.good <<'EOF'
FROM alpine:3.22
RUN dd if=/dev/zero of=/big bs=1M count=50 && rm /big
EOF
docker build -q -t size:bad  -f Dockerfile.bad .
docker build -q -t size:good -f Dockerfile.good .
docker image ls size

Expected: size:bad is about 50 MB larger than size:good (look at the DISK USAGE column; the CONTENT SIZE column shown since Engine 29 is the compressed size, and 50 MB of zeros compresses to almost nothing, so the two look nearly equal there). docker history size:bad shows the 50 MB layer is still there. If the alpine:3.22 tag is unavailable, use alpine:latest instead.

Observe copy-up
docker run -d --name cow nginx:alpine
docker exec cow sh -c 'echo "# changed" >> /etc/nginx/nginx.conf; rm /usr/share/nginx/html/index.html'
docker diff cow
C /etc
C /etc/nginx
C /etc/nginx/nginx.conf
C /usr/share/nginx/html
D /usr/share/nginx/html/index.html
...

C = Changed (copied up), A = Added, D = Deleted (whiteout). Clean up: docker rm -f cow

Case 1: pin base images by digest for reproducible builds

Upstream python:3.13-slim was republished (the tag moved to a new digest), and the nightly build's image suddenly had different OpenSSL behavior. Fix: write FROM python:3.13-slim@sha256:… in the Dockerfile and let Dependabot or Renovate open digest-update PRs automatically, merged after CI passes. You get reproducibility without missing security patches.

Case 2: multi-arch images enable cheaper ARM nodes

After adding an Arm64 (Ampere / Cobalt) node pool to AKS, the same tag runs on both node types as long as the image is an Image Index containing amd64 + arm64. Build it with docker buildx build --platform linux/amd64,linux/arm64 --push (Module 4).

Case 3: disk filled up by images

A build machine produced dozens of image versions every day. Run docker image prune -a --filter "until=168h" -f and docker builder prune --keep-storage 20GB -f from cron or CI, and set disk-usage alerts on the disks holding /var/lib/docker and /var/lib/containerd.

Common errors and fixes

manifest unknown / not found: manifest unknown

The tag does not exist (typo, version retired) or the repository path is wrong. Verify with docker buildx imagetools inspect REPO:TAG, or check the available tags on the registry page.

no matching manifest for linux/amd64 in the manifest list entries

The image has no variant for the current platform. Choose another tag, run it under QEMU emulation with --platform (slow), or build a multi-platform image yourself.

exec /usr/local/bin/app: exec format error

The binary's architecture does not match the host; most commonly it was built on Apple Silicon (arm64) and run on an amd64 VM. Check with docker image inspect -f '{{.Architecture}}' and build with --platform linux/amd64.

toomanyrequests: You have reached your pull rate limit

Docker Hub applies strict rate limits to anonymous pulls (see docs.docker.com/docker-hub/usage for current quotas). Fix: run docker login; in the enterprise, pull through ACR cache rules (Artifact Cache) or a registry proxy; reuse the local cache in CI.

no space left on device
docker system df -v
docker image prune -a -f; docker builder prune -f
sudo du -sh /var/lib/docker /var/lib/containerd
or score ≥ 70% on the Quiz

Module 3 · Containers: lifecycle, signals and resource limits

12:00 – 19:00 · Most "weird problems" in production come down to PID 1, exit codes and resource limits
7 minEngine 29.xcgroup v2
Learning objectives
  • Master the container state machine: created → running ⇄ paused → exited → removed, and the command behind each transition.
  • Understand the docker stop signal flow (SIGTERM → wait 10 seconds → SIGKILL) and fix PID 1 not handling signals.
  • Quickly classify failures from exit codes 125/126/127/137/143; set memory, CPU and PID limits and restart policies.

What: container = image + writable layer + runtime config + one process

A container's lifecycle is bound to its main process (PID 1 inside the container): when the main process exits, the container becomes exited. So you cannot use systemctl in a container to start a service in the background and let the main process exit - the foreground process is the container.

Why: what makes PID 1 special

  • Signals: the Linux kernel does not deliver signals with "default disposition" to PID 1. If the app registers no SIGTERM handler, docker stop waits 10 seconds for nothing and then kills it with SIGKILL, exit code 137.
  • Zombie processes: PID 1 is responsible for reaping orphaned processes. If your app forks child processes, use --init (built-in tini) or ENTRYPOINT ["tini","--"].
  • Shell-form trap: CMD python app.py actually runs /bin/sh -c "python app.py"; PID 1 is sh, and sh does not forward signals. Use exec form instead: CMD ["python","app.py"].

How: exit code cheat sheet

Exit codeMeaningTypical cause
0Normal exitBatch job finished
1Application errorUncaught exception, bad config
125docker run itself failedBad flag, port already in use
126Command cannot be executedNo execute permission, script has CRLF line endings
127Command not foundWrong PATH, no bash in slim/distroless images
137128+9 = SIGKILLOOM killed (check .State.OOMKilled), or stop timeout
143128+15 = SIGTERMNormal graceful stop
139128+11 = SIGSEGVSegfault, often native deps mismatched with libc (musl vs glibc)

When: choosing a restart policy

PolicyBehaviorUse case
no (default)Never restarts automaticallyOne-off tasks
on-failure[:5]Restarts on non-zero exit, optional max retriesBatch jobs, workers
alwaysAlways restarts; also starts after a daemon restart (even if previously stopped manually)Rarely used
unless-stoppedLike always, but containers stopped manually are not started after a daemon restartPreferred for long-running services on a single host
ImportantOn standalone Docker (not Swarm), HEALTHCHECK only marks the container unhealthy; it does not restart it automatically. Self-healing requires an orchestrator (AKS, Swarm) or external monitoring.

Container state machine

created running paused exited restarting removed start pause unpause stop / kill / process exits start / restart restart policy kicks in rm rm (a created container can also be removed directly) docker create → createddocker run = create + start
Figure 3-1 Container state machine (the STATUS column of docker ps -a)

docker stop signal timeline

t=0t=10s (-t / --timeout, or STOPSIGNAL / stop_grace_period) Send SIGTERM App exits gracefully → exit 143 / 0 ✓ Still running → SIGKILL → 137 ✗ If PID 1 is sh or ignores SIGTERM: you land in the red box every time, wasting 10 s per deploy and possibly dropping in-flight requests

Interactive state machine: click a command and watch the state change and the Engine's response

(none) created running paused exited removed
$ # pick a command to start (container name: web)

Key docker run flags

FlagDescriptionExample
-d / -itDetached / interactive terminaldocker run -it --rm alpine sh
--nameContainer name (its DNS name on user-defined networks)--name api
--rmRemove automatically on exitThrowaway debug containers
-p host:ctrPublish a port-p 127.0.0.1:8080:80 (bind to loopback only)
-e / --env-fileEnvironment variables--env-file .env
--memory / --memory-swapMemory limit (cgroup memory.max)--memory 512m --memory-swap 512m (equal values disable swap)
--cpusCPU quota (cpu.max)--cpus 1.5
--pids-limitMax number of processes, prevents fork bombs--pids-limit 200
--restartRestart policy--restart unless-stopped
--initUse tini as PID 1 (forwards signals, reaps zombies)—
--userRun as the given UID:GID--user 10001:10001
--read-only + --tmpfsRead-only root filesystem--read-only --tmpfs /tmp
--cap-drop / --cap-addTrim Linux capabilities--cap-drop ALL --cap-add NET_BIND_SERVICE
--security-optSecurity options--security-opt no-new-privileges
--health-cmd etc.Define a health check at run time--health-cmd 'wget -qO- localhost/ || exit 1' --health-interval 10s
--log-optLog rotation--log-opt max-size=10m --log-opt max-file=3

Operations commands

CommandPurpose
docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'List all containers
docker logs -f --tail 100 --since 10m webFollow logs
docker exec -it web shGet a shell in the container (new process, shared namespaces)
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' webWhy it exited
docker stats --no-streamLive CPU, memory, network, IO data
docker top webProcesses in the container (host view)
docker stop -t 30 web / docker kill -s HUP webGraceful stop / send any signal
docker update --memory 1g --memory-swap 1g webChange resource limits live
docker cp web:/etc/nginx/nginx.conf .Copy files between container and host
docker container prune -fRemove all stopped containers

Warm-up: basic container operations (about 3 min)

# 1. run an nginx container
docker run -d --name web -p 8080:80 nginx:alpine
#   -d detached; --name container name; -p host port:container port
curl -sI localhost:8080 | head -1        # HTTP/1.1 200 OK

# 2. check status
docker ps            # running containers
docker ps -a         # all containers (including stopped)
docker image ls      # local images (the old docker images still works)

# 3. the troubleshooting trio
docker logs -f web          # follow logs live (Ctrl+C to quit)
docker exec -it web sh      # shell into the container (exit to leave)
docker inspect web          # full config: IP, mounts, env vars…

# 4. environment variables (how most cloud config gets injected)
docker run -d --name db -e POSTGRES_PASSWORD=secret postgres:17

# 5. stop and clean up
docker stop web && docker rm web
docker rm -f db
Quick exercise: start an httpd (Apache) container mapped to port 8081; view its logs; run ls inside it; then clean it up.
Sample solution
docker run -d --name apache -p 8081:80 httpd:2.4
docker logs apache
docker exec apache ls
docker rm -f apache

Lab 3: signals, OOM and resource limits (about 6 min)

PID 1 ignores SIGTERM: stop takes 10 seconds
docker run -d --name nosig alpine sleep 300
time docker stop nosig
docker inspect -f 'exit={{.State.ExitCode}}' nosig
real    0m10.3s
exit=137
With --init (tini): signals are forwarded correctly
docker run -d --init --name withinit alpine sleep 300
time docker stop withinit
docker inspect -f 'exit={{.State.ExitCode}}' withinit
real    0m0.4s
exit=143
Reproduce OOMKilled
docker run --name oom --memory 64m --memory-swap 64m python:3.13-slim \
  python -c "a = bytearray(200*1024*1024)"
echo "exit=$?"
docker inspect -f 'OOMKilled={{.State.OOMKilled}} ExitCode={{.State.ExitCode}}' oom
exit=137
OOMKilled=true ExitCode=137
See the actual limits in cgroup v2
docker run -d --name lim --memory 256m --cpus 0.5 --pids-limit 100 nginx:alpine
CID=$(docker inspect -f '{{.Id}}' lim)
cat /sys/fs/cgroup/system.slice/docker-$CID.scope/memory.max
cat /sys/fs/cgroup/system.slice/docker-$CID.scope/cpu.max
cat /sys/fs/cgroup/system.slice/docker-$CID.scope/pids.max
docker stats --no-stream lim
268435456
50000 100000
100
CONTAINER ID   NAME   CPU %   MEM USAGE / LIMIT   ...
xxxxxxxxxxxx   lim    0.00%   3.1MiB / 256MiB     ...

50000 100000 in cpu.max means at most 50 ms of CPU per 100 ms period, i.e. 0.5 cores.

A hardened production run
docker run -d --name hardened \
  --read-only --tmpfs /tmp --tmpfs /var/cache/nginx --tmpfs /var/run \
  --cap-drop ALL --cap-add NET_BIND_SERVICE --cap-add CHOWN --cap-add SETUID --cap-add SETGID \
  --security-opt no-new-privileges \
  --memory 256m --cpus 0.5 --pids-limit 200 \
  --restart unless-stopped \
  --log-opt max-size=10m --log-opt max-file=3 \
  -p 127.0.0.1:8080:80 nginx:alpine
curl -sI localhost:8080 | head -1
HTTP/1.1 200 OK
Clean up
docker rm -f nosig withinit oom lim hardened

Case 1: 502s on every release

Symptom: during rolling releases, a burst of 502 errors appeared at the load balancer; container logs showed no "shutdown" messages, and every exit code was 137.
Root cause: the Dockerfile used CMD npm start (shell form), so PID 1 was sh, SIGTERM never reached the Node process, it was SIGKILLed after 10 seconds, and in-flight requests were cut off.
Fix: switch to CMD ["node","server.js"], handle SIGTERM in the app (stop accepting new requests, wait for in-flight ones to finish), and set the stop timeout longer than the load balancer's draining time.

Case 2: Java/Node in a container sees all of the host's memory

Older runtimes size the heap from host memory, exceed the cgroup limit and get OOM killed. Modern JVMs (JDK 10+) and Node detect cgroup v2 limits, but it is still best to set them explicitly: -XX:MaxRAMPercentage=75 or NODE_OPTIONS=--max-old-space-size=384, kept consistent with --memory.

Case 3: logs fill the disk

The default json-file log driver does not rotate. One container at debug log level wrote 80 GB of logs in a week and filled the whole host's disk. Global fix: set "log-driver":"local" in daemon.json, or configure max-size/max-file for json-file (applies only to containers created afterwards), and ship logs centrally to Azure Monitor / Log Analytics.

Common errors and fixes

Container exits right after starting (Exited (0) 2 seconds ago)

The main process has nothing to do in the foreground (e.g. the service was started in daemon mode, or CMD is a script that finishes and exits). Investigate: docker logs, docker inspect -f '{{.Config.Cmd}} {{.Config.Entrypoint}}'. Fix: run the service in the foreground (e.g. nginx -g 'daemon off;'). For quick debugging, use docker run -it --entrypoint sh IMAGE to look inside the image.

Bind for 0.0.0.0:8080 failed: port is already allocated
sudo ss -lntp | grep :8080
docker ps --filter publish=8080

Use a different host port, or stop the container/process holding that port.

OCI runtime exec failed: exec: "bash": executable file not found in $PATH

alpine, slim and distroless images have no bash. Use sh instead; distroless images do not even have a shell, so use docker debug (Docker Desktop/subscription feature), or start a debug container sharing the PID/network namespaces: docker run -it --rm --pid container:web --network container:web nicolaka/netshoot.

Exited (137) + OOMKilled=true

Raise --memory, fix the memory leak, or tune the runtime's heap settings. Note: OOMKilled=false with exit code 137 usually means a stop timeout or a manual kill.

Container stuck in Restarting (1)

The restart policy keeps relaunching a process that crashes on startup. First run docker update --restart=no NAME to break the loop, then check docker logs for the cause of the first failure.

or score ≥ 70% on the Quiz

Module 4 · Dockerfile and BuildKit: fast, lean, secure images

19:00 – 28:00 · The core hands-on module of this lesson
9 minBuildKit (default builder for docker build)# syntax=docker/dockerfile:1
Learning objectives
  • Understand how each instruction affects the build cache, and order instructions from least to most frequently changing.
  • Use multi-stage builds, cache mounts, secret mounts, a non-root user and HEALTHCHECK.
  • Distinguish CMD from ENTRYPOINT, ARG from ENV, and COPY from ADD; build multi-architecture images.

What: a Dockerfile describes a build graph (DAG)

Since Docker 23.0, docker build on Linux uses BuildKit by default (via the Buildx client). BuildKit converts the Dockerfile into LLB (low-level build graph), so it can build independent stages in parallel, skip stages the final target doesn't need, and support cache/secret/ssh mounts.

Why: cache rules determine build speed

  • RUN: a cache hit as long as the instruction string and parent layer are unchanged (BuildKit does not check whether apt-get update would fetch new data).
  • COPY / ADD: decided by the content checksum of the copied files, regardless of modification time.
  • Once one layer's cache is invalidated, every layer after it must be rebuilt. So put the most frequently changing COPY . . last.
  • .dockerignore decides which files go into the build context: excluding .git, node_modules and .env both speeds up builds and keeps secrets out of the image.
The most common beginner trap: the listen addressAn app inside a container must listen on 0.0.0.0, not just 127.0.0.1. Otherwise, even with a -p port mapping, traffic arriving on the container's eth0 finds no listener and the app is unreachable from outside. The Flask development server listens only on 127.0.0.1 by default, which is why this lesson uses gunicorn --bind 0.0.0.0:8000.

How: commonly confused instructions

PairDifferenceRecommendation
CMD vs ENTRYPOINTENTRYPOINT is the fixed executable; CMD supplies default arguments, and docker run IMAGE args overrides CMDUse exec form (JSON array) for both; end an ENTRYPOINT script with exec "$@"
ARG vs ENVARG exists only at build time; ENV is written into the image and visible at runtimeNever pass secrets via ARG/ENV (they stay in the image history); use --mount=type=secret
COPY vs ADDADD also auto-extracts local tar files and supports URLs and Git addressesUse COPY by default; use ADD only when you need those features (optionally with --checksum)
EXPOSEMetadata only (documentation); it does not publish a portPorts are actually published with -p or Compose ports
RUN shell form vs exec formShell form supports && and variable expansionShell form is fine for RUN; use exec form for CMD/ENTRYPOINT

When: use cases for advanced BuildKit features

FeatureSyntaxUse case
Multi-stage buildFROM … AS builder + COPY --from=builderThe compiler toolchain stays out of the final image, which can shrink it several-fold
Cache mountRUN --mount=type=cache,target=/root/.cache/pip pip install …Package download cache is reused across builds and never enters an image layer
Secret mountRUN --mount=type=secret,id=pipconf,target=/etc/pip.conf pip install …Private package index credentials that never remain in any layer
Multi-platformdocker buildx build --platform linux/amd64,linux/arm64One tag serves both x86 and ARM nodes
Remote cache--cache-to type=registry,ref=…:buildcache,mode=maxReuse cache in CI when every run gets a fresh runner
Build checksdocker build --check .Statically check the Dockerfile for common issues without building

Multi-stage build data flow

Build context app.pyrequirements.txtDockerfile.dockerignore ✗ .git .env tests/(excluded by .dockerignore) Stage: builder FROM python:3.13-slim AS builder python -m venv /opt/venv RUN --mount=type=cache pip install (build tools, pip cache; not shipped) BuildKit cache mount/root/.cache/pip (kept across builds) COPY --from/opt/venv Stage: runtime (final image) FROM python:3.13-slim useradd appuser (UID 10001) COPY /opt/venv (runtime deps only) COPY app.py USER appuser · HEALTHCHECK CMD ["gunicorn", …] Lean · non-root · traceable
Figure 4-1 Builder-stage artifacts reach the runtime stage via COPY --from; build tools and caches never enter the final image

How cache invalidation propagates

FROM ✓ CACHED COPY req ✓ RUN pip ✓ COPY . ✗ changed All later layers ✗ rebuilt Changing only app.py: all dependency layers hit the cache, and the build takes seconds

Build cache simulator: compare two instruction orders

Pick a "code change" and watch which steps in the two Dockerfiles hit the cache (green) and which must rerun (orange). Timings are illustrative.

✗ Anti-pattern
✓ Recommended
Pick a scenario...

Image size comparison (illustrative)

Key docker build / buildx options

OptionDescription
-t name:tagTag the build result; you can pass multiple -t
-f path/DockerfileSpecify the Dockerfile path
--target stageBuild only up to the given stage (e.g. a test stage)
--build-arg K=VPass an ARG (never use it for secrets)
--secret id=x,src=file / env=VARProvided to RUN --mount=type=secret,id=x
--platform linux/amd64,linux/arm64Multi-platform build (the containerd image store can load it locally; otherwise use --push)
--push / --loadAfter building, push directly / load into the local image store
--cache-from / --cache-toExternal cache: type=registry, type=gha, type=local
--no-cache / --pullDisable the cache / always check for base image updates
--progress=plainFull build log output (for troubleshooting)
--checkRun build checks (lint) only, without building
--provenance=true --sbom=trueGenerate supply-chain attestations (SLSA provenance, SBOM)
docker buildx ls                        # list builders
docker builder prune --keep-storage 10GB -f
docker buildx du                        # build cache usage

Lab 4: build a production-grade Python API image (about 8 min)

The api image built in this lab is reused in Modules 5, 7 and 8.

Create the project files
mkdir -p ~/dockerlab/api && cd ~/dockerlab/api

cat > requirements.txt <<'EOF'
flask==3.1.*
gunicorn==23.*
psycopg[binary]==3.2.*
EOF

cat > app.py <<'EOF'
import os, socket
from flask import Flask, jsonify

app = Flask(__name__)

@app.get("/")
def index():
    return jsonify(service="api", host=socket.gethostname(),
                   version=os.getenv("APP_VERSION", "dev"))

@app.get("/healthz")
def healthz():
    return "ok"

@app.get("/visits")
def visits():
    import psycopg
    with psycopg.connect(os.environ["DATABASE_URL"], connect_timeout=3) as conn:
        conn.execute("CREATE TABLE IF NOT EXISTS visits (id serial PRIMARY KEY, ts timestamptz DEFAULT now())")
        conn.execute("INSERT INTO visits DEFAULT VALUES")
        n = conn.execute("SELECT count(*) FROM visits").fetchone()[0]
    return jsonify(visits=n, host=socket.gethostname())
EOF

cat > .dockerignore <<'EOF'
.git
.env
**/__pycache__
*.pyc
Dockerfile*
compose*.yaml
EOF
Write the multi-stage Dockerfile
# syntax=docker/dockerfile:1
ARG PYTHON_VERSION=3.13

# ---------- builder ----------
FROM python:${PYTHON_VERSION}-slim AS builder
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /src
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt

# ---------- runtime ----------
FROM python:${PYTHON_VERSION}-slim AS runtime
LABEL org.opencontainers.image.source="https://example.com/your/repo"
RUN useradd --create-home --uid 10001 appuser
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1
COPY --chown=appuser:appuser app.py .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \
  CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "--access-logfile", "-", "app:app"]
cat > Dockerfile   # paste the content above, then press Ctrl+D
docker build --check .
Check complete, no warnings found.
Build and observe the cache
docker build -t api:1.0 .
echo "# touch" >> app.py
docker build --progress=plain -t api:1.1 . 2>&1 | grep -E '^#[0-9]+ (\[|CACHED|DONE)' | tail -n 20
#7 [builder 4/5] COPY requirements.txt .
#7 CACHED
#8 [builder 5/5] RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
#8 CACHED
...
#12 [runtime 5/5] COPY --chown=appuser:appuser app.py .
#12 DONE 0.0s
Run it and verify non-root and the health check
docker run -d --name api -p 127.0.0.1:8000:8000 -e APP_VERSION=1.1 api:1.1
sleep 15
curl -s localhost:8000/ ; echo
docker exec api id
docker inspect -f '{{.State.Health.Status}}' api
docker image ls api
{"host":"3f2a9c1d7e44","service":"api","version":"1.1"}
uid=10001(appuser) gid=10001(appuser) groups=10001(appuser)
healthy
(Optional) Build a multi-platform image
docker run --privileged --rm tonistiigi/binfmt --install arm64   # install the QEMU emulator
docker buildx build --platform linux/amd64,linux/arm64 -t api:multi .
docker image ls api       # the Engine 29 tree view shows both platform variants

If the host uses the classic overlay2 storage (upgraded from an older version), multi-platform results can't be loaded locally; add --push to push to a registry (Module 8).

Clean up
docker rm -f api

Case 1: CI build cut from 9 minutes to 1

Azure DevOps hosted agents start from a clean environment every time, so there is no local cache. Fix: reorder the COPY steps + --mount=type=cache + a remote cache:

docker buildx create --use --name ci --driver docker-container
docker buildx build \
  --cache-from type=registry,ref=$ACR.azurecr.io/api:buildcache \
  --cache-to   type=registry,ref=$ACR.azurecr.io/api:buildcache,mode=max \
  -t $ACR.azurecr.io/api:$BUILD_ID --push .

Case 2: a secret leaked into image history

A team used ARG PIP_TOKEN to access a private package index, and docker history --no-trunc showed the token in plain sight; the image had already been pushed to a shared registry. Fix: rotate the token immediately; switch to RUN --mount=type=secret,id=pipconf,target=/etc/pip.conf + docker build --secret id=pipconf,src=pip.conf; add image secret scanning to CI.

8 essential rules for the cloud

#RuleWhy / how
1Pin version tags (better still: pin the digest)Use python:3.13-slim, not latest; otherwise the same Dockerfile built at different times may produce different results
2Small base imagesslim, alpine, distroless: faster pulls, smaller attack surface (note alpine uses musl libc)
3Multi-stage buildsFor compiled projects such as Go, Java or Node front ends, size usually drops dramatically
4Never bake secrets into imagesInject at runtime via environment variables / Key Vault / Secrets Manager; use secret mounts at build time
5Run as non-rootRequired by many platforms and Kubernetes security policies
6One concern per containerDeploy web and database separately, so each scales and upgrades independently
7Log to stdout/stderrDon't write to files inside the container; platforms such as Azure Monitor and CloudWatch collect standard output automatically (in Python, set PYTHONUNBUFFERED=1)
8Mind the CPU architectureApple silicon Macs build arm64 by default, while cloud servers are mostly amd64: docker build --platform linux/amd64, or build multi-platform images

Scan for vulnerabilities before pushing

trivy image api:1.1              # open-source Trivy (installed separately)
docker scout cves api:1.1        # Docker Scout: bundled with Docker Desktop; on Linux Engine install the Scout CLI plugin and log in to a Docker account

Case 3: security baseline (for regulated industries such as aviation)

  • Pin base images by digest, sourced from a trusted registry (cached or imported via ACR).
  • Non-root, read-only root filesystem, no debugging tools beyond a shell (or use distroless images).
  • Generate an SBOM and provenance at build time (--sbom=true --provenance=mode=max); after pushing, scan for vulnerabilities with Trivy / Defender for Containers.
  • Add the OCI labels org.opencontainers.image.source/revision so images trace back to a specific commit.

Common errors and fixes

COPY failed: file not found in build context / "/app.py": not found

The file is not in the build context (paths are relative to the last argument of docker build, not to the Dockerfile's location), or it was excluded by .dockerignore.

Dependencies are reinstalled on every build

COPY . . comes before the dependency install, or the build context contains files that change every time (such as logs or .git). Reorder the instructions and tighten .dockerignore.

apt-get install installs old versions / 404 Not Found

RUN apt-get update was cached on its own and is stale. Combine them in one instruction: RUN apt-get update && apt-get install -y --no-install-recommends pkg && rm -rf /var/lib/apt/lists/*.

/bin/sh: ./entrypoint.sh: not found (even though the file exists)

The script has Windows line endings (CRLF), so the shebang became #!/bin/sh\r. Set *.sh text eol=lf in .gitattributes, or run sed -i 's/\r$//' during the build.

ERROR: failed to solve: … failed to compute cache key

Usually the COPY source path doesn't exist. Add --progress=plain to see the full log and identify which step failed.

Multi-platform build is not supported for the docker driver

This occurs on older hosts using classic storage. Enable the containerd image store, or create a builder with the docker-container driver: docker buildx create --use --driver docker-container, then use --push.

or score ≥ 70% on the Quiz

Module 5 · Networking: drivers, DNS and port publishing

28:00 – 36:00 · For cloud engineers who know VNet/NSG: Linux bridge and iptables from a different angle
8 minlibnetworkiptables-nft / legacy (nftables backend is experimental)
Learning objectives
  • Choose the right network driver: bridge, host, none, overlay, macvlan/ipvlan.
  • Understand the embedded DNS (127.0.0.11) of user-defined bridges, and why containers on the default bridge cannot reach each other by name.
  • Trace a packet end to end from the Azure NSG through iptables DNAT, the bridge and the veth into the container.

What: network drivers at a glance

DriverHow it worksTypical useCloud analogy
bridge (default docker0)Linux bridge + veth pair + NATSingle-host containersLike a private subnet + NAT gateway
User-defined bridgeSame as above, one br-xxxx per network, with embedded DNSFirst choice for multiple services on one host (Compose default)Dedicated subnet + private DNS zone
hostShares the host's network namespace; no isolation, no NATExtremely performance-sensitive workloads, or when many ports are neededBinding directly to the VM NIC
noneLoopback onlyOffline batch jobs, security sandboxesNo NIC
overlayVXLAN tunnels across hostsSwarm multi-host networkingCross-VNet peering
macvlan / ipvlanContainers get a MAC/IP directly on the physical networkLegacy systems, devices that must sit directly on the L2 networkNote: Azure VNet does not allow unknown MACs by default, so macvlan usually does not work

Why: user-defined bridges beat the default bridge

  • DNS service discovery: The official docs: "User-defined bridges provide automatic DNS resolution between containers." Containers can reach each other by name or alias; on the default bridge you can only use IPs (or the deprecated --link).
  • Isolation: Every container started without --network joins the default bridge, and they can all reach each other; a custom network only lets containers attached to it communicate.
  • Hot-pluggable: Containers can run docker network connect/disconnect while running.
  • Configurable: Each network can have its own subnet, gateway, MTU and so on.
Containers cannot reach each other via localhostEach container has its own network namespace, so localhost inside a container points only to itself. The right way: put the containers on the same user-defined network and use the container name (or Compose service name), e.g. REDIS_HOST=redis, @db:5432.

How: how port publishing is implemented

  1. -p 8080:80 → dockerd writes a DNAT rule into the DOCKER chain of the nat table: dpt:8080 → 172.18.0.2:80.
  2. The filter table allows the forwarded traffic and provides the DOCKER-USER chain for your own filtering rules (this chain takes effect before Docker's own rules).
  3. Access to localhost from the host itself may be forwarded by the docker-proxy (userland proxy) process.
  4. Container egress traffic: SNAT via MASQUERADE, reaching external networks with the host IP.
Firewall trap-p 8080:80 binds to 0.0.0.0 (and IPv6) by default, and bypasses ufw. On Azure, the NSG is the outer line of defense; on the host, use -p 127.0.0.1:8080:80 instead, or add rules to the DOCKER-USER chain.

When: DNS resolution order inside a container

On a user-defined network, the container's /etc/resolv.conf points to nameserver 127.0.0.11 (Docker's embedded DNS). It first resolves container names, service names and aliases on the same network, and forwards anything it cannot resolve to the upstream DNS configured on the host (on Azure, usually 168.63.129.16).

Single-host network topology

Azure VM (Ubuntu) · eth0 10.0.0.4 iptables / nftnat: DOCKER (DNAT)filter: DOCKER-USER docker0 172.17.0.1 br-appnet 172.18.0.1 (user-defined) vethvethveth legacyeth0 172.17.0.2no DNS name resolution apieth0 172.18.0.2:8000 dbeth0 172.18.0.3:5432 (not published) Embedded DNS 127.0.0.11"db" → 172.18.0.3 -p 127.0.0.1:8000:8000DNAT → 172.18.0.2:8000 Egress: container → MASQUERADE → eth0 → Internet Ingress: Azure NSG → eth0 → DNAT → bridge → veth → container
Figure 5-1 The default bridge and a user-defined bridge side by side; db publishes no port and is reachable only inside appnet

Animation A: inbound packet path (curl http://VM:8080)

Click "Play".

Animation B: service name resolution (api reaching db)

Pick a network…

docker network commands

CommandDescription
docker network lsThree networks exist by default: bridge, host, none
docker network create --driver bridge --subnet 10.10.0.0/24 --gateway 10.10.0.1 appnetCreate a custom network (subnet optional)
docker network create --internal backendInternal network: containers cannot reach external networks
docker run --network appnet --network-alias database …Join a network and set a DNS alias
docker network connect / disconnect appnet apiConnect/disconnect a network at runtime
docker network inspect appnet -f '{{json .Containers}}'Show containers and IPs on the network
docker network pruneRemove unused networks
docker port apiShow port mappings
-p 8080:80 / -p 127.0.0.1:8080:80 / -p 8080:80/udp / -PPublish ports: all addresses / localhost only / UDP / all EXPOSE ports on random host ports
--dns, --add-host db.local:10.0.0.5, --add-host host.docker.internal:host-gatewayCustom DNS servers and hosts entries (host-gateway points to the host)

Host-side diagnostic commands

ip -br addr | grep -E "docker0|br-"
ip link show type veth
sudo iptables -t nat -S DOCKER
sudo iptables -S DOCKER-USER
docker run --rm -it --network container:api nicolaka/netshoot   # share api's network namespace for debugging

Lab 5: service discovery and port publishing (about 7 min)

Default bridge: names do not resolve
docker run -d --name a1 alpine sleep 600
docker run --rm alpine ping -c1 a1
ping: bad address 'a1'
Create a user-defined network and deploy db + api
docker network create appnet
docker run -d --name db --network appnet \
  -e POSTGRES_PASSWORD=labpass postgres:17
docker run -d --name api --network appnet -p 127.0.0.1:8000:8000 \
  -e DATABASE_URL=postgresql://postgres:labpass@db:5432/postgres api:1.1
sleep 8
curl -s localhost:8000/visits; echo
curl -s localhost:8000/visits; echo
{"host":"…","visits":1}
{"host":"…","visits":2}
Inspect the embedded DNS
docker exec api cat /etc/resolv.conf
docker run --rm --network appnet nicolaka/netshoot dig +short db
nameserver 127.0.0.11
options ndots:0
172.18.0.2

IP addresses depend on container start order and the network's subnet allocation.

Look at iptables and the bridge on the host
docker network inspect appnet -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{"\n"}}{{end}}'
sudo iptables -t nat -S DOCKER | grep 8000
ip -br link | grep -E "br-|veth"
db 172.18.0.2/16
api 172.18.0.3/16
-A DOCKER -d 127.0.0.1/32 ! -i br-xxxxxxxx -p tcp -m tcp --dport 8000 -j DNAT --to-destination 172.18.0.3:8000
Verify db is not exposed on the host
sudo ss -lntp | grep 5432 || echo "5432 not listening on the host -- correct"
Hot-plug networks
docker network connect appnet a1
docker exec a1 ping -c1 db
docker network disconnect appnet a1
Clean up (you may keep appnet, db and api for the next module, but starting fresh is recommended)
docker rm -f a1 api db; docker network rm appnet

Lab 5B (beginner): Flask + Redis counter (about 6 min)

A lighter app that practices "custom image → custom network → named volume persistence" in one go. Module 7 rewrites it as a Compose file.

Create the app files
mkdir -p ~/myapp && 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=6379, socket_connect_timeout=1)

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

cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF

cat > .dockerignore <<'EOF'
__pycache__
.git
.env
*.log
EOF

cat > Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m appuser
USER appuser
EXPOSE 5000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000')" || exit 1
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
EOF
Build and run it alone (no Redis yet)
docker build -t myapp:1.0 .
docker run -d --name app -p 5000:5000 myapp:1.0
sleep 3; curl localhost:5000
docker rm -f app
Hello from 1c2d3e4f5a6b, hits=N/A (redis not connected)
Custom network + named volume
docker network create mynet
docker run -d --name redis --network mynet -v redis-data:/data redis:7-alpine
docker run -d --name app --network mynet -p 5000:5000 -e REDIS_HOST=redis myapp:1.0
sleep 3; curl localhost:5000; curl localhost:5000
Hello from …, hits=1
Hello from …, hits=2
Verify persistence: delete and recreate the Redis container; the count is not reset
docker stop redis && docker rm redis     # SIGTERM → Redis writes data to /data/dump.rdb before shutting down
docker run -d --name redis --network mynet -v redis-data:/data redis:7-alpine
curl localhost:5000      # hits=3, continuing from the previous value
NoteUse docker stop here, not docker rm -f. rm -f sends SIGKILL immediately, so Redis has no time to save; and the default RDB snapshot rules (e.g. 10000 writes within 60 seconds) never trigger in this lab, so the count would go back to 1. This illustrates the point: a volume only keeps data that has "already been written to disk". In production you can enable AOF persistence with redis-server --appendonly yes.
Common inspection commands and cleanup
docker volume ls; docker network ls; docker network inspect mynet
docker rm -f app redis; docker network rm mynet

Case 1: database port accidentally exposed to the internet

A developer started PostgreSQL on a VM with -p 5432:5432, assuming ufw already blocked the port; but Docker's DNAT rules take effect before ufw, and with an overly broad NSG rule the database was found by scanners. Fix: don't publish the database port, keep it on an internal network only; bind to 127.0.0.1: when needed; whitelist in the DOCKER-USER chain; let the NSG allow only the necessary ports and sources.

# allow only 10.0.0.0/8 to reach published container ports, drop the rest (example; verify in a lab first)
sudo iptables -I DOCKER-USER -i eth0 ! -s 10.0.0.0/8 -j DROP

Case 2: corporate address range conflict

A network auto-created by Compose used 192.168.x.0/20, which happened to overlap the company VPN range; when the VM accessed services behind the VPN, packets were routed into the Docker bridge. Fix: configure default-address-pools in daemon.json to plan container address ranges centrally.

Case 3: frontend/backend network tiers

web joins both the frontend and backend networks; api joins backend; db joins only backend (which can be made --internal to block internet access). This matches the "subnet + NSG" tiering approach in Azure (the Compose example in Module 7 uses this structure).

Common errors and fixes

Containers cannot reach each other by name: Name or service not known / bad address

The containers are on the default bridge, or not on the same network. Check with docker inspect -f '{{json .NetworkSettings.Networks}}' NAME and put both on the same user-defined network.

Published port is unreachable from outside
  1. Is the app listening on 0.0.0.0? If it listens only on 127.0.0.1, it cannot be reached from outside the container (Flask's default behavior).
  2. Confirm the mapping with docker port NAME; is it bound to 127.0.0.1?
  3. NSG inbound rules, the DOCKER-USER chain.
  4. Test from inside the container: docker exec NAME wget -qO- localhost:PORT.
DNS resolution of external domains fails inside the container / apt update times out

Check the host's /etc/resolv.conf (systemd-resolved's 127.0.0.53 cannot be used directly in containers; Docker handles this automatically); behind a corporate proxy, configure HTTP(S)_PROXY in the daemon or container; an MTU mismatch (VPN/tunnel environments) can be fixed with docker network create -o com.docker.network.driver.mtu=1400.

Error response from daemon: Pool overlaps with other one on this address space

The specified subnet overlaps an existing network. Use docker network ls and docker network inspect to see which subnets are taken, then pick another range or remove unused networks.

or score ≥ 70% on the Quiz

Module 6 · Storage and volumes: making data outlive the container

36:00 – 42:00 · Choosing between volume, bind mount and tmpfs; lifecycle and backup
6 minlocal volume driver
Learning objectives
  • Choose volume / bind mount / tmpfs for a given scenario, and state where each stores its data and how long it lives.
  • Understand the behavioral differences between the -v and --mount syntaxes.
  • Back up and restore volumes, and handle UID/GID permission issues.

What: three mount types

TypeData locationManaged byLifecycleTypical use
volume (named volume)/var/lib/docker/volumes/<name>/_dataDockerIndependent of the container; must be removed explicitlyDatabases, persistent business data (preferred in production)
Anonymous volumeSame as above, named with a random hashDockerRemoved with the container when using --rm or docker rm -vPaths declared by the VOLUME instruction in the image
bind mountAny path on the hostYouSame as the host filesInjecting config files, mounting source code during development, reading host logs
tmpfsHost memoryKernelGone when the container stopsTemporary files, sensitive transient data, writable directories under a read-only root filesystem

Why: why a database must not write to the container layer

  • The container layer is deleted along with docker rm, and the standard way to upgrade an image is "remove the old container, then create a new one from the new image".
  • overlayfs copy-up and write performance are poorly suited to random IO on large files; volumes bypass the union filesystem and write directly to the host filesystem.
  • Volumes can be backed up and migrated independently, and volume drivers can mount remote storage such as NFS/SMB.

How: the difference between -v and --mount

Behavior-v / --volume--mount
Syntax-v src:dst[:ro], compact--mount type=volume,src=x,dst=/data,readonly, explicit
Bind source path does not existSilently creates an empty directory (owned by root), often masking typosFails immediately: bind source path does not exist
RecommendationQuick interactive useScripts and production (more explicit, less error-prone)

When: the "pre-populate" behavior of named volumes

When you mount an empty named volume onto a directory that already has content in the image, Docker first copies the image's content into the volume; a bind mount instead hides the image's original content. So if you bind an empty host directory onto /etc/nginx, nginx fails to start because it cannot find its config file.

Version noteThe official postgres image changed the default PGDATA location in version 18 (the official recommendation is to mount /var/lib/postgresql). This lesson uses postgres:17, whose data directory is /var/lib/postgresql/data. Read the image's Docker Hub description before upgrading to 18.

Mount types diagram

Container /var/lib/postgresql/data/etc/nginx/nginx.conf/tmp Docker host volume: pgdata/var/lib/docker/volumes/pgdata/_data bind: /srv/nginx/nginx.confAny host path (:ro) tmpfsMemory (never hits disk) --mount type=volumetype=bind,readonlytype=tmpfs
Figure 6-1 All three mount types bypass the container's writable layer

Decision flow

Data must persist? No tmpfs / container layer Yes Edit directly on host? Yes bind mount (:ro) No Named volume ✓

Simulator: is the data still there after this operation?

Container
Storage location

docker volume and mount options

Command / optionDescription
docker volume create pgdataCreate a named volume (it can also be created automatically on first use)
docker volume ls -f dangling=trueList volumes not referenced by any container
docker volume inspect pgdataShow Mountpoint, Driver, Labels
docker volume rm pgdataRemove a volume (fails if a container references it)
docker volume pruneBy default removes only unused anonymous volumes; add -a to also remove unused named volumes
--mount type=volume,src=pgdata,dst=/var/lib/postgresql/dataMount a named volume
--mount type=bind,src=$PWD/nginx.conf,dst=/etc/nginx/nginx.conf,readonlyBind-mount a single file read-only
--mount type=tmpfs,dst=/tmp,tmpfs-size=64mSize-limited tmpfs
-v pgdata:/var/lib/postgresql/data / -v ./conf:/etc/app:roShort form
--volumes-from otherReuse all mounts of another container (common for backups)
docker run --rm -v pgdata:/data -v $PWD:/backup alpine tar czf /backup/pg.tgz -C /data .Back up a volume

Lab 6: database persistence, backup and restore (about 6 min)

Run Postgres with a named volume and write data
docker volume create pgdata
docker run -d --name pg -e POSTGRES_PASSWORD=labpass \
  --mount type=volume,src=pgdata,dst=/var/lib/postgresql/data postgres:17
sleep 6
docker exec pg psql -U postgres -c "CREATE TABLE t(msg text); INSERT INTO t VALUES ('survives rm');"
Remove the container and recreate it with the same volume
docker rm -f pg
docker run -d --name pg -e POSTGRES_PASSWORD=labpass \
  --mount type=volume,src=pgdata,dst=/var/lib/postgresql/data postgres:17
sleep 4
docker exec pg psql -U postgres -tAc "SELECT msg FROM t;"
survives rm
Back up the volume (in production, stop writes first or use pg_dump for consistency)
mkdir -p ~/backup
docker stop pg
docker run --rm -v pgdata:/data:ro -v ~/backup:/backup alpine \
  tar czf /backup/pgdata-$(date +%F).tgz -C /data .
docker start pg
ls -lh ~/backup
Restore into a new volume and verify
docker volume create pgdata_restore
docker run --rm -v pgdata_restore:/data -v ~/backup:/backup alpine \
  sh -c "tar xzf /backup/pgdata-*.tgz -C /data"
docker run -d --name pg2 -e POSTGRES_PASSWORD=labpass \
  -v pgdata_restore:/var/lib/postgresql/data postgres:17
sleep 4
docker exec pg2 psql -U postgres -tAc "SELECT msg FROM t;"
survives rm
bind mount: -v vs --mount
docker run --rm --mount type=bind,src=/nonexistent,dst=/x alpine true
docker run --rm -v /tmp/autocreated:/x alpine true; ls -ld /tmp/autocreated
docker: Error response from daemon: invalid mount config for type "bind": bind source path does not exist: /nonexistent
drwxr-xr-x 2 root root 4096 … /tmp/autocreated
bind mount permission issues: when the container runs as UID 10001, the host directory must be writable by that UID
mkdir -p ~/appdata
docker run --rm --user 10001:10001 -v ~/appdata:/data alpine touch /data/f   # Permission denied
sudo chown 10001:10001 ~/appdata
docker run --rm --user 10001:10001 -v ~/appdata:/data alpine touch /data/f && echo OK
Clean up
docker rm -f pg pg2; docker volume rm pgdata pgdata_restore

Case 1: a cleanup script deletes production data

To free disk space, an operator first ran docker rm -f $(docker ps -aq) intending to "recreate all containers", then ran docker volume prune -a -f. The database's named volume was deleted because, at that moment, no container referenced it. (Note: since Engine 23, docker volume prune removes only anonymous volumes by default; -a is needed to remove named volumes.) Prevention: forbid volume prune -a on production hosts; label important volumes (--label keep=true) and exclude them during cleanup with --filter "label!=keep=true"; back up regularly and rehearse restores.

Case 2: using managed storage on Azure

With single-host Docker, keep persistent data on a separate managed data disk attached to the VM (for example, put /var/lib/docker on the data disk, or bind-mount from the data disk), so you can use Azure Backup snapshots and scale storage independently. When several VMs need to share files, you can mount Azure Files (SMB) with the local driver:

# Requires cifs-utils on the host; the key should come from Key Vault, never hard-code it in scripts. Do not put databases on SMB.
docker volume create --driver local \
  --opt type=cifs \
  --opt device=//<account>.file.core.windows.net/<share> \
  --opt o=addr=<account>.file.core.windows.net,username=<account>,password=<key>,vers=3.0,uid=10001,gid=10001 \
  shared-files

Case 3: hot reload in development

During development, bind-mount the source directory so changes take effect immediately; in production images, the code is baked in with COPY to guarantee immutability. Compose's develop.watch (Module 7) offers a better way to sync.

Common errors and fixes

Permission denied (when writing to a bind mount or volume)

The UID of the process in the container has no write permission on the host directory. Align the UIDs: chown the host directory, or create the user with a fixed UID in the Dockerfile; do not just resort to chmod 777.

Error response from daemon: remove pgdata: volume is in use

A container (including stopped ones) still references this volume: docker ps -a --filter volume=pgdata.

After mounting config, the container's original files "disappeared"

A bind mount hides the original contents of that directory in the image. Mount only the single file, or first copy the default config out with docker cp and then edit it.

Data lost after recreating the database container

The mount point does not match the data directory the image actually uses (for example, postgres 18 changed PGDATA), or an anonymous volume was used (deleted with --rm). Check with docker inspect -f '{{json .Mounts}}'.

Verified tutorial videos

▶
Docker Full Course — freeCodeCamp.org
About 7 hours · English · watch the "Storage and volumes" chapter
▶
100+ Docker Concepts you Need to Know — Fireship
8:28 · English · covers volume and bind mount concepts
NoteWe could not find a verifiable, sufficiently recent short video (Chinese or English) dedicated to Docker volumes, so this module relies mainly on the official documentation.

Official documentation

or score ≥ 70% on the Quiz

Module 7 · Docker Compose: declarative orchestration of multi-service apps

42:00 – 50:00 · Turn the networks, volumes and health checks you have learned into a single compose.yaml
8 minCompose v5.x (docker compose plugin)Compose Specification
Learning objectives
  • Understand the Compose "project" model and its resource naming rules.
  • Use healthcheck + depends_on.condition: service_healthy to control startup order.
  • Master up / down / logs / exec / config / watch, plus profiles, multi-file overrides and scaling.

What: Compose is a declarative client on top of the Engine API

Compose reads compose.yaml (which follows the open Compose Specification), computes the desired state, then calls the Engine API to create networks, volumes and containers. Since v2 it is docker compose (a plugin written in Go), replacing the old Python docker-compose (v1, no longer maintained). The main changes in Compose v5 (per the official release notes): Compose can be embedded as an SDK in third-party software, and the built-in builder was removed, with all builds delegated to Docker Bake (the same BuildKit path as docker build).

Why: why not keep writing shell scripts

  • Idempotent: re-running docker compose up -d recreates only the services whose configuration changed.
  • Automatic networking: a <project>_default network is created by default, and the service name is the DNS name.
  • Readable and reviewable: YAML goes into Git and code review; environment differences are handled with multi-file overrides or profiles.

How: naming rules (very useful when troubleshooting)

ResourceName formatExample (project directory dockerlab)
Project nameDefaults to the directory name; set with -p, COMPOSE_PROJECT_NAME or a top-level name:dockerlab
Container<project>-<service>-<index>dockerlab-api-1
Network<project>_<network>dockerlab_backend
Volume<project>_<volume>dockerlab_pgdata

When: the three depends_on conditions

conditionMeaning
service_started (default for the short list form)The dependency's container has merely started; this does not mean the service is ready
service_healthyStarts only after the dependency's healthcheck reports healthy
service_completed_successfullyThe dependency has exited with code 0 (e.g. a database migration job)

From Compose to the cloud: concept mapping

Compose is the standard tool for developing and testing multi-service apps locally. In the cloud the ideas are the same, only mapped to the platform's resource objects:

ComposeAzure Container AppsAWS ECSKubernetes / AKS
serviceContainer App (or multiple containers in one app)Task Definition + ServiceDeployment + Service
portsIngressALB Target GroupService / Ingress
environment / secretsEnvironment variables / Secrets (can reference Key Vault)Environment variables / Secrets ManagerConfigMap / Secret
volumesAzure Files volumeEFS volumePersistentVolumeClaim
healthcheckHealth probesContainer health checkliveness / readiness probe
--scaleReplica count / KEDA autoscalingdesiredCount / Auto Scalingreplicas / HPA
Common outdated syntaxThe top-level version: "3.8" is obsolete; current versions warn the attribute `version` is obsolete, it will be ignored. Just delete it. The recommended file name is compose.yaml.

Application architecture for this module's lab

Project dockerlab (compose.yaml) BrowserSSH tunnel :8080 network: frontend web (nginx)ports 127.0.0.1:8080:80 network: backend (internal: true) http://api:8000 api ×Nbuild: ./api dbpostgres:17 volume: pgdata adminerprofile: debug Startup order: db(healthy) → api(healthy) → web
Figure 7-1 web sits on both networks; db is only on the internal network and publishes no ports

Startup order animation: docker compose up -d

docker compose commands

CommandDescription
docker compose up -d [--build] [--wait]Create/update and start in the background; --wait waits until services are running/healthy
docker compose ps [-a]List the project's containers
docker compose logs -f --tail 50 apiView service logs
docker compose exec db psql -U postgresRun a command in a service container
docker compose run --rm api python -c '…'Run a one-off task using the service's configuration
docker compose configPrint the final config after variable interpolation and merging (first stop when troubleshooting)
docker compose up -d --scale api=3Scale (the service must not set container_name or a fixed host port)
docker compose watchWatch for file changes and sync/rebuild automatically (uses the develop.watch config)
docker compose --profile debug up -dEnable services in a specific profile
docker compose -f compose.yaml -f compose.prod.yaml up -dMerge and override multiple files
docker compose pull / build / restart / stop / top / eventsOther common operations
docker compose downRemove containers and networks (volumes are kept)
docker compose down -v --rmi localAlso remove volumes and locally built images (data will be lost!)

Lab 7: a three-service stack (about 8 min)

Reuse the ~/dockerlab/api directory created in Module 4.

Prepare the nginx config and environment variables
cd ~/dockerlab
mkdir -p web
cat > web/default.conf <<'EOF'
server {
    listen 80;
    location / {
        proxy_pass http://api:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
EOF
cat > .env <<'EOF'
POSTGRES_PASSWORD=labpass
APP_VERSION=2.0
EOF
Write compose.yaml
name: dockerlab

services:
  web:
    image: nginx:alpine
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./web/default.conf:/etc/nginx/conf.d/default.conf:ro
    networks: [frontend, backend]
    depends_on:
      api:
        condition: service_healthy
    restart: unless-stopped

  api:
    build:
      context: ./api
    image: api:2.0
    environment:
      APP_VERSION: ${APP_VERSION}
      DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/postgres
    networks: [backend]
    depends_on:
      db:
        condition: service_healthy
        restart: true
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 256M
    restart: unless-stopped
    develop:
      watch:
        - action: sync+restart
          path: ./api/app.py
          target: /app/app.py
        - action: rebuild
          path: ./api/requirements.txt

  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data
    networks: [backend]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s
    restart: unless-stopped

  adminer:
    image: adminer
    profiles: [debug]
    ports:
      - "127.0.0.1:8081:8080"
    networks: [frontend, backend]

networks:
  frontend:
  backend:
    internal: true

volumes:
  pgdata:
docker compose config --quiet && echo "config is valid"
Start and watch the startup order
docker compose up -d --build --wait
docker compose ps
NAME                IMAGE          COMMAND                  SERVICE   CREATED          STATUS                    PORTS
dockerlab-api-1     api:2.0        "gunicorn --bind 0.0…"   api       30 seconds ago   Up 18 seconds (healthy)   8000/tcp
dockerlab-db-1      postgres:17    "docker-entrypoint.s…"   db        30 seconds ago   Up 29 seconds (healthy)   5432/tcp
dockerlab-web-1     nginx:alpine   "/docker-entrypoint.…"   web       30 seconds ago   Up 6 seconds              127.0.0.1:8080->80/tcp
Access the app (or open it in a browser on your machine via ssh -L 8080:localhost:8080)
curl -s localhost:8080/ ; echo
curl -s localhost:8080/visits ; echo
{"host":"…","service":"api","version":"2.0"}
{"host":"…","visits":1}
Scale out api and observe load balancing
docker compose up -d --scale api=3 --wait
docker compose restart web            # nginx resolves api's DNS at startup, so restart it after scaling
for i in $(seq 30); do curl -s localhost:8080/ | python3 -c 'import sys,json;print(json.load(sys.stdin)["host"])'; done | sort | uniq -c

Expected: 3 different container hostnames appear in the output, though not necessarily evenly (e.g. 20 / 5 / 5). Docker's embedded DNS returns multiple A records for the service name; nginx starts one worker process per CPU and each worker round-robins on its own, so on a many-core machine a handful of requests may all land on the same replica.

Verify network isolation and persistence
docker compose exec api python -c "import urllib.request;urllib.request.urlopen('https://www.microsoft.com',timeout=3)" \
  || echo "backend is an internal network, so api cannot reach the internet -- as expected"
docker compose down            # volumes are kept
docker compose up -d --wait
curl -s localhost:8080/visits ; echo   # the counter keeps increasing instead of resetting
(Optional) Dev mode and profiles
docker compose --profile debug up -d     # additionally starts adminer
docker compose watch                     # edit api/app.py in another terminal and watch it sync and restart
Clean up
docker compose --profile debug down -v

Lab 7B (beginner): turn the Flask + Redis app from Module 5B into Compose

Create compose.yaml in ~/myapp
services:
  web:
    build: .
    ports:
      - "5000:5000"
    environment:
      - REDIS_HOST=redis
    depends_on:
      - redis
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data

volumes:
  redis-data:
Build, start, inspect and clean up with one command each
cd ~/myapp
docker compose up -d --build     # build and start
docker compose ps
docker compose logs -f web       # Ctrl+C to exit
curl localhost:5000
docker compose down              # remove containers and networks (volumes kept)
docker compose down -v           # also remove volumes
Scaling exercise: running docker compose up -d --scale web=3 as is fails, because the 3 replicas compete for host port 5000. Change ports to "5000" (container port only; the host port is assigned randomly), or drop the port and put an nginx reverse proxy in front (i.e. the full lab above), then scale. Use docker compose ps to see the port each replica got.
ComparisonIn this minimal version, depends_on: [redis] only waits for the Redis container to "start", not to be "ready". The app uses socket_connect_timeout and exception handling, so it tolerates this; in production use condition: service_healthy as in the full lab above.

Case 1: single-host production deployment (edge sites / small internal services)

For internal tools that do not justify Kubernetes, use the "Compose + systemd + image digest" combo: CI builds and pushes to ACR → update the image digest in compose.prod.yaml in the deployment repository → run docker compose pull && docker compose up -d --wait on the VM. Use --wait as the deployment gate, and roll back to the previous digest on failure.

services:
  api:
    build: !reset null
    image: myacr.azurecr.io/demo/api@sha256:<digest>
    logging:
      driver: local
      options: { max-size: "20m", max-file: "5" }

Case 2: CI integration test environment

In the pipeline, run docker compose -f compose.yaml -f compose.ci.yaml up -d --wait, then the tests, and finally docker compose down -v regardless of the outcome. Use -p ci-$BUILD_ID to isolate parallel jobs and avoid project and network name collisions.

Case 3: secrets management

Do not put passwords in compose.yaml or commit the .env file. Use Compose secrets: (mounted as files under /run/secrets/<name>; the postgres image supports POSTGRES_PASSWORD_FILE), written by the deployment process after fetching them from Azure Key Vault.

Common errors and fixes

dependency failed to start: container dockerlab-db-1 is unhealthy

Inspect the detailed health check output: docker inspect -f '{{json .State.Health}}' dockerlab-db-1 | python3 -m json.tool. Common causes: the check command does not exist in the image (e.g. curl), start_period is too short, or environment variables such as the password are wrong.

Changed .env or compose.yaml, but the containers did not change

First use docker compose config to confirm the variables are interpolated correctly; after changing the Dockerfile or code you need up -d --build; to force recreation: up -d --force-recreate.

WARN: the attribute `version` is obsolete

Just delete the version: line at the top of the file; it has no functional effect.

docker-compose: command not found

v1 is no longer maintained. Use docker compose (with a space) and make sure the docker-compose-plugin package is installed.

Containers/networks of two projects interfere with each other

Two directories with the same name get the same project name. Set the project name explicitly with -p or a top-level name:.

or score ≥ 70% on the Quiz

Module 8 · Registries, ACR integration and troubleshooting

50:00 – 60:00 · The image distribution path, Azure authentication, and a reusable troubleshooting method
10 minOCI Distribution SpecAzure CLI · az acr
Learning objectives
  • Break down the image reference registry/namespace/repo:tag@digest and understand the push flow: "layer existence check + upload + manifest".
  • Know the ACR authentication options: az acr login (3-hour token), --expose-token, managed identity, service principal; know when you should not use the admin account.
  • Pull images on a VM without passwords using a managed identity; build in the cloud with ACR Tasks.
  • Establish an "outside-in, layer-by-layer" Docker troubleshooting workflow.

What: anatomy of an image reference

myacr.azurecr.io / demo / api : 2.0 @sha256:3b1f…
└──── registry ───┘ └ ns ┘ └repo┘ └tag┘ └──── digest (immutable) ────┘

nginx:alpine  ≡  docker.io/library/nginx:alpine     # when omitted, defaults to Docker Hub's library namespace

Why: push and pull only transfer "what is missing"

  1. push: for each layer, first send HEAD /v2/<repo>/blobs/<digest>; if it exists, skip it (Layer already exists), otherwise upload it; finally PUT /v2/<repo>/manifests/<tag>.
  2. pull: GET manifest → select by platform → download only the blobs not present locally → verify digests → unpack into snapshots.
  3. A tag is just a pointer to a manifest digest and can be overwritten; production deployments should reference the digest, or enable tag locking in the repository (ACR supports az acr repository update --write-enabled false).

How: ACR authentication options (source: Microsoft Learn, updated 2026-02)

MethodUse caseNotes
az acr login --name XInteractive use by engineersUses your Entra ID identity; the docs state: "the token that az acr login uses is valid for 3 hours". In environments without a Docker daemon (e.g. Cloud Shell), use --expose-token
Managed identityUnattended pulls from VMs, AKS, Container Apps, App Service; pushes from Azure pipelinesPreferred; no secrets to rotate
Service principalCI/CD outside AzureFor docker login the username is the appId and the password is the secret; prefer OIDC workload identity federation instead
Repository-scoped token (token + scope map)IoT/edge devices, read-only access for external partnersCan be limited to specific repositories and actions
Admin userTesting onlyDocs: "designed for a single user to access the registry, mainly for testing purposes"; has full permissions and should be disabled in production

When: choosing RBAC roles

  • By default ACR uses the "RBAC Registry Permissions" mode: AcrPull for pulling, AcrPush for pushing (includes pull).
  • If the registry has the ABAC repository permissions mode enabled, the docs say AcrPull/AcrPush/AcrDelete "are not honored"; use roles such as Container Registry Repository Reader / Writer / Contributor instead, optionally with conditions that scope them to specific repositories.
  • Least privilege: give runtimes pull permission only; only the CI build identity gets push permission.

End-to-end delivery flow: build → ACR → VM

Build sideEngineer / CI runnerdocker build · tagor az acr build (cloud build) Microsoft Entra IDUser / SP / managed identityRBAC: AcrPush / AcrPull ① Authenticate ② Exchange for ACR token ③ docker push Azure Container Registry myacr.azurecr.io demo/api:2.0 → sha256:… Defender vulnerability scan Tasks / Artifact Cache Premium: geo-replication / private endpoint ④ pull Run side Ubuntu VM + DockerSystem-assigned managed identityaz login --identityaz acr loginor: AKS / Container Apps(kubelet identity + AcrPull) No long-lived passwords anywhere: Entra identity → short-lived ACR token
Figure 8-1 The four stages: build, authenticate, distribute, run

Layered troubleshooting model

① Clientcontext / permissions ② Daemonjournalctl / disk ③ Imagetag / platform / registry ④ Processlogs / exit code ⑤ NetworkDNS / ports / FW ⑥ Storagemounts / perms ⑦ ResourcesOOM / CPU Rule out layers left to right: each has one or two decisive commands (see the decision tree on the Troubleshooting tab)

Animation: docker push myacr.azurecr.io/demo/api:2.0

$ az acr login --name myacr

Registry-related Docker commands

CommandDescription
docker login REGISTRY [-u USER --password-stdin]Log in; credentials are stored in ~/.docker/config.json or a credential helper
docker tag api:2.0 myacr.azurecr.io/demo/api:2.0Add a name that includes the registry (must use the full, all-lowercase login server name)
docker push myacr.azurecr.io/demo/api:2.0Push
docker push --all-tags myacr.azurecr.io/demo/apiPush all local tags of a repository
docker buildx imagetools inspect REFShow a remote image's digest and platforms
docker logout REGISTRYRemove local credentials

Pushing to Docker Hub (the flow is the same for every registry; only the login differs)

docker login                                   # Docker Hub; use an access token rather than your password
docker tag myapp:1.0 <your-username>/myapp:1.0
docker push <your-username>/myapp:1.0
# AWS ECR: aws ecr get-login-password | docker login --username AWS --password-stdin <acct>.dkr.ecr.<region>.amazonaws.com
# GCP: gcloud auth configure-docker <region>-docker.pkg.dev
# Azure ACR: az acr login -n <acr-name> (see the table below and the lab)

Azure CLI (az acr)

CommandDescription
az acr create -g RG -n NAME --sku Basic|Standard|PremiumCreate a registry (name is globally unique, 5–50 alphanumeric characters)
az acr login -n NAMELog Docker in with your current Entra identity (3-hour token)
az acr login -n NAME --expose-tokenOutput the token only, for environments without a Docker daemon
az acr repository list -n NAME -o tableList repositories
az acr repository show-tags -n NAME --repository demo/api --detail -o tableList tags with digests
az acr manifest list-metadata -r NAME -n demo/apiShow manifest metadata
az acr build -r NAME -t demo/api:{{.Run.ID}} .ACR Tasks cloud build (no local Docker needed)
az acr import -n NAME --source docker.io/library/nginx:alpine -t base/nginx:alpineImport a public image into your private registry
az acr repository delete -n NAME --image demo/api:2.0Delete a manifest and all of its tags
az acr check-health -n NAME --yesDiagnose the local environment (Docker, CLI, DNS, auth)

Lab 8: push to ACR, pull on the VM with a managed identity (about 8 min)

PrerequisitesSteps 1–2 run on your machine (already az login-ed); from step 3 on, run on the VM. The VM needs the Azure CLI installed first (see Module 0).
[Your machine] Create the ACR
RG=rg-docker-lab
ACR=acrdockerlab$RANDOM          # must be globally unique; lowercase letters and digits only
az acr create -g $RG -n $ACR --sku Basic
echo "ACR=$ACR"                  # note this name; you need it on the VM
[Your machine] Enable a system-assigned managed identity on the VM and grant push permission
az vm identity assign -g $RG -n vm-docker
PRINCIPAL=$(az vm show -g $RG -n vm-docker --query identity.principalId -o tsv)
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment create --assignee-object-id $PRINCIPAL \
  --assignee-principal-type ServicePrincipal --role AcrPush --scope $ACR_ID

In this lab the VM both pushes and runs, so it gets AcrPush. In production, separate the build identity (AcrPush) from the runtime identity (AcrPull). Role assignments can take a few minutes to take effect. If your registry has the ABAC repository permissions mode enabled, use the "Container Registry Repository Writer" role instead.

[VM] Log in with the managed identity
export ACR=<name-from-previous-step>
az login --identity
az acr login --name $ACR
Login Succeeded
[VM] Tag and push
docker tag api:2.0 $ACR.azurecr.io/demo/api:2.0
docker push $ACR.azurecr.io/demo/api:2.0
The push refers to repository [acrdocker….azurecr.io/demo/api]
5f70bf18a086: Pushed
…
2.0: digest: sha256:… size: 1234
az acr repository show-tags -n $ACR --repository demo/api --detail -o table
docker buildx imagetools inspect $ACR.azurecr.io/demo/api:2.0
[VM] Delete the local image, then pull from ACR by digest and run
DIGEST=$(az acr repository show -n $ACR --image demo/api:2.0 --query digest -o tsv); echo $DIGEST
docker rmi $ACR.azurecr.io/demo/api:2.0 api:2.0
docker run -d --name fromacr -p 127.0.0.1:8001:8000 $ACR.azurecr.io/demo/api@$DIGEST
curl -s localhost:8001/ ; echo
[Anywhere] ACR Tasks cloud build (no local Docker needed; suits restricted CI environments)
cd ~/dockerlab/api
az acr build -r $ACR -t demo/api:{{.Run.ID}} -t demo/api:latest .
az acr repository show-tags -n $ACR --repository demo/api -o table
Token expiry demo: after 3 hours, docker push returns unauthorized: authentication required; just run az acr login again.
Cleanup (after the course, on your machine)
az group delete -n rg-docker-lab --yes --no-wait

Case 1: eliminating Docker Hub rate limits and supply-chain risk

Many CI jobs pulled base images anonymously from Docker Hub and kept hitting toomanyrequests. Approach: sync approved base images into an internal ACR with az acr import or ACR Artifact Cache (cache rules), standardize Dockerfiles on FROM myacr.azurecr.io/base/python:3.13-slim@sha256:…, and use Azure Policy to block AKS from pulling images from unapproved registries.

Case 2: ACR on a private network

Premium SKU + private endpoint + public network access disabled. Common failure: the VM still resolves myacr.azurecr.io to a public IP because the Private DNS Zone privatelink.azurecr.io is not linked to that VNet. Note that the data endpoint myacr.<region>.data.azurecr.io must also resolve. Verify with nslookup and az acr check-health.

Case 3: traceable releases

Every pipeline build produces an immutable tag (Git SHA or build number) plus SBOM/provenance, and deployment manifests reference the digest; an ACR retention policy cleans up untagged manifests; Defender for Containers continuously scans pushed images and blocks deployment when critical vulnerabilities are found.

Interactive troubleshooting decision tree

Common registry / ACR errors

unauthorized: authentication required / 401

The token has expired (3 hours) or you never logged in: run az acr login again. Make sure the registry name in the image name is all lowercase and matches the registry you logged in to.

denied: requested access to the resource is denied / 403

Authenticated but not authorized: pushing with only AcrPull; the role assignment has not taken effect yet; old AcrPull/AcrPush roles used in ABAC mode; network rules (firewall/private endpoint) denied access. Check with az role assignment list --scope $ACR_ID -o table.

Error response from daemon: Get "https://myacr.azurecr.io/v2/": dial tcp: lookup … no such host / i/o timeout

DNS or network issue: check the private DNS zone and whether outbound NSG/firewall rules allow *.azurecr.io and the data endpoint; a corporate proxy must be configured in the daemon (/etc/systemd/system/docker.service.d/http-proxy.conf).

az acr login: This command requires running the docker daemon

The current environment has no Docker daemon (e.g. Cloud Shell). Use az acr login -n NAME --expose-token and hand the token to another client.

x509: certificate signed by unknown authority

A corporate TLS inspection proxy replaced the certificate. Install the corporate root CA on the host (/usr/local/share/ca-certificates/ + update-ca-certificates), or place it at /etc/docker/certs.d/<registry>/ca.crt, then restart Docker.

Videos and official resources

NoteWe could not find a high-quality video with a verifiable uploader and duration that covers current ACR authentication (managed identity, ABAC mode). For this module, treat the official Microsoft Learn docs as authoritative so you do not pick up outdated practices (such as enabling the admin account).
▶
Docker Full Course — freeCodeCamp.org
About 7 hours · English · optional: the "Repositories / Docker Hub" chapter (general registry concepts)

Microsoft Learn (verified)

or score ≥ 70% on the Quiz

Cheat sheet

Docker Engine 29.x · Compose v5.x · Azure CLI · every code block can be copied with one click
After-class reference

System and daemon

docker version; docker info
docker context ls; docker context use NAME
docker system df -v
docker system events --since 10m
docker system prune -f            # stopped containers + dangling images + unused networks + build cache
sudo journalctl -u docker -f
sudo dockerd --validate --config-file /etc/docker/daemon.json

Images

docker pull IMG[:TAG|@sha256:…] [--platform linux/arm64]
docker image ls [--digests] [-f dangling=true]
docker image history --no-trunc IMG
docker image inspect -f '{{.Architecture}} {{.Config.User}}' IMG
docker buildx imagetools inspect IMG
docker tag SRC TARGET; docker rmi IMG
docker image prune -a --filter until=168h -f
docker image save -o x.tar IMG; docker image load -i x.tar

Containers

docker run -d --name N -p 127.0.0.1:8080:80 --restart unless-stopped \
  --memory 512m --cpus 1 --pids-limit 200 --init \
  --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges IMG
docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
docker logs -f --tail 100 N;  docker exec -it N sh
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' N
docker stats --no-stream;  docker top N;  docker diff N
docker stop -t 30 N;  docker kill -s HUP N;  docker rm -f N
docker update --restart=no --memory 1g --memory-swap 1g N
docker cp N:/path ./local

Build

docker build --check .
docker build -t IMG:TAG [--target S] [--build-arg K=V] [--progress=plain] .
docker build --secret id=x,src=./secret.txt -t IMG .
docker buildx build --platform linux/amd64,linux/arm64 -t REG/IMG:TAG --push .
docker buildx build --cache-from type=registry,ref=REG/IMG:cache \
  --cache-to type=registry,ref=REG/IMG:cache,mode=max -t REG/IMG:TAG --push .
docker buildx build --sbom=true --provenance=mode=max -t REG/IMG:TAG --push .
docker buildx ls; docker buildx du; docker builder prune --keep-storage 10GB -f

Networking

docker network ls
docker network create [--subnet 10.10.0.0/24] [--internal] NET
docker run --network NET --network-alias ALIAS IMG
docker network connect|disconnect NET CTR
docker network inspect NET
docker port CTR
docker run --rm -it --network container:CTR nicolaka/netshoot
sudo iptables -t nat -S DOCKER; sudo iptables -S DOCKER-USER

Storage

docker volume create|ls|inspect|rm VOL
docker volume prune [-a]             # by default removes only anonymous volumes
--mount type=volume,src=VOL,dst=/data
--mount type=bind,src=$PWD/conf,dst=/etc/app,readonly
--mount type=tmpfs,dst=/tmp,tmpfs-size=64m
docker run --rm -v VOL:/data:ro -v $PWD:/b alpine tar czf /b/vol.tgz -C /data .
docker run --rm -v VOL:/data -v $PWD:/b alpine tar xzf /b/vol.tgz -C /data

Compose

docker compose config [--quiet]
docker compose up -d [--build] [--wait] [--force-recreate]
docker compose ps; docker compose logs -f --tail 50 SVC
docker compose exec SVC sh; docker compose run --rm SVC CMD
docker compose up -d --scale SVC=3
docker compose --profile debug up -d
docker compose -f compose.yaml -f compose.prod.yaml up -d
docker compose watch
docker compose down [-v] [--rmi local]

Registry and ACR

az acr create -g RG -n ACR --sku Basic
az acr login -n ACR                       # token valid for 3 hours
TOKEN=$(az acr login -n ACR --expose-token --output tsv --query accessToken)
docker login ACR.azurecr.io -u 00000000-0000-0000-0000-000000000000 --password-stdin <<< $TOKEN
docker tag IMG ACR.azurecr.io/ns/img:tag; docker push ACR.azurecr.io/ns/img:tag
az acr repository list -n ACR -o table
az acr repository show-tags -n ACR --repository ns/img --detail -o table
az acr build -r ACR -t ns/img:{{.Run.ID}} .
az acr import -n ACR --source docker.io/library/nginx:alpine -t base/nginx:alpine
az login --identity                       # VM managed identity
az acr check-health -n ACR --yes

Quick troubleshooting table

SymptomCheck firstCommon cause
Container exits right after startingdocker logs <container>, docker inspect -f '{{.State.ExitCode}}'Wrong CMD, or the main process simply finishes
Port not reachableCheck port mappings with docker ps / docker portApp listens only on 127.0.0.1, or -p reversed (format is host:container)
Containers cannot reach each otherdocker network inspectNot on the same network, or using localhost
Slow buildsSee which layer misses the cache (--progress=plain)Wrong COPY order, or missing .dockerignore
Disk fulldocker system dfClean up with docker system prune (deletes unused resources; confirm before running)
exec format error in the cloudCheck the image architectureBuilt on an arm64 machine, run on amd64
Exited (137)docker inspect -f '{{.State.OOMKilled}}'Memory limit exceeded, or SIGKILL after stop timeout
push returns unauthorized / deniedaz acr login, check role assignmentsToken expired (3 hours) or missing push permission

For the fuller interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.

Recommended /etc/docker/daemon.json baseline (adjust before use)

{
  "live-restore": true,
  "log-driver": "local",
  "log-opts": { "max-size": "20m", "max-file": "5" },
  "default-address-pools": [ { "base": "10.200.0.0/16", "size": 24 } ],
  "userland-proxy": true,
  "features": { "containerd-snapshotter": true }
}

After editing, validate with sudo dockerd --validate --config-file /etc/docker/daemon.json, then run sudo systemctl restart docker. After switching the storage backend (containerd-snapshotter), existing images and containers are not visible in the new backend, so plan the migration first.

Capstone lab + final quiz

End to end: build → verify locally → push to ACR → deploy by digest → roll back
After class ≈ 30 minCovers all modules
ScenarioYou own an internal API service. The security team requires: the image runs as non-root, an SBOM is generated, deployments reference an immutable digest, the database is not exposed, and a failed release can be rolled back within 1 minute. Complete the whole flow on the Azure VM.
Code change and build (Module 4)
cd ~/dockerlab
sed -i 's/service="api"/service="api-v3"/' api/app.py
GIT_SHA=$(date +%s)   # in a real project use git rev-parse --short HEAD
docker build --check api
docker buildx build --sbom=true --provenance=mode=max \
  -t $ACR.azurecr.io/demo/api:$GIT_SHA --push api
Get the digest and generate the production override file (Modules 2, 7, 8)
DIGEST=$(az acr repository show -n $ACR --image demo/api:$GIT_SHA --query digest -o tsv)
cat > compose.prod.yaml <<EOF
services:
  api:
    build: !reset null
    image: $ACR.azurecr.io/demo/api@$DIGEST
EOF
docker compose -f compose.yaml -f compose.prod.yaml config | grep image:
Deploy with --wait as the gate (Modules 3, 7)
az acr login -n $ACR
docker compose -f compose.yaml -f compose.prod.yaml up -d --wait \
  && echo "DEPLOY OK" || echo "DEPLOY FAILED"
curl -s localhost:8080/ ; echo
Security checks (Modules 3, 5, 6)
docker compose exec api id                                    # should be uid=10001
sudo ss -lntp | grep -E ':5432|:8000' || echo "db/api not exposed on host ✓"
docker inspect -f '{{json .Mounts}}' dockerlab-db-1 | python3 -m json.tool | grep -E 'Type|Name'
docker buildx imagetools inspect $ACR.azurecr.io/demo/api:$GIT_SHA --format '{{json .SBOM}}' | head -c 300; echo
Simulate a bad release and roll back (Module 8 troubleshooting)
cp compose.prod.yaml compose.prod.yaml.good
sed -i "s#@sha256:.*#:does-not-exist#" compose.prod.yaml
docker compose -f compose.yaml -f compose.prod.yaml up -d --wait || {
  echo "release failed, rolling back"; cp compose.prod.yaml.good compose.prod.yaml
  docker compose -f compose.yaml -f compose.prod.yaml up -d --wait; }
curl -s localhost:8080/ ; echo
Wrap-up: docker compose down -v; on your machine run az group delete -n rg-docker-lab --yes --no-wait.
Acceptance checklist

Open-ended self-check (answer first, then expand the reference answer)

1. What is the difference between an image and a container? Where does data written inside a container go after you delete it?

An image is a read-only template; a container is a running instance of an image. Data written inside a container lives in its writable layer (upperdir) and disappears when the container is deleted, unless it is stored in a volume or bind mount.

2. Why COPY requirements.txt first and the rest of the code afterwards?

To take advantage of layer caching. Dependencies rarely change while code changes often; installing dependencies first means a code change does not reinstall them, so builds are much faster.

3. How do two containers reach each other? Why can't they use localhost?

Put both containers on the same user-defined network and use the container name (or Compose service name), resolved by the embedded DNS at 127.0.0.11. Each container has its own network namespace, so localhost points only to itself.

4. In -p 8080:80, which is the host port? Which address does it bind to by default?

8080 is the host port and 80 is the container port. By default it binds to 0.0.0.0 (and IPv6) and bypasses ufw; for local-only access write -p 127.0.0.1:8080:80.

5. Name 3 practices that make an image more cloud-ready.

Pin version tags or digests, use small base images and multi-stage builds, run as non-root, keep secrets out of the image, log to stdout, mind the CPU architecture, scan for vulnerabilities and generate an SBOM before pushing.

6. Why does docker stop take 10 seconds for an app started with a shell-form CMD?

PID 1 is /bin/sh, which does not forward SIGTERM to the app; after the 10-second timeout Docker sends SIGKILL (exit code 137). Use an exec-form CMD or --init.

Final quiz (12 questions covering all modules)

Sources & versions

Where every technical fact in this course was verified (verified on 2026-11-14)
TopicVerified findingSource
Docker Engine versionLatest stable 29.9.3 (2026-11-03); 29.0.0 released 2025-11-10Engine 29 release notes
Key Engine 29 changesNew installs default to the containerd image store; nftables firewall backend is experimental; cgroup v1 deprecated (supported until at least 2029-05); minimum API version v1.44, relaxed to v1.40 in 29.3.0; Docker Content Trust removed from the CLI; docker image ls defaults to a tree view; save/load support multi-platformSame as above
Ubuntu installdeb822-format docker.sources; supports 26.10, 26.04 LTS, 24.04 LTS, 22.04 LTS; ufw/firewalld are bypassed; compatible only with iptables-nft / iptables-legacyInstall Docker Engine on Ubuntu (2026-10-12)
Bridge networksUser-defined bridges provide DNS resolution between containers, better isolation, and hot attach/detachBridge network driver (2026-02-21)
Compose v5Can be embedded as an SDK; built-in builder removed, builds delegated to Docker Bake; v5.x continues to ship (e.g. v5.4.0)v5.0.0 release · v5.4.0 release · Compose history
ACR Docker CLIaz acr login is the recommended method; the login server name must be all lowercase; docker rmi only removes the local imageMicrosoft Learn (2026-02-27)
ACR authenticationToken valid for 3 hours; --expose-token usage; admin account for testing onlyMicrosoft Learn (2026-02-03)
ACR ABACDefault mode is "RBAC Registry Permissions"; in ABAC mode AcrPull/AcrPush/AcrDelete are not honoredAKS Engineering Blog (2026-01-23)

Content merge notes

This course incorporates all of "hour 1: Docker core fundamentals" (docker-hour1-fundamentals.ch.md): the concepts and analogy table (Module 1), Docker Desktop / Play with Docker as alternative environments (Module 0), the basic container warm-up and httpd exercise (Module 3), listening on 0.0.0.0 (Module 4), the 8 cloud-readiness rules and vulnerability scanning (Module 4), why containers cannot use localhost to reach each other (Module 5), the Flask + Redis starter lab (Modules 5B / 7B), mapping Compose to cloud platforms (Module 7), pushing to Docker Hub/ECR/Artifact Registry (Module 8), the quick troubleshooting table (cheat sheet), and the open-ended self-check (capstone lab page). The following updates were made during the merge:

  • Image versions aligned with those used in this course: nginx:1.27 → nginx:alpine, python:3.12-slim → python:3.13-slim, postgres:16 → postgres:17; version constraints added to dependencies (the original requirements.txt did not pin versions).
  • The Redis persistence check now uses docker stop + docker rm: the original used docker rm -f (SIGKILL), so Redis had no time to write its RDB snapshot and the counter reset to 1.
  • Docker Scout: the original said it "ships with Docker Desktop"; added that Docker Engine on Linux needs the Scout CLI plugin installed separately.
  • "Port not reachable" now includes the security note about the default 0.0.0.0 binding bypassing ufw.

Video verification notes

Every video link in the course was verified via third-party index pages for title, channel, video ID and (where available) duration and publish date: Fireship "Docker in 100 Seconds" (Gjnup-PuquQ, 2:07, 2020-08-17), "100+ Docker Concepts" (rIrNIzy6U_g, 8:28, 2024-03-12), "Learn Docker in 7 Easy Steps" (gAkwW2tuIqE); NetworkChuck "Docker networking is CRAZY!!" (bKFMS5C4CG0, 39:12, 2022-08-06); Christian Lempa "Docker Networking Tutorial" (5grbXvV_DSk, 19:46); freeCodeCamp "Docker Full Course" (rjjES5IsPdg, about 7 hours, article published 2026-06-04). All of these videos are in English, and most were recorded before Engine 29, so for version details rely on this course and the official docs.

Audio narration notes

The Audio tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time. Quality depends on the voices installed in your operating system: for example "Microsoft Aria/Jenny" on Windows or "Samantha" on macOS. If you need offline MP3s, feed the scripts to a TTS service such as Azure AI Speech (the environment that generated this course could not reach a TTS service, so no MP3s are embedded).

Known limitations

  • IDs, IPs, hashes, timings and column names in "Expected output" blocks are examples; your environment will differ.
  • Timings and image sizes in the animations are illustrative, meant to explain the concepts, not benchmark data.
  • CLI output formats may differ slightly between Engine 29 minor versions and between Compose v5 minor versions.