Docker Hour 1: Core Fundamentals
- Draw the full call chain of
docker runfrom 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
| # | Time | Module | Core content | Animation / interaction | Lab (Azure VM) |
|---|---|---|---|---|---|
| 0 | Before class | Setup | Create an Ubuntu VM with az CLI and install Docker from the official apt repository | — | Install + hello-world |
| 1 | 00–06 | Docker architecture | CLI → REST API → dockerd → containerd → shim → runc; namespaces, cgroups v2 | Step-by-step animation of the docker run call chain | docker info, inspect the process tree |
| 2 | 06–12 | Images | OCI images, layers, digests, containerd image store, copy-on-write | Layering + CoW demo | pull / history / inspect |
| 3 | 12–19 | Containers | Lifecycle, PID 1 and signals, exit codes, resource limits, restart policies | Clickable state machine | Resource limits and reproducing OOM |
| 4 | 19–28 | Dockerfile and BuildKit | Instruction semantics, cache invalidation, multi-stage builds, cache mounts, non-root | Build cache simulator | Build a Python API image |
| 5 | 28–36 | Networking | Network drivers, embedded DNS, port publishing and iptables | Packet path animation | User-defined networks and service-to-service access |
| 6 | 36–42 | Storage (volumes) | volume / bind / tmpfs, lifecycle, backup and restore | Where data goes after a container is removed | Postgres persistence and backup |
| 7 | 42–50 | Docker Compose | Compose spec, naming rules, healthcheck dependencies, profiles, watch | Startup order animation | web + api + db three-service stack |
| 8 | 50–60 | Registry · ACR · Troubleshooting | Tags vs digests, push/pull, ACR authentication, troubleshooting methods | Push flow animation + troubleshooting decision tree | Push to ACR, pull on the VM with a managed identity |
| — | After class | Cheat sheet · Capstone lab | End to end: build → scan → push → deploy | Final quiz | Capstone lab |
How to use this course
Concepts · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Audio narration · Videos
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).
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.
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)
- 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.
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
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
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.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
Module 1 · Docker architecture and internals
docker run through the whole call chain- 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)
| Concept | In one sentence | Analogy | See |
|---|---|---|---|
| Image | A read-only application package template containing code, dependencies and runtime environment | Class / installation disc | Module 2 |
| Container | A running instance of an image; essentially an isolated process | Object (instance) | Module 3 |
| Dockerfile | The script that builds an image | Recipe | Module 4 |
| Network | Lets containers communicate with each other | LAN | Module 5 |
| Volume | Keeps data after a container is removed | External hard drive | Module 6 |
| Compose | Declares multiple services in one YAML file | Orchestra score | Module 7 |
| Registry | Stores and distributes images: Docker Hub, Azure ACR, AWS ECR, GCP Artifact Registry | GitHub | Module 8 |
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
| Component | Responsibility | Interface | Why it is separate |
|---|---|---|---|
| docker CLI | Parses commands, calls the API | HTTP REST (Engine API) | One CLI can manage multiple remote Engines via docker context |
| dockerd | Image management, networking (libnetwork), volumes, BuildKit, API server | REST server; gRPC client | Provides developer-facing high-level abstractions |
| containerd | Container/task lifecycle, content store, snapshotter | gRPC (/run/containerd/containerd.sock) | CNCF graduated project, also used directly by Kubernetes (CRI) |
| containerd-shim-runc-v2 | One shim per container: holds stdio, reaps the exit code | ttrpc | Decouples containers from dockerd/containerd so containers keep running when the daemon restarts (with live-restore) |
| runc | OCI runtime: creates namespaces and cgroups per config.json, then execs the user process | CLI (OCI Runtime Spec) | Exits after creation; not long-running |
How: the three kernel pillars
pid, net, mnt, uts, ipc, user, cgroup. PID 1 inside the container is just an ordinary PID on the host.
memory.max, cpu.max, pids.max, io.max.
--memory and --cpus ultimately write to these files. Engine 29 has deprecated cgroup v1.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).
crictl talks to containerd directly. But OCI images built with Docker work identically on both.Architecture diagram: Docker Engine components
Flowchart: how a container process is born
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.
Core commands and flags
| Command | Purpose | Key flags / notes |
|---|---|---|
docker version | Shows Client/Server versions and API version | --format '{{.Server.Version}}' |
docker info | Engine-wide info: storage driver, cgroup, runtimes, registry mirrors | -f '{{.CgroupVersion}}' |
docker context ls / use | Switch the target Engine (local, remote over SSH) | docker context create vm1 --docker host=ssh://azureuser@IP |
docker system df | Disk usage of images, containers, volumes and build cache | -v shows details |
docker system events | Real-time event stream (create/start/die/oom) | --filter event=oom --since 10m |
systemctl status docker containerd | Check daemon status | journalctl -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
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)
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",
...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.
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;moby namespace):
sudo ctr -n moby containers ls sudo ctr -n moby tasks ls
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"
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.
Verified instructional videos
Official docs
Module 2 · Images: layers, content addressing and copy-on-write
- 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
| Object | Contents | Identifier |
|---|---|---|
| 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) |
| Manifest | Points to one config and an ordered list of layers | sha256:… |
| Config | ENV, CMD, ENTRYPOINT, WORKDIR, USER, history, rootfs diff_ids | The Image ID is usually computed from it or from the manifest (depends on the storage backend) |
| Layer | A 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-slimstore the base layers only once on disk and in the registry; push showsLayer 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)
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.
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/loadaccepts multiple--platformvalues. - Both compressed blobs and unpacked snapshots are kept, so disk usage may be higher than with overlay2.
docker image lsshows a tree view by default, listing each platform variant.
OCI image object graph
overlayfs union mount
Interactive demo: layer sharing and copy-on-write (CoW)
Click the buttons in order and watch how layers are reused, copied and masked.
Core commands and flags
| Command | Purpose | Common flags |
|---|---|---|
docker pull IMAGE[:TAG|@DIGEST] | Pull an image | --platform linux/arm64, -q |
docker image ls | List local images (tree view by default in Engine 29) | --digests, -f dangling=true, --format '{{.Repository}}:{{.Tag}}' |
docker image inspect | Show config, layers, architecture | -f '{{.Architecture}} {{.Config.Cmd}}' |
docker image history | Which instruction produced each layer, and layer sizes | --no-trunc, --format '{{.Size}}\t{{.CreatedBy}}' |
docker buildx imagetools inspect | Inspect a remote index/manifest without downloading the image | --raw, --format '{{json .Manifest}}' |
docker tag SRC TARGET | Add another name for the same image (no data copied) | — |
docker image rm / rmi | Remove a tag or an image | -f |
docker image prune | Remove dangling images | -a removes all unused images, --filter until=168h |
docker image save / load | Export/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)
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 resultdocker 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]
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.
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
Module 3 · Containers: lifecycle, signals and resource limits
- Master the container state machine: created → running ⇄ paused → exited → removed, and the command behind each transition.
- Understand the
docker stopsignal 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 stopwaits 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) orENTRYPOINT ["tini","--"]. - Shell-form trap:
CMD python app.pyactually 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 code | Meaning | Typical cause |
|---|---|---|
0 | Normal exit | Batch job finished |
1 | Application error | Uncaught exception, bad config |
125 | docker run itself failed | Bad flag, port already in use |
126 | Command cannot be executed | No execute permission, script has CRLF line endings |
127 | Command not found | Wrong PATH, no bash in slim/distroless images |
137 | 128+9 = SIGKILL | OOM killed (check .State.OOMKilled), or stop timeout |
143 | 128+15 = SIGTERM | Normal graceful stop |
139 | 128+11 = SIGSEGV | Segfault, often native deps mismatched with libc (musl vs glibc) |
When: choosing a restart policy
| Policy | Behavior | Use case |
|---|---|---|
no (default) | Never restarts automatically | One-off tasks |
on-failure[:5] | Restarts on non-zero exit, optional max retries | Batch jobs, workers |
always | Always restarts; also starts after a daemon restart (even if previously stopped manually) | Rarely used |
unless-stopped | Like always, but containers stopped manually are not started after a daemon restart | Preferred for long-running services on a single host |
unhealthy; it does not restart it automatically. Self-healing requires an orchestrator (AKS, Swarm) or external monitoring.Container state machine
docker stop signal timeline
Interactive state machine: click a command and watch the state change and the Engine's response
Key docker run flags
| Flag | Description | Example |
|---|---|---|
-d / -it | Detached / interactive terminal | docker run -it --rm alpine sh |
--name | Container name (its DNS name on user-defined networks) | --name api |
--rm | Remove automatically on exit | Throwaway debug containers |
-p host:ctr | Publish a port | -p 127.0.0.1:8080:80 (bind to loopback only) |
-e / --env-file | Environment variables | --env-file .env |
--memory / --memory-swap | Memory limit (cgroup memory.max) | --memory 512m --memory-swap 512m (equal values disable swap) |
--cpus | CPU quota (cpu.max) | --cpus 1.5 |
--pids-limit | Max number of processes, prevents fork bombs | --pids-limit 200 |
--restart | Restart policy | --restart unless-stopped |
--init | Use tini as PID 1 (forwards signals, reaps zombies) | — |
--user | Run as the given UID:GID | --user 10001:10001 |
--read-only + --tmpfs | Read-only root filesystem | --read-only --tmpfs /tmp |
--cap-drop / --cap-add | Trim Linux capabilities | --cap-drop ALL --cap-add NET_BIND_SERVICE |
--security-opt | Security 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-opt | Log rotation | --log-opt max-size=10m --log-opt max-file=3 |
Operations commands
| Command | Purpose |
|---|---|
docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | List all containers |
docker logs -f --tail 100 --since 10m web | Follow logs |
docker exec -it web sh | Get a shell in the container (new process, shared namespaces) |
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' web | Why it exited |
docker stats --no-stream | Live CPU, memory, network, IO data |
docker top web | Processes in the container (host view) |
docker stop -t 30 web / docker kill -s HUP web | Graceful stop / send any signal |
docker update --memory 1g --memory-swap 1g web | Change resource limits live |
docker cp web:/etc/nginx/nginx.conf . | Copy files between container and host |
docker container prune -f | Remove 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
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)
docker run -d --name nosig alpine sleep 300
time docker stop nosig
docker inspect -f 'exit={{.State.ExitCode}}' nosig
real 0m10.3s exit=137
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
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
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.
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
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.
Verified tutorial videos
Official docs
Module 4 · Dockerfile and BuildKit: fast, lean, secure images
- 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 whetherapt-get updatewould 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. .dockerignoredecides which files go into the build context: excluding.git,node_modulesand.envboth speeds up builds and keeps secrets out of the image.
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
| Pair | Difference | Recommendation |
|---|---|---|
CMD vs ENTRYPOINT | ENTRYPOINT is the fixed executable; CMD supplies default arguments, and docker run IMAGE args overrides CMD | Use exec form (JSON array) for both; end an ENTRYPOINT script with exec "$@" |
ARG vs ENV | ARG exists only at build time; ENV is written into the image and visible at runtime | Never pass secrets via ARG/ENV (they stay in the image history); use --mount=type=secret |
COPY vs ADD | ADD also auto-extracts local tar files and supports URLs and Git addresses | Use COPY by default; use ADD only when you need those features (optionally with --checksum) |
EXPOSE | Metadata only (documentation); it does not publish a port | Ports are actually published with -p or Compose ports |
RUN shell form vs exec form | Shell form supports && and variable expansion | Shell form is fine for RUN; use exec form for CMD/ENTRYPOINT |
When: use cases for advanced BuildKit features
| Feature | Syntax | Use case |
|---|---|---|
| Multi-stage build | FROM … AS builder + COPY --from=builder | The compiler toolchain stays out of the final image, which can shrink it several-fold |
| Cache mount | RUN --mount=type=cache,target=/root/.cache/pip pip install … | Package download cache is reused across builds and never enters an image layer |
| Secret mount | RUN --mount=type=secret,id=pipconf,target=/etc/pip.conf pip install … | Private package index credentials that never remain in any layer |
| Multi-platform | docker buildx build --platform linux/amd64,linux/arm64 | One tag serves both x86 and ARM nodes |
| Remote cache | --cache-to type=registry,ref=…:buildcache,mode=max | Reuse cache in CI when every run gets a fresh runner |
| Build checks | docker build --check . | Statically check the Dockerfile for common issues without building |
Multi-stage build data flow
How cache invalidation propagates
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.
Image size comparison (illustrative)
Key docker build / buildx options
| Option | Description |
|---|---|
-t name:tag | Tag the build result; you can pass multiple -t |
-f path/Dockerfile | Specify the Dockerfile path |
--target stage | Build only up to the given stage (e.g. a test stage) |
--build-arg K=V | Pass an ARG (never use it for secrets) |
--secret id=x,src=file / env=VAR | Provided to RUN --mount=type=secret,id=x |
--platform linux/amd64,linux/arm64 | Multi-platform build (the containerd image store can load it locally; otherwise use --push) |
--push / --load | After building, push directly / load into the local image store |
--cache-from / --cache-to | External cache: type=registry, type=gha, type=local |
--no-cache / --pull | Disable the cache / always check for base image updates |
--progress=plain | Full build log output (for troubleshooting) |
--check | Run build checks (lint) only, without building |
--provenance=true --sbom=true | Generate 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.
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# 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.
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
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)
healthydocker 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).
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
| # | Rule | Why / how |
|---|---|---|
| 1 | Pin 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 |
| 2 | Small base images | slim, alpine, distroless: faster pulls, smaller attack surface (note alpine uses musl libc) |
| 3 | Multi-stage builds | For compiled projects such as Go, Java or Node front ends, size usually drops dramatically |
| 4 | Never bake secrets into images | Inject at runtime via environment variables / Key Vault / Secrets Manager; use secret mounts at build time |
| 5 | Run as non-root | Required by many platforms and Kubernetes security policies |
| 6 | One concern per container | Deploy web and database separately, so each scales and upgrades independently |
| 7 | Log to stdout/stderr | Don't write to files inside the container; platforms such as Azure Monitor and CloudWatch collect standard output automatically (in Python, set PYTHONUNBUFFERED=1) |
| 8 | Mind the CPU architecture | Apple 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/revisionso 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.
Verified tutorial videos
Official documentation
Module 5 · Networking: drivers, DNS and port publishing
- 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
| Driver | How it works | Typical use | Cloud analogy |
|---|---|---|---|
bridge (default docker0) | Linux bridge + veth pair + NAT | Single-host containers | Like a private subnet + NAT gateway |
| User-defined bridge | Same as above, one br-xxxx per network, with embedded DNS | First choice for multiple services on one host (Compose default) | Dedicated subnet + private DNS zone |
| host | Shares the host's network namespace; no isolation, no NAT | Extremely performance-sensitive workloads, or when many ports are needed | Binding directly to the VM NIC |
| none | Loopback only | Offline batch jobs, security sandboxes | No NIC |
| overlay | VXLAN tunnels across hosts | Swarm multi-host networking | Cross-VNet peering |
| macvlan / ipvlan | Containers get a MAC/IP directly on the physical network | Legacy systems, devices that must sit directly on the L2 network | Note: 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
--networkjoins 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/disconnectwhile running. - Configurable: Each network can have its own subnet, gateway, MTU and so on.
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
-p 8080:80→ dockerd writes a DNAT rule into theDOCKERchain of the nat table:dpt:8080 → 172.18.0.2:80.- The filter table allows the forwarded traffic and provides the
DOCKER-USERchain for your own filtering rules (this chain takes effect before Docker's own rules). - Access to localhost from the host itself may be forwarded by the
docker-proxy(userland proxy) process. - Container egress traffic: SNAT via
MASQUERADE, reaching external networks with the host IP.
-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
Animation A: inbound packet path (curl http://VM:8080)
Animation B: service name resolution (api reaching db)
docker network commands
| Command | Description |
|---|---|
docker network ls | Three networks exist by default: bridge, host, none |
docker network create --driver bridge --subnet 10.10.0.0/24 --gateway 10.10.0.1 appnet | Create a custom network (subnet optional) |
docker network create --internal backend | Internal 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 api | Connect/disconnect a network at runtime |
docker network inspect appnet -f '{{json .Containers}}' | Show containers and IPs on the network |
docker network prune | Remove unused networks |
docker port api | Show port mappings |
-p 8080:80 / -p 127.0.0.1:8080:80 / -p 8080:80/udp / -P | Publish 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-gateway | Custom 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)
docker run -d --name a1 alpine sleep 600 docker run --rm alpine ping -c1 a1
ping: bad address 'a1'
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}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.
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
sudo ss -lntp | grep 5432 || echo "5432 not listening on the host -- correct"
docker network connect appnet a1 docker exec a1 ping -c1 db docker network disconnect appnet a1
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.
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"]
EOFdocker 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)
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
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
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.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
- Is the app listening on
0.0.0.0? If it listens only on127.0.0.1, it cannot be reached from outside the container (Flask's default behavior). - Confirm the mapping with
docker port NAME; is it bound to 127.0.0.1? - NSG inbound rules, the
DOCKER-USERchain. - 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.
Verified tutorial videos
Official docs
Module 6 · Storage and volumes: making data outlive the container
- 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
-vand--mountsyntaxes. - Back up and restore volumes, and handle UID/GID permission issues.
What: three mount types
| Type | Data location | Managed by | Lifecycle | Typical use |
|---|---|---|---|---|
| volume (named volume) | /var/lib/docker/volumes/<name>/_data | Docker | Independent of the container; must be removed explicitly | Databases, persistent business data (preferred in production) |
| Anonymous volume | Same as above, named with a random hash | Docker | Removed with the container when using --rm or docker rm -v | Paths declared by the VOLUME instruction in the image |
| bind mount | Any path on the host | You | Same as the host files | Injecting config files, mounting source code during development, reading host logs |
| tmpfs | Host memory | Kernel | Gone when the container stops | Temporary 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 exist | Silently creates an empty directory (owned by root), often masking typos | Fails immediately: bind source path does not exist |
| Recommendation | Quick interactive use | Scripts 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.
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
Decision flow
Simulator: is the data still there after this operation?
docker volume and mount options
| Command / option | Description |
|---|---|
docker volume create pgdata | Create a named volume (it can also be created automatically on first use) |
docker volume ls -f dangling=true | List volumes not referenced by any container |
docker volume inspect pgdata | Show Mountpoint, Driver, Labels |
docker volume rm pgdata | Remove a volume (fails if a container references it) |
docker volume prune | By default removes only unused anonymous volumes; add -a to also remove unused named volumes |
--mount type=volume,src=pgdata,dst=/var/lib/postgresql/data | Mount a named volume |
--mount type=bind,src=$PWD/nginx.conf,dst=/etc/nginx/nginx.conf,readonly | Bind-mount a single file read-only |
--mount type=tmpfs,dst=/tmp,tmpfs-size=64m | Size-limited tmpfs |
-v pgdata:/var/lib/postgresql/data / -v ./conf:/etc/app:ro | Short form |
--volumes-from other | Reuse 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)
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');"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
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
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
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
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
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
Official documentation
Module 7 · Docker Compose: declarative orchestration of multi-service apps
- Understand the Compose "project" model and its resource naming rules.
- Use
healthcheck+depends_on.condition: service_healthyto 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 -drecreates only the services whose configuration changed. - Automatic networking: a
<project>_defaultnetwork 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)
| Resource | Name format | Example (project directory dockerlab) |
|---|---|---|
| Project name | Defaults 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
| condition | Meaning |
|---|---|
service_started (default for the short list form) | The dependency's container has merely started; this does not mean the service is ready |
service_healthy | Starts only after the dependency's healthcheck reports healthy |
service_completed_successfully | The 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:
| Compose | Azure Container Apps | AWS ECS | Kubernetes / AKS |
|---|---|---|---|
| service | Container App (or multiple containers in one app) | Task Definition + Service | Deployment + Service |
ports | Ingress | ALB Target Group | Service / Ingress |
environment / secrets | Environment variables / Secrets (can reference Key Vault) | Environment variables / Secrets Manager | ConfigMap / Secret |
volumes | Azure Files volume | EFS volume | PersistentVolumeClaim |
healthcheck | Health probes | Container health check | liveness / readiness probe |
--scale | Replica count / KEDA autoscaling | desiredCount / Auto Scaling | replicas / HPA |
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
Startup order animation: docker compose up -d
docker compose commands
| Command | Description |
|---|---|
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 api | View service logs |
docker compose exec db psql -U postgres | Run 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 config | Print the final config after variable interpolation and merging (first stop when troubleshooting) |
docker compose up -d --scale api=3 | Scale (the service must not set container_name or a fixed host port) |
docker compose watch | Watch for file changes and sync/rebuild automatically (uses the develop.watch config) |
docker compose --profile debug up -d | Enable services in a specific profile |
docker compose -f compose.yaml -f compose.prod.yaml up -d | Merge and override multiple files |
docker compose pull / build / restart / stop / top / events | Other common operations |
docker compose down | Remove containers and networks (volumes are kept) |
docker compose down -v --rmi local | Also 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.
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
EOFname: 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"
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
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}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.
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 resettingdocker compose --profile debug up -d # additionally starts adminer docker compose watch # edit api/app.py in another terminal and watch it sync and restart
docker compose --profile debug down -v
Lab 7B (beginner): turn the Flask + Redis app from Module 5B into Compose
~/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: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
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.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:.
Verified tutorial videos
docker-compose (v1) and the top-level version: field; follow the v5 syntax on this page instead.Official docs
Module 8 · Registries, ACR integration and troubleshooting
- Break down the image reference
registry/namespace/repo:tag@digestand 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"
- push: for each layer, first send
HEAD /v2/<repo>/blobs/<digest>; if it exists, skip it (Layer already exists), otherwise upload it; finallyPUT /v2/<repo>/manifests/<tag>. - pull:
GET manifest→ select by platform → download only the blobs not present locally → verify digests → unpack into snapshots. - 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)
| Method | Use case | Notes |
|---|---|---|
az acr login --name X | Interactive use by engineers | Uses 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 identity | Unattended pulls from VMs, AKS, Container Apps, App Service; pushes from Azure pipelines | Preferred; no secrets to rotate |
| Service principal | CI/CD outside Azure | For 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 partners | Can be limited to specific repositories and actions |
| Admin user | Testing only | Docs: "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
Layered troubleshooting model
Animation: docker push myacr.azurecr.io/demo/api:2.0
Registry-related Docker commands
| Command | Description |
|---|---|
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.0 | Add a name that includes the registry (must use the full, all-lowercase login server name) |
docker push myacr.azurecr.io/demo/api:2.0 | Push |
docker push --all-tags myacr.azurecr.io/demo/api | Push all local tags of a repository |
docker buildx imagetools inspect REF | Show a remote image's digest and platforms |
docker logout REGISTRY | Remove 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)
| Command | Description |
|---|---|
az acr create -g RG -n NAME --sku Basic|Standard|Premium | Create a registry (name is globally unique, 5–50 alphanumeric characters) |
az acr login -n NAME | Log Docker in with your current Entra identity (3-hour token) |
az acr login -n NAME --expose-token | Output the token only, for environments without a Docker daemon |
az acr repository list -n NAME -o table | List repositories |
az acr repository show-tags -n NAME --repository demo/api --detail -o table | List tags with digests |
az acr manifest list-metadata -r NAME -n demo/api | Show 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:alpine | Import a public image into your private registry |
az acr repository delete -n NAME --image demo/api:2.0 | Delete a manifest and all of its tags |
az acr check-health -n NAME --yes | Diagnose the local environment (Docker, CLI, DNS, auth) |
Lab 8: push to ACR, pull on the VM with a managed identity (about 8 min)
az login-ed); from step 3 on, run on the VM. The VM needs the Azure CLI installed first (see Module 0).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
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.
export ACR=<name-from-previous-step> az login --identity az acr login --name $ACR
Login Succeeded
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
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
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 tabledocker push returns unauthorized: authentication required; just run az acr login again.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
Microsoft Learn (verified)
- Push and pull images with the Docker CLI (last updated 2026-02-27)
- Authentication options (last updated 2026-02-03)
- Troubleshoot registry login
- ACR Repository Permissions with ABAC (AKS Engineering Blog, 2026-01-23)
Cheat sheet
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.tarContainers
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 ./localBuild
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 --yesQuick troubleshooting table
| Symptom | Check first | Common cause |
|---|---|---|
| Container exits right after starting | docker logs <container>, docker inspect -f '{{.State.ExitCode}}' | Wrong CMD, or the main process simply finishes |
| Port not reachable | Check port mappings with docker ps / docker port | App listens only on 127.0.0.1, or -p reversed (format is host:container) |
| Containers cannot reach each other | docker network inspect | Not on the same network, or using localhost |
| Slow builds | See which layer misses the cache (--progress=plain) | Wrong COPY order, or missing .dockerignore |
| Disk full | docker system df | Clean up with docker system prune (deletes unused resources; confirm before running) |
| exec format error in the cloud | Check the image architecture | Built 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 / denied | az acr login, check role assignments | Token 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
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
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: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
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; echocp 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/ ; echodocker compose down -v; on your machine run az group delete -n rg-docker-lab --yes --no-wait.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
| Topic | Verified finding | Source |
|---|---|---|
| Docker Engine version | Latest stable 29.9.3 (2026-11-03); 29.0.0 released 2025-11-10 | Engine 29 release notes |
| Key Engine 29 changes | New 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-platform | Same as above |
| Ubuntu install | deb822-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-legacy | Install Docker Engine on Ubuntu (2026-10-12) |
| Bridge networks | User-defined bridges provide DNS resolution between containers, better isolation, and hot attach/detach | Bridge network driver (2026-02-21) |
| Compose v5 | Can 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 CLI | az acr login is the recommended method; the login server name must be all lowercase; docker rmi only removes the local image | Microsoft Learn (2026-02-27) |
| ACR authentication | Token valid for 3 hours; --expose-token usage; admin account for testing only | Microsoft Learn (2026-02-03) |
| ACR ABAC | Default mode is "RBAC Registry Permissions"; in ABAC mode AcrPull/AcrPush/AcrDelete are not honored | AKS 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 useddocker 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.