Docker Hour 8 (Optional): 50 Production Problems + 50 Interview Questions
- Given an exact error message, tell whether it belongs to the build, runtime, network, or storage/daemon/registry layer, and name the first diagnostic command.
- Understand the mechanism behind each problem (cache keys, PID 1, cgroups, DNAT, embedded DNS, copy-on-write, the credential chain) instead of just memorizing fix commands.
- Reproduce, diagnose, fix and clean up the 16 most typical failures on a disposable Ubuntu VM.
- Answer 50 common Docker interview questions with the structure "30-second answer → in-depth mechanism → production experience", and handle common follow-ups.
- Quantify your mastery with mock interviews (timer + self-rating) and find your weak modules.
1-hour schedule
| # | Time | Module | Content | Interactive |
|---|---|---|---|---|
| 0 | Before class | How to use this lesson and the failure lab environment | Ubuntu 24.04 VM + Docker Engine 29; safety rules | Environment self-check |
| 1 | 00–08 | A · Build & Images | Problems 1–12: context, cache, COPY, multi-stage, architecture, proxy, size, secrets, disk, failed to solve, tag drift, rate limits | Error search · build troubleshooting tree |
| 2 | 08–16 | A · Container Runtime & Resources | Problems 13–25: exit codes, OOM, signals, zombies, CRLF, permissions, restart loops, health checks, CPU throttling, time zones | Exit-code troubleshooting tree |
| 3 | 16–24 | A · Networking, Ports & DNS | Problems 26–38: listen address, port conflicts, localhost, DNS, ufw, subnets, MTU, proxies, iptables, IPv6, Compose networks, host mode | "Port unreachable" troubleshooting tree |
| 4 | 24–30 | A · Storage, Logs, Daemon & Registry | Problems 39–50: data loss, masking, UIDs, logs, read-only root, daemon.json, socket, registry auth, manifest, x509, containerd image store | Daemon/registry troubleshooting tree |
| 5 | 30–37 | B · Fundamentals & Architecture | Questions 1–13 | Mock interview |
| 6 | 37–44 | B · Images & Dockerfile | Questions 14–25 | Mock interview |
| 7 | 44–52 | B · Networking, Storage & Compose | Questions 26–38 | Mock interview |
| 8 | 52–60 | B · Security, Production & Orchestration | Questions 39–50 | Mock interview |
| — | After class | Cheat sheet · Final drills | 50 entries of "error → first command → fix"; 50 flashcards; 8 mixed failures; full mock interview | Final quiz, 12 questions |
How to use this lesson
- In the module's Overview tab, search for the error's most distinctive words (e.g.
exec format,allocated,x509). - Click a table row to open its entry in Problem Details, then follow "diagnostic commands → compare with the sample output → fix".
- Not sure which layer? The Decision Tree tab narrows it down from the symptom step by step.
- All 50 entries are also in the cheat sheet, which is handy to print and pin at your desk.
- Start with the Overview table and pick out the questions you are unsure of by difficulty.
- Use the Mock Interview: random questions, a 2-minute countdown, answer out loud before revealing the reference answer, then rate yourself "Got it / Partial / Missed". Scores are stored locally in your browser.
- Go through the interview flashcards the night before; before the interview, do the full mock interview (10 random questions).
- Answer structure: one-sentence conclusion → mechanism → commands/configuration → pitfalls you hit in production.
Overview of Parts A and B
Each entry: symptom → root cause (at the mechanism level) → diagnostic commands → sample output → fix → prevention and best practices → which of the first seven lessons covers it. Error messages use Docker's actual wording where possible; it may vary slightly between versions, as noted.
Each question: 30-second answer → in-depth answer (mechanism, commands, configuration) → common follow-up questions → bonus points → common wrong answers. Difficulty levels are JuniorMidSenior.
How this lesson relates to the first seven
| Lesson | Most referenced in this lesson |
|---|---|
| Lesson 1 Core fundamentals | Architecture, image layers, Dockerfile/BuildKit, networking, storage, Compose, registries |
| Lesson 2 Production readiness | ENTRYPOINT/CMD, signals and graceful shutdown, multi-stage builds, resource limits, HEALTHCHECK, hardening |
| Lesson 3 Azure · Lesson 4 AWS | ACR/ECR authentication, image pull failures in the cloud, architecture mismatches |
| Lesson 5 Image CI, supply chain and release | Image CI and OIDC, tagging and promotion, SBOMs and scanning, signing, release and rollback |
| Lesson 6 Application architecture | Connection pools, gateways, migrations, dependency readiness |
| Lesson 7 Deep troubleshooting | tcpdump/strace/nsenter, SNAT/MTU, build performance, advanced networking |
Module 0 · How to Use This Lesson and the Failure Lab Environment (Before Class)
- Lessons 1 and 2 completed (Lessons 3–7 are optional; relevant entries link to them).
- An Ubuntu 24.04 VM you can rebuild at any time (2 vCPU / 4 GB RAM / 30 GB disk is enough), or Docker Desktop (some network labs behave differently there, as noted in the entries).
Option A: Ubuntu 24.04 VM + Docker Engine 29 (recommended)
Install from Docker's official apt repository (same as Lesson 1 Module 0):
sudo apt-get update && sudo apt-get 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 echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo $VERSION_CODENAME) stable" | sudo tee /etc/apt/sources.list.d/docker.list sudo apt-get update sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin sudo usermod -aG docker $USER # takes effect after logging in again; note that the docker group is equivalent to root newgrp docker
The install commands follow Install Docker Engine on Ubuntu; if they later switch to a deb822-style docker.sources file, follow them.
Environment self-check
docker version --format 'Client {{.Client.Version}} / Server {{.Server.Version}}'
docker compose version
docker buildx version
docker info --format 'Storage: {{.Driver}} · Cgroup: {{.CgroupDriver}} v{{.CgroupVersion}} · Root: {{.DockerRootDir}}'
docker info --format '{{json .DriverStatus}}' # with the containerd image store you will see io.containerd.snapshotter.v1
sudo apt-get install -y jq curl dnsutils iproute2 tcpdump # diagnostic tools
Client 29.x.x / Server 29.x.x Docker Compose version v5.x.x github.com/docker/buildx v0.x.x ... Storage: overlayfs · Cgroup: systemd v2 · Root: /var/lib/docker [["driver-type","io.containerd.snapshotter.v1"]]
Upgraded machines may still show Storage: overlay2 (the classic graphdriver); see problem 50 for the difference.
Option B: Docker Desktop
- Desktop runs dockerd inside a Linux VM, so VM networking sits between the host and containers: problems involving
--network host, iptables, ufw and MTU (some entries in 26–38) behave differently. - On Desktop you can reach the host via
host.docker.internal; Linux Engine needs--add-host=host.docker.internal:host-gateway.
Safety rules (must read)
sudo cp /etc/docker/daemon.json /etc/docker/daemon.json.bak (if it exists); afterwards, restore using each lab's "Clean up" steps.- All labs name containers, networks and volumes with the
lab8-prefix; clean up precisely withdocker ps -aq --filter name=lab8-instead of casually runningdocker system prune -a --volumes. - Never use real secrets in the labs; the secret-leak lab uses the fake value
FAKE-TOKEN-123. - Labs that change firewall rules can lock you out of SSH on a cloud VM: make sure you have console access first.
A general four-step troubleshooting method (used throughout Part A)
| Step | Command | Question it answers |
|---|---|---|
| 1 Check status | docker ps -a · docker inspect -f '{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}' C | Is it running? How did it exit? |
| 2 Check logs | docker logs --tail 100 -t C · journalctl -u docker --since -10m | What did the app/daemon say? |
| 3 Check config | docker inspect C (Config/HostConfig/Mounts/NetworkSettings) | Which settings are actually in effect? |
| 4 Go inside | docker exec -it C sh · docker debug C (provided by Docker Desktop; see the official docs for availability) · nsenter | Reproduce from the container's point of view |
For deeper tools (tcpdump, strace, py-spy, nsenter) see Lesson 7.
Module 1 · Part A: Build & Images (Problems 1–12)
- Locate a build failure in the right BuildKit phase: load Dockerfile → resolve base image → transfer context → execute instructions → export image.
- Understand how the cache key derives from "instruction text + parent layer + file-content checksums", and avoid pointless misses.
- Handle and prevent environment problems such as architecture mismatches, network/proxy, disk space and rate limits.
Type a keyword from the error (e.g. not found, exec format, toomanyrequests) to filter; click a row to open its entry in "Problem Details".
#1 The build hangs right at the start: => [internal] load build context … transferring context: 2.31GB
Symptom: Every docker build first spends tens of seconds to several minutes on "transferring context", and the image unexpectedly contains .git, node_modules and .env.
Root cause: The build context is the entire content of the PATH directory in docker build PATH, and BuildKit has to sync it (on demand) to the builder. Without a .dockerignore, local dependency folders, Git history, build artifacts and logs are all sent; combined with COPY . ., these files also land in image layers, and any change to any of them invalidates the cache of COPY . ..
Diagnostic commands
docker build --progress=plain -t lab8-app . 2>&1 | grep -E 'transferring context|load build context' du -sh .[!.]* * 2>/dev/null | sort -h | tail # find large directories cat .dockerignore 2>/dev/null || echo "no .dockerignore"
#5 [internal] load build context #5 transferring context: 2.31GB 48.2s done 1.1G node_modules 820M .git no .dockerignore
Fix
.git node_modules **/__pycache__ dist *.log .env .env.* Dockerfile* compose*.yaml
Or narrow the build context to a subdirectory: docker build -f docker/Dockerfile ./app.
Prevention and best practices
- Commit a
.dockerignoreon day one of a new project; an allowlist (*followed by!src,!package*.json) is the safest style. - Use precise
COPYinstructions in the Dockerfile instead ofCOPY . .. - Record the "transferring context" size in CI and alert when it exceeds a threshold.
See Lesson 1 Module 4 (Dockerfile and BuildKit), Lesson 7 Builds at scale.
#2 Changed one line of code and npm ci / pip install runs from scratch again (cache fully invalidated)
Symptom: The dependency install step in the build log never shows CACHED; every build takes 3–10 minutes.
Root cause: BuildKit computes cache keys in instruction order: for RUN it is "parent layer + command text", and for COPY/ADD it also includes the content checksums of the copied files. Once one step misses the cache, every later step has to run again. The common pattern of COPY . . before RUN npm ci means any source change reruns the dependency install. Other causes: ARG/ENV values that differ each time (such as a build timestamp), or CI building on a fresh builder every time (no cache import/export).
Diagnostic commands
docker build --progress=plain . 2>&1 | grep -E '^#[0-9]+ \[|CACHED' docker history --no-trunc lab8-app | head # which instruction produced each layer docker buildx du --verbose | head -30 # is the build cache still there?
#7 [2/5] WORKDIR /app #7 CACHED #8 [3/5] COPY . . #9 [4/5] RUN npm ci ← no CACHED, because the content of #8 changed
Fix
FROM node:22-slim WORKDIR /app COPY package.json package-lock.json ./ # copy only the dependency manifests first RUN --mount=type=cache,target=/root/.npm npm ci COPY . . # source code goes last CMD ["node","server.js"]
Enable a remote cache in CI: docker buildx build --cache-from type=registry,ref=REG/app:buildcache --cache-to type=registry,ref=REG/app:buildcache,mode=max . (on GitHub Actions you can use type=gha).
Prevention and best practices
- Order instructions from least to most frequently changing.
- Do not put ARGs that change every build, such as
BUILD_DATE, near the top of the Dockerfile; if needed, use them in a LABEL in the last layer. - Use a cache mount for the package manager's download directory so downloads are reused even when the layer cache misses.
See Lesson 1 Module 4, Lesson 2 CI module, Lesson 7 Build performance.
#3 ERROR: failed to build: failed to solve: failed to compute cache key: failed to calculate checksum of ref …: "/requirements.txt": not found
Symptom: COPY requirements.txt . reports not found, although the file is clearly in the repository. Older versions/the classic builder word it as COPY failed: file not found in build context or excluded by .dockerignore (wording varies by version).
Root cause: COPY source paths are always relative to the build-context root, not to the directory containing the Dockerfile, and you cannot escape the context with ../. Three common causes: ① building with -f sub/Dockerfile . while writing paths relative to the Dockerfile's directory; ② the file is excluded by .dockerignore (e.g. an allowlist forgot it); ③ letter case differs (Windows/macOS file systems are case-insensitive, the Linux builder is not).
Diagnostic commands
# see what the builder actually received: list the context with a throwaway Dockerfile printf 'FROM busybox\nCOPY . /ctx\nRUN find /ctx -maxdepth 2 | sort\n' | docker build --no-cache --progress=plain -f - . 2>&1 | grep /ctx grep -n '' .dockerignore git ls-files | grep -i requirements
#6 0.21 /ctx #6 0.21 /ctx/app #6 0.21 /ctx/app/requirements.txt ← actually under app/ 1:* 2:!src
Fix
Make the COPY path relative to the context root (COPY app/requirements.txt .), or change the context to ./app; add !app/requirements.txt to the .dockerignore allowlist; make file-name case consistent.
Prevention and best practices
- Agree that "context = repository root or service directory" and pin the build command in the README/Makefile/bake file.
- When you need files outside the context, use a BuildKit named context:
docker buildx build --build-context shared=../shared ., thenCOPY --from=shared ….
See Lesson 1 Module 4.
#4 Multi-stage build: failed to resolve source metadata for docker.io/library/build:latest … pull access denied
Symptom: COPY --from=build /app/dist ./dist fails, and BuildKit actually tries to pull an image called build from Docker Hub; or the copy succeeds but the target is empty or not the expected files.
Root cause: The value of --from is first matched against stage names (FROM … AS builder); if nothing matches, it is treated as an image reference and pulled. So a misspelled stage name (build vs builder) turns into "pull a non-existent image". Another case is a wrong path: the artifact is actually in /src/dist but is copied from /app/dist because of a different WORKDIR. Also note that BuildKit builds only the stages the target depends on; with --target, unreferenced stages are skipped.
Diagnostic commands
grep -nE '^FROM|--from' Dockerfile docker build --target builder -t lab8-builder . && docker run --rm lab8-builder ls -la /app /src 2>&1 | head docker build --check . # static Dockerfile checks (BuildKit build checks)
1:FROM node:22 AS builder 9:COPY --from=build /app/dist ./dist ERROR: failed to build: failed to solve: build: failed to resolve source metadata for docker.io/library/build:latest: pull access denied, repository does not exist or may require authorization
Fix
Use consistent stage names (COPY --from=builder); first build the intermediate stage with --target builder and ls to confirm the artifact path; use meaningful lowercase stage names (build checks warn about inconsistent casing).
Prevention and best practices
- Run
docker build --checkin CI and treat build-check warnings as errors (you can put# check=error=truein the Dockerfile). - Set
WORKDIRexplicitly in every stage to avoid path assumptions.
#5 exec /usr/local/bin/docker-entrypoint.sh: exec format error
Symptom: The image runs fine on an Apple Silicon laptop, but after being pushed to the registry it exits immediately on x86_64 servers / ECS / Container Apps, and the log contains only this line. There may also be a runtime warning: WARNING: The requested image's platform (linux/arm64) does not match the detected host platform (linux/amd64/v3) and no specific platform was requested.
Root cause: The binary in the image was compiled for a different CPU architecture, and the kernel's execve() cannot recognize the ELF format. docker build builds for the local architecture by default; without binfmt/QEMU, foreign binaries cannot run. A rarer cause: a script without a shebang (#!/bin/sh) also produces exec format error.
Diagnostic commands
docker image inspect --format '{{.Os}}/{{.Architecture}}{{if .Variant}}/{{.Variant}}{{end}}' myapp:1.0
docker buildx imagetools inspect REG/myapp:1.0 | grep -i platform
uname -m
head -c 4 entrypoint.sh | od -c | head -1 # does it start with #! ?
linux/arm64 Platform: linux/arm64 x86_64
Fix
# build and push a multi-arch image (needs a docker-container builder or the containerd image store) docker buildx create --name multi --use 2>/dev/null || true docker run --privileged --rm tonistiigi/binfmt --install all # only if you need QEMU emulation docker buildx build --platform linux/amd64,linux/arm64 -t REG/myapp:1.0 --push .
For languages that cross-compile well, such as Go and Rust, prefer FROM --platform=$BUILDPLATFORM + TARGETOS/TARGETARCH in the Dockerfile; cross-compiling is much faster than QEMU.
Prevention and best practices
- Build multi-arch images consistently in CI; specify the architecture explicitly on the deployment platform (e.g.
runtimePlatformin an ECS task). - Assert the platform list with
imagetools inspectbefore releasing.
See Lesson 3 Troubleshooting in the cloud, Lesson 4 ECS troubleshooting, Lesson 7 Builds at scale.
#6 RUN apt-get update: Temporary failure resolving 'deb.debian.org' / pip: Max retries exceeded … ConnectTimeoutError
Symptom: On the same machine curl can reach the internet, but apt-get, pip and npm time out or fail to resolve during the build. Most common on corporate networks, VPNs and air-gapped data centers.
Root cause: RUN executes in an isolated network namespace: ① an HTTP proxy configured on the host through environment variables is not automatically passed into the build container; ② when the host's /etc/resolv.conf points to 127.0.0.53 (systemd-resolved), Docker cannot use a loopback DNS inside the container and falls back to other upstreams (with the default bridge it may fall back to public DNS, which the corporate network blocks); ③ a corporate TLS-intercepting proxy causes SSL: CERTIFICATE_VERIFY_FAILED.
Diagnostic commands
docker run --rm busybox nslookup deb.debian.org # does runtime DNS work? docker run --rm busybox cat /etc/resolv.conf env | grep -i _proxy docker build --progress=plain --no-cache . 2>&1 | grep -iE 'resolv|timeout|proxy|certificate'
nslookup: can't resolve 'deb.debian.org' nameserver 8.8.8.8 ← the corporate network blocks external DNS HTTPS_PROXY=http://proxy.corp:3128
Fix
# 1) Proxy: HTTP_PROXY/HTTPS_PROXY/NO_PROXY are predefined ARGs; no need to declare them in the Dockerfile, and they are not written to the image history
docker build --build-arg HTTPS_PROXY=$HTTPS_PROXY --build-arg NO_PROXY=$NO_PROXY .
# or configure "proxies" in ~/.docker/config.json; the CLI injects them into builds and containers automatically
# 2) DNS: /etc/docker/daemon.json
# { "dns": ["10.0.0.2", "10.0.0.3"] } then sudo systemctl restart docker
# 3) Temporary workaround: docker build --network=host .
Corporate CA: in the Dockerfile, COPY corp-ca.crt /usr/local/share/ca-certificates/ and then RUN update-ca-certificates, or mount it temporarily with RUN --mount=type=secret.
Prevention and best practices
- Do not hard-code
ENV HTTP_PROXY=…in the Dockerfile (it ends up in the image, and production traffic would go through the proxy too). - On internal networks, use apt/pip/npm mirrors or an Artifactory/Nexus proxy repository, configured centrally on the CI builders.
See Lesson 1 Module 5 (Networking), Lesson 7 Advanced networking; for proxy configuration, the official doc Use a proxy server with the Docker CLI is authoritative.
#7 1.8GB image: slow pulls, slow cold starts, hundreds of CVEs in the vulnerability scan
Symptom: docker images shows a Python/Node service image larger than 1GB; during autoscaling, a new instance needs 1–2 minutes just to pull the image.
Root cause: ① A full base image (python:3.13 ships a compiler toolchain); ② build tools, source code and test data are left in the final image; ③ downloading in one layer and deleting in another — the delete only adds a whiteout in the upper layer, and the data is still in the lower layer; ④ package manager caches (/var/lib/apt/lists, ~/.cache/pip) are not cleaned.
Diagnostic commands
docker images myapp --format '{{.Repository}}:{{.Tag}} {{.Size}}'
docker history --format 'table {{.Size}}\t{{.CreatedBy}}' myapp:1.0 | head -15
# optional: inspect wasted space layer by layer with dive
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive myapp:1.0
myapp:1.0 1.82GB SIZE CREATED BY 612MB RUN /bin/sh -c pip install -r requirements.txt 1.02GB (layers of the base image python:3.13)
Fix
FROM python:3.13-slim AS build WORKDIR /app COPY requirements.txt . RUN --mount=type=cache,target=/root/.cache/pip pip wheel --wheel-dir /wheels -r requirements.txt FROM python:3.13-slim WORKDIR /app COPY --from=build /wheels /wheels RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels COPY src/ ./src/ USER 10001 CMD ["python","-m","src.main"]
Clean up apt in the same layer as the install: apt-get install -y --no-install-recommends … && rm -rf /var/lib/apt/lists/*.
Prevention and best practices
- Minimal base images such as slim / distroless / Chainguard + multi-stage builds.
- Set an image size budget in CI (e.g. fail above 300MB), and scan regularly with
docker scout cvesor Trivy.
#8 Security scan: NPM_TOKEN / AWS_SECRET_ACCESS_KEY visible in docker history
Symptom: To install private dependencies, the Dockerfile used ARG NPM_TOKEN or COPY .npmrc, followed by RUN rm .npmrc. The security team still extracted the token from the image. BuildKit build checks report a SecretsUsedInArgOrEnv warning.
Root cause: An image is a stack of read-only layers: a file added by COPY lives in that layer's tarball, and a later rm only masks it in an upper layer. An ARG used in a RUN appears as an environment variable in the image history/build metadata, and an ENV is stored directly in the image config. Anyone who can pull the image can see it.
Diagnostic commands
docker history --no-trunc myapp:1.0 | grep -iE 'token|secret|password'
docker image inspect -f '{{json .Config.Env}}' myapp:1.0
docker save myapp:1.0 -o /tmp/img.tar && tar -tf /tmp/img.tar | head # layer tarballs can be unpacked and inspected directly
<missing> RUN |1 NPM_TOKEN=FAKE-TOKEN-123 /bin/sh -c npm ci ... ["PATH=/usr/local/bin:...","NODE_ENV=production"]
Fix
# syntax=docker/dockerfile:1 RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:1.1 . # For private Git repos use SSH forwarding: RUN --mount=type=ssh … with docker build --ssh default .
Immediately rotate any leaked token, and delete the old image tags from the registry (remember the image may already be cached elsewhere).
Prevention and best practices
- Enable build checks in CI and scan images for secrets (Trivy
--scanners secret, Docker Scout, etc.). - Inject runtime secrets with the orchestrator's secret mechanism; never bake them into the image.
#9 ERROR: failed to solve: … write /var/lib/docker/…: no space left on device (during build)
Symptom: After a few weeks, builds on a CI machine or dev box start failing; df -h shows the partition holding /var/lib/docker at 100%.
Root cause: BuildKit's build cache (intermediate layers, cache mounts, multiple copies of multi-arch artifacts) exists independently of images, and docker image prune does not clean it; every --no-cache build or code change adds new cache records. Dangling images (<none>), stopped containers and anonymous volumes live on the same partition. Another case is inode exhaustion (df -i), easily triggered by node_modules layers with huge numbers of small files.
Diagnostic commands
df -h /var/lib/docker; df -i /var/lib/docker docker system df docker buildx du | tail -3
TYPE TOTAL ACTIVE SIZE RECLAIMABLE Images 41 6 18.2GB 14.9GB (81%) Containers 9 2 1.1GB 1.0GB (90%) Local Volumes 12 3 4.4GB 3.9GB (88%) Build Cache 612 0 27.5GB 27.5GB
Fix
docker builder prune --filter until=72h -f # remove build cache older than 72 hours docker builder prune --keep-storage 10GB -f # or keep only 10GB (check the flag name with docker builder prune --help) docker image prune -f # dangling images docker container prune -f
Prevention and best practices
- Configure garbage collection for the built-in builder in
daemon.json("builder": {"gc": {"enabled": true, "defaultKeepStorage": "20GB"}}; the official Build garbage collection page is authoritative for field names). - Put
/var/lib/dockeron its own disk and monitor usage; rebuild CI runners periodically. - Do not casually run
prune -a --volumeson a shared host — it deletes volumes other people need.
See Lesson 1 Module 3 (Images), problem #42 (logs and disk).
#10 ERROR: failed to solve: process "/bin/sh -c npm run build" did not complete successfully: exit code: 1
Symptom: The build fails at some RUN step, the default progress output shows only the last few lines and the real error is collapsed; or a step "succeeds" but produces a broken artifact.
Root cause: "failed to solve" is just BuildKit's outer message saying it failed to solve the build graph; the real cause is in the stderr of the RUN command. Another subtle class of problem is shell semantics: in RUN curl … | tar x, curl fails but tar succeeds, the pipeline returns 0, and the build continues with a missing artifact (/bin/sh has no pipefail by default).
Diagnostic commands
docker build --progress=plain . 2>&1 | tail -60 # build up to the stage before the failure and run the step by hand inside a container docker build --target deps -t lab8-debug . && docker run --rm -it lab8-debug sh # experimental debugger (see the official docs): BUILDX_EXPERIMENTAL=1 docker buildx debug build .
#11 [build 5/6] RUN npm run build #11 2.913 Error: Cannot find module '@internal/ui' #11 ERROR: process "/bin/sh -c npm run build" did not complete successfully: exit code: 1
Fix
Fix it based on the real stderr (here a private package was not installed; see the secret mount in #8). Rewrite pipelines like this:
SHELL ["/bin/bash", "-o", "pipefail", "-c"] RUN curl -fsSL https://example.com/tool.tgz | tar -xz -C /usr/local/bin
Prevention and best practices
- Always use
--progress=plainin CI so logs are searchable. - Always add
-ftocurlso HTTP 4xx/5xx returns non-zero. - Split long RUNs into separately debuggable stages (
deps,build,test) and pinpoint failures with--target.
#11 Built/ran fine yesterday, the same Dockerfile fails today (base image tag drift)
Symptom: No code change, but after a rebuild you get ModuleNotFoundError, glibc version errors, changed OpenSSL behavior, or a sudden change in image size.
Root cause: A tag is a mutable pointer: python:3, node:lts and ubuntu:latest move to a new digest with each upstream release (e.g. a Debian major switch bookworm → trixie, or a Python minor upgrade). Combined with unpinned apt-get install pkg and unlocked pip install, builds are not reproducible.
Diagnostic commands
docker image inspect --format '{{index .RepoDigests 0}}' python:3.13-slim
docker buildx imagetools inspect python:3.13-slim | head -5
docker run --rm python:3.13-slim sh -c 'cat /etc/os-release | head -2; python -V'
python@sha256:3f1d…a9 Name: docker.io/library/python:3.13-slim Digest: sha256:8c2e…71 ← differs from the digest recorded in last week's build PRETTY_NAME="Debian GNU/Linux 13 (trixie)"
Fix
FROM python:3.13-slim-bookworm@sha256:<verified digest>
Lock dependencies (package-lock.json, poetry.lock, requirements.txt with hashes). Let Renovate/Dependabot open PRs that update digests, so upgrades go through CI tests instead of "happening silently".
Prevention and best practices
- Write tags down to the distro codename (
-bookworm) and pin the digest; reference image digests in production deployments. - Record the base image digest for every build artifact (already included in SBOM / provenance attestations).
#12 toomanyrequests: You have reached your unauthenticated pull rate limit. https://www.docker.com/increase-rate-limit
Symptom: At CI peak times, or when many nodes pull from Docker Hub at once, FROM or docker pull returns 429. Most common when all nodes share one NAT egress.
Root cause: Docker Hub rate-limits pulls per account (authenticated) or per source IP (anonymous); corporate NAT makes hundreds of runners share one IP's anonymous quota. The exact limits change; Docker Hub usage and limits is authoritative.
Diagnostic commands
# check the remaining quota (method from the official docs; see the ratelimit-limit / ratelimit-remaining headers) TOKEN=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull" | jq -r .token) curl -s --head -H "Authorization: Bearer $TOKEN" https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest | grep -i ratelimit docker info | grep -i -A2 'registry mirrors'
ratelimit-limit: 100;w=21600 ratelimit-remaining: 0;w=21600
Fix
- Run
docker loginin CI (with an organization access token) so the quota is counted per account. - Use a pull-through cache: a self-hosted
registry:2proxy cache (daemon.json"registry-mirrors"only applies to Docker Hub), a Harbor proxy project, ACR Artifact Cache, or ECR pull-through cache. - Import frequently used base images into your own private registry (
az acr import,crane copy).
Prevention and best practices
- Never make production deployments depend directly on Docker Hub availability; mirror base images into an internal registry.
- Reuse layer caches on CI builders to reduce repeated pulls.
Build failure troubleshooting decision tree
Pick your symptom and step through to the diagnostic commands and a conclusion; every step reflects real BuildKit behavior.
~/lab8-build.Lab 1-A: Oversized context and .dockerignore (#1)
mkdir -p ~/lab8-build/big && cd ~/lab8-build/big
mkdir -p node_modules .git && head -c 300M /dev/urandom > node_modules/blob && head -c 100M /dev/urandom > .git/pack
echo 'console.log("hi")' > app.js
printf 'FROM node:22-alpine\nWORKDIR /app\nCOPY . .\nCMD ["node","app.js"]\n' > Dockerfiledocker build --progress=plain -t lab8-big . 2>&1 | grep 'transferring context'
docker images lab8-big --format '{{.Size}}'#5 transferring context: 419.47MB 3.1s done 585MB
printf 'node_modules\n.git\n' > .dockerignore
docker build --progress=plain -t lab8-big . 2>&1 | grep 'transferring context'
docker images lab8-big --format '{{.Size}}'#5 transferring context: 87B done 165MB
docker rmi lab8-big; rm -rf ~/lab8-build/bigLab 1-B: COPY paths are relative to the context (#3)
mkdir -p ~/lab8-build/ctx/docker ~/lab8-build/ctx/app && cd ~/lab8-build/ctx echo flask > app/requirements.txt printf 'FROM python:3.13-slim\nCOPY requirements.txt .\n' > docker/Dockerfile docker build -f docker/Dockerfile -t lab8-ctx . 2>&1 | tail -2
ERROR: failed to build: failed to solve: failed to compute cache key: failed to calculate checksum of ref ...: "/requirements.txt": not found
sed -i 's#COPY requirements.txt#COPY app/requirements.txt#' docker/Dockerfile, the rebuild should succeed.docker rmi lab8-ctx; rm -rf ~/lab8-build/ctxLab 1-C: Secret leaked into the image history (#8)
mkdir -p ~/lab8-build/sec && cd ~/lab8-build/sec cat > Dockerfile <<'EOF' FROM alpine:3.22 ARG TOKEN RUN echo "using $TOKEN" > /dev/null EOF docker build --build-arg TOKEN=FAKE-TOKEN-123 -t lab8-leak . 2>&1 | grep -i -A2 warn docker history --no-trunc lab8-leak | grep FAKE
WARN: SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ARG "TOKEN") ... <missing> ... RUN |1 TOKEN=FAKE-TOKEN-123 /bin/sh -c echo "using $TOKEN" > /dev/null ...
Replace the alpine tag with a currently available version; the exact warning wording depends on your version.
cat > Dockerfile <<'EOF' # syntax=docker/dockerfile:1 FROM alpine:3.22 RUN --mount=type=secret,id=token,env=TOKEN test -n "$TOKEN" && echo ok EOF echo FAKE-TOKEN-123 > token.txt docker build --secret id=token,src=token.txt -t lab8-noleak . docker history --no-trunc lab8-noleak | grep -c FAKE # prints 0
The env= option requires a recent Dockerfile frontend (see the official docs); with older versions, read the default /run/secrets/token file instead.
docker rmi lab8-leak lab8-noleak; rm -rf ~/lab8-build/secLab 1-D: Architecture mismatch (#5)
uname -m # x86_64 ls /proc/sys/fs/binfmt_misc/ | grep -i qemu || echo "QEMU binfmt not installed" docker run --rm --platform linux/arm64 alpine:3.22 uname -m
QEMU binfmt not installed exec /bin/uname: exec format error
aarch64: docker run --privileged --rm tonistiigi/binfmt --install arm64. This shows that whether "an image runs" depends on whether the host kernel can execute binaries for that architecture.docker run --privileged --rm tonistiigi/binfmt --uninstall qemu-aarch64 (optional); docker image rm alpine:3.22.Video tutorials (titles and channels verified via YouTube oEmbed)
No verified video dedicated to troubleshooting build errors was found. Here is a 3-minute script you can record yourself:
- (0:00) Run
docker build --progress=plainin a terminal and point out the #N step numbers and CACHED markers. - (0:40) Show
transferring contextdropping from 400MB to 87B (Lab 1-A). - (1:20) Reorder the COPY instructions and show the dependency layer becoming CACHED.
- (2:00) Find the leaked token with
docker history --no-truncand switch to a secret mount. - (2:40) Recap: locate the phase first, then find the cause.
Official documentation
Module 2 · Part A: Container Runtime & Resources (Problems 13–25)
- Know where to look from the exit code alone: 0 / 1 / 125 / 126 / 127 / 137 / 139 / 143.
- Understand the special semantics of PID 1 on Linux (ignores signals by default, reaps zombies) and Docker's stop sequence (SIGTERM → grace period → SIGKILL).
- Use cgroup v2 statistics files to identify OOM kills and CPU throttling.
Type an exit code or error keyword (e.g. 137, OOM, unhealthy) to filter; click a row to jump to the details.
#13 docker ps -a: Exited (0) 2 seconds ago — the container exits "normally" right after starting
Symptom: docker run -d myimg returns a container ID, but the container immediately becomes Exited (0); the log is empty or has a single "started" line.
Root cause: A container lives exactly as long as its main process (PID 1). When the main process ends normally (exit code 0), the container stops. Typical causes: ① the main command sends the service to the background (service nginx start, nginx in its default daemon mode, java -jar app.jar &) and the script then ends; ② the entrypoint script lacks a final exec "$@", so CMD never runs; ③ the default CMD of docker run ubuntu is bash, and without -it stdin is closed, so bash reads EOF and exits immediately.
Diagnostic commands
docker ps -a --filter name=web --format '{{.Names}} {{.Status}}'
docker inspect -f 'Entrypoint={{json .Config.Entrypoint}} Cmd={{json .Config.Cmd}}' web
docker logs web
docker run --rm -it --entrypoint sh myimg # enter the image and run the start command by hand
web Exited (0) 2 seconds ago Entrypoint=["/entrypoint.sh"] Cmd=["nginx"] Starting nginx: nginx.
Fix
Run the service in the foreground: CMD ["nginx","-g","daemon off;"]; run Java/Node directly as the main process; end the entrypoint script with exec "$@". When debugging an image, keep it running with docker run -it or sleep infinity.
Prevention and best practices
- One main process per container; if you need several processes, split them into Compose services, and use supervisord/s6 only when truly necessary.
- Exited (0) does not mean "no problem"; configure alerts for long-running services.
See Lesson 1 Module 3 (Container lifecycle), Lesson 2 ENTRYPOINT/CMD.
#14 STATUS stuck at Restarting (1) 5 seconds ago (restart loop / Exited (1))
Symptom: A container with --restart unless-stopped or Compose restart: always keeps restarting and its RestartCount keeps growing; without a restart policy it shows Exited (1).
Root cause: Exit code 1 is a generic error reported by the application itself: a missing environment variable, a config syntax error, a dependency (database) not ready yet so the connection fails, a failed migration, and so on. The restart policy just keeps retrying with an increasing delay (starting at 100ms and doubling, with a cap; reset once the container has run for more than 10 seconds); it does not fix anything, and if the dependency never becomes ready, you get a loop.
Diagnostic commands
docker inspect -f '{{.State.ExitCode}} restarts={{.RestartCount}} started={{.State.StartedAt}}' api
docker logs --tail 50 -t api # logs from previous runs are visible even while restarting
docker events --filter container=api --since 10m --format '{{.Time}} {{.Action}}'
docker update --restart=no api # stop the loop first to make debugging easier
1 restarts=17 started=2026-11-15T03:12:44.1Z 2026-11-15T03:12:44Z KeyError: 'DATABASE_URL' 1763176364 die 1763176364 start
Fix
Fix the configuration based on the logs. For dependency-readiness problems, use depends_on: {db: {condition: service_healthy}} in Compose, and also implement connection retries with back-off in the application itself (orchestrators do not guarantee start order).
Prevention and best practices
- Validate required configuration at startup and print a clear error (fail fast).
- Monitor
RestartCountordieevents indocker events. - In Kubernetes the same symptom is called CrashLoopBackOff.
See Lesson 2 Advanced Compose, Lesson 6 Dependency readiness and migrations.
#15 Exit code 125: docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "3f2a…". You have to remove (or rename) that container to be able to reuse that name.
Symptom: The second run of a deployment script's docker run --name web … fails, and echo $? prints 125. Other 125 cases: unknown arguments (unknown flag), an invalid --memory value, a missing mount source, and so on.
Root cause: Exit code 125 means the docker command itself or the daemon failed; the container was never created/started, and the application is not involved. Container names are unique per host, and stopped containers still hold their names; --rm containers are removed only after they exit.
Diagnostic commands
docker run --name web -d nginx:alpine; echo "exit=$?"
docker ps -a --filter name=^/web$ --format '{{.ID}} {{.Status}} {{.Image}}'
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "3f2a9c…". You have to remove (or rename) that container to be able to reuse that name. exit=125 3f2a9c1d0b7e Exited (0) 3 hours ago nginx:alpine
Fix
docker rm -f web 2>/dev/null; docker run -d --name web nginx:alpine # idempotent form for scripts # better: manage it with Compose; docker compose up -d replaces containers whose config changed
Prevention and best practices
- Deploy with declarative tools (Compose, an orchestrator) rather than hand-written
docker runscripts. - Make scripts distinguish exit codes: 125 → check docker arguments; 126/127 → check the image command (#16).
Exit codes are defined in docker run · Exit status; see also Lesson 1 Module 3.
#16 Exit code 127 / 126: exec: "python": executable file not found in $PATH / exec: "/app/run.sh": permission denied
Symptom: The full error looks like docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "python": executable file not found in $PATH: unknown (wording varies by version). docker run returns 127; permission problems return 126.
Root cause: runc failed when calling execve() inside the container to start the given command. 127: the command does not exist in the image's $PATH (slim images ship only python3, distroless has no shell, a typo, or a multi-stage build forgot to copy it). 126: the file exists but is not executable (missing x bit, on a noexec mount, or it is a directory).
Diagnostic commands
docker run --rm --entrypoint sh myimg -c 'echo $PATH; command -v python python3; ls -l /app/run.sh'
docker image inspect -f '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' myimg
git ls-files -s run.sh # 100644 means no executable bit in the repository
/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin /usr/local/bin/python3 -rw-r--r-- 1 root root 112 Nov 15 03:00 /app/run.sh 100644 5d1f… 0 run.sh
Fix
Fix the command name or use an absolute path; in the Dockerfile use COPY --chmod=0755 run.sh /app/ (supported by BuildKit) or run git update-index --chmod=+x run.sh; with distroless images call the binary directly in exec form, without relying on a shell.
Prevention and best practices
- Use the JSON (exec) form for CMD/ENTRYPOINT with absolute paths.
- Run a smoke test in CI after building the image (
docker run --rm img --version).
#17 Exited (137) — State.OOMKilled: true (killed for exceeding the memory limit)
Symptom: After running for a while, the container exits with code 137; the host's dmesg shows Memory cgroup out of memory: Killed process … (java).
Root cause: 137 = 128 + 9, meaning the process received SIGKILL. With --memory set, the container cgroup's memory.max applies; when memory (including non-reclaimable page cache and tmpfs) exceeds the limit, the kernel OOM killer kills a process inside that cgroup. Note: 137 can also come from docker kill or a stop timeout (#19), so you must check the OOMKilled field. Runtimes such as the JVM that are not aware of container limits size their heap too large.
Diagnostic commands
docker inspect -f 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} limit={{.HostConfig.Memory}}' api
docker stats --no-stream api
sudo dmesg -T | grep -i 'out of memory' | tail -3
CID=$(docker inspect -f '{{.Id}}' api); cat /sys/fs/cgroup/system.slice/docker-$CID.scope/memory.events 2>/dev/null
exit=137 oom=true limit=268435456 [Sat Nov 15 03:20:11 2026] Memory cgroup out of memory: Killed process 4121 (java) total-vm:... anon-rss:262144kB oom 3 oom_kill 3
The cgroup path depends on the cgroup driver (with the systemd driver it is system.slice/docker-<id>.scope); the directory is removed once the container stops.
Fix
Size the limit from the measured peak (leave 20–30% headroom); use -XX:MaxRAMPercentage=75 for the JVM and --max-old-space-size for Node; hunt for memory leaks (Lesson 7 py-spy/heap dumps); also set --memory-swap equal to --memory so swapping does not slow things down.
Prevention and best practices
- Set a memory limit on every production container and alert on OOM events (
docker events --filter event=oom). - Record memory curves during load tests and set the limit from the P99 peak.
See Lesson 2 Resource limits, Lesson 7 Performance analysis.
#18 Exited (139) — segmentation fault (SIGSEGV), common with alpine/musl or native extensions
Symptom: The container exits with 139 right after starting, or crashes on specific requests; the log may contain only Segmentation fault (core dumped), or nothing at all.
Root cause: 139 = 128 + 11 (SIGSEGV): the process accessed invalid memory. Common causes with containers: ① running a binary or wheel compiled for glibc on alpine (musl libc); ② native extensions that do not match the library versions in the base image (OpenSSL/ICU changed after a base image upgrade); ③ incompatibilities when running a foreign architecture under QEMU; ④ thread stacks too small (musl's default thread stack is smaller than glibc's), crashing deep recursion.
Diagnostic commands
docker inspect -f '{{.State.ExitCode}} {{.State.Error}}' worker
docker run --rm --entrypoint sh myimg -c 'ldd /usr/local/bin/worker; cat /etc/os-release | head -1'
sudo dmesg -T | grep -i segfault | tail -2
139 /lib64/ld-linux-x86-64.so.2 (0x7f…) Error relocating /usr/local/bin/worker: __memcpy_chk: symbol not found NAME="Alpine Linux" worker[5120]: segfault at 0 ip 00007f… error 4 in libc.musl-x86_64.so.1
Fix
Switch to a glibc base image that matches the binary (-slim, distroless/cc), or compile from source against musl on alpine; pin the base image digest and run integration tests before upgrading; if you need core dumps, use --ulimit core=-1 and configure core_pattern on the host.
Prevention and best practices
- For Python/Node services with native extensions, prefer Debian slim over alpine.
- Test multi-arch images on the real target architecture, not only under QEMU.
See Lesson 2 Multi-stage builds and base image choice, Lesson 7 strace/gdb.
#19 docker stop always waits 10 seconds and ends with Exited (137) instead of 0/143
Symptom: Stops and rolling releases are slow; the application never performs a graceful shutdown (in-flight requests are cut off, unflushed data is lost).
Root cause: docker stop first sends STOPSIGNAL (SIGTERM by default) to PID 1, waits for the grace period (10 seconds by default, adjustable with -t / stop_grace_period), then sends SIGKILL. The Linux kernel gives PID 1 special protection: signals for which PID 1 has not registered a handler are ignored. The shell form CMD python app.py actually runs /bin/sh -c "python app.py", so PID 1 is sh, which does not forward SIGTERM to its child; the application never receives it even if it registered a handler. A process that handles SIGTERM properly usually exits with 0 or 143 (128+15).
Diagnostic commands
docker exec api ps -o pid,comm,args | head -3
docker image inspect -f '{{json .Config.Cmd}} stopsignal={{.Config.StopSignal}}' myimg
time docker stop api; docker inspect -f '{{.State.ExitCode}}' api
PID COMMAND COMMAND 1 sh /bin/sh -c python app.py 7 python python app.py ["/bin/sh","-c","python app.py"] stopsignal= real 0m10.4s 137
Fix
Switch to the exec form CMD ["python","app.py"]; in entrypoint scripts hand PID 1 to the application with exec "$@"; implement SIGTERM handling in the app (stop accepting new requests, wait for in-flight requests, close connection pools); if the framework expects a different signal (e.g. nginx graceful shutdown uses SIGQUIT), set STOPSIGNAL.
Prevention and best practices
- Set the grace period to "longest request time + headroom", coordinated with the load balancer's deregistration delay.
- Measure
docker stopduration in CI and treat anything over 3 seconds as a regression.
#20 ps shows lots of <defunct> zombie processes, eventually fork: Resource temporarily unavailable
Symptom: The container periodically spawns child processes (health-check scripts, external commands, a headless browser); after a few days ps is full of [sh] <defunct>; with --pids-limit set, no new processes can be created once the limit is reached.
Root cause: When a child exits, its parent must reap it with wait(); if the parent exits first, the orphan is adopted by PID 1 of its PID namespace. In a container PID 1 is your application, which usually does not reap children it does not know about, so zombies pile up and consume PID table entries.
Diagnostic commands
docker exec worker ps -eo pid,ppid,stat,comm | awk '$3 ~ /Z/' | head
docker exec worker ps -eo stat | grep -c Z
docker inspect -f 'init={{.HostConfig.Init}} pids={{.HostConfig.PidsLimit}}' worker
311 1 Z chrome <defunct> 312 1 Z chrome <defunct> … 4821 init=<nil> pids=<nil>
Fix
docker run --init (Compose: init: true): Docker injects a tiny init (docker-init, based on tini) as PID 1 that forwards signals and reaps zombies; or install tini in the image and use ENTRYPOINT ["/usr/bin/tini","--"].
Prevention and best practices
- Always enable init for containers that spawn child processes.
- Set
--pids-limitso a fork bomb cannot affect the host.
#21 exec /entrypoint.sh: no such file or directory (although the file exists — CRLF line endings)
Symptom: An entrypoint script edited on Windows fails at runtime with no such file or directory, yet docker run --entrypoint sh img -c 'ls -l /entrypoint.sh' shows the file. Running it directly may also show /bin/sh^M: bad interpreter.
Root cause: The first line of the script is #!/bin/sh\r\n, so the kernel looks for an interpreter named /bin/sh\r, which does not exist, and returns ENOENT — the "file" in the error is the interpreter, not the script. Git on Windows with core.autocrlf=true converts LF to CRLF on checkout. The same error appears when running a binary that needs the glibc dynamic loader on alpine (the interpreter /lib64/ld-linux-x86-64.so.2 does not exist).
Diagnostic commands
file entrypoint.sh head -1 entrypoint.sh | od -c | head -2 git config core.autocrlf; git ls-files --eol entrypoint.sh
entrypoint.sh: POSIX shell script, ASCII text executable, with CRLF line terminators 0000000 # ! / b i n / s h \r \n true i/lf w/crlf attr/ entrypoint.sh
Fix
printf '*.sh text eol=lf\nDockerfile text eol=lf\n' >> .gitattributes git add --renormalize . && git commit -m "Normalize line endings" # fallback: in the Dockerfile, RUN sed -i 's/\r$//' /entrypoint.sh
Prevention and best practices
- Commit a
.gitattributesto the repository; configure editors to use LF. - Check for CRLF in CI with
fileor shellcheck.
#22 PermissionError: [Errno 13] Permission denied: '/app/data' (after switching to a non-root user)
Symptom: After adding USER 10001 to harden the image, the application fails to write its log/cache/upload directory; or it fails on Kubernetes/OpenShift when run with a random UID.
Root cause: Permission checks inside a container are ordinary Linux DAC: the process UID/GID is compared with the file owner and mode bits. COPY sets file ownership to root (0:0) by default, and directories created by WORKDIR also belong to root, so a non-root process cannot write to them. (For UID mismatches on volume mounts see #41. Binding ports below 1024 is usually not a problem in Docker, because Docker sets net.ipv4.ip_unprivileged_port_start=0 in the container's network namespace by default; see the official docs.)
Diagnostic commands
docker exec api id
docker exec api ls -ld /app /app/data
docker image inspect -f 'User={{.Config.User}}' myimg
uid=10001 gid=10001 groups=10001 drwxr-xr-x 1 root root 4096 Nov 15 03:00 /app drwxr-xr-x 2 root root 4096 Nov 15 03:00 /app/data User=10001
Fix
RUN groupadd -g 10001 app && useradd -u 10001 -g app -M -s /usr/sbin/nologin app \ && mkdir -p /app/data && chown app:app /app/data COPY --chown=10001:10001 src/ /app/src/ USER 10001:10001
Grant write access only to directories that need it; on platforms that run arbitrary UIDs (OpenShift), make the directory group 0 and group-writable (chgrp 0 … && chmod g=u …).
Prevention and best practices
- Keep code directories read-only (owned by root, process non-root); put writable data on volumes or tmpfs.
- Use a numeric UID in USER so Kubernetes
runAsNonRootcan verify it.
See Lesson 2 Hardening.
#23 STATUS: Up 5 minutes (unhealthy) — the health check keeps failing
Symptom: The service is actually reachable, but the container stays unhealthy, Compose services with depends_on: condition: service_healthy never start, or Swarm keeps replacing the task.
Root cause: The HEALTHCHECK command runs inside the container; exit code 0 means healthy, 1 unhealthy. Common reasons for failure: ① the image has no curl/wget (slim, distroless), so the command itself returns 127; ② the checked port/path is wrong, or the app listens only after startup completes; ③ timeout or start_period is too short for a slow-starting app; ④ the health endpoint depends on the database, so a database hiccup makes every instance unhealthy. Docker itself does not restart a container because it is unhealthy (only Swarm/orchestrators replace it).
Diagnostic commands
docker inspect -f '{{json .State.Health}}' api | jq '.Status, .FailingStreak, .Log[-1]'
docker inspect -f '{{json .Config.Healthcheck}}' api | jq
docker exec api sh -c 'command -v curl wget; echo $?'
"unhealthy"
12
{ "ExitCode": 127, "Output": "/bin/sh: 1: curl: not found\n", ... }
Fix
# no curl needed: check with the runtime's own capabilities
HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \
CMD ["python","-c","import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz',timeout=2).status==200 else 1)"]
Prevention and best practices
- The health endpoint should check only the service itself (liveness); put dependency checks on an endpoint with readiness semantics.
- Engine 25+ supports
--start-intervalto check more often during startup (see the official docs). - Note that Kubernetes and Container Apps do not use the HEALTHCHECK in the image.
See Lesson 2 HEALTHCHECK.
#24 CPU at only 30%, yet P99 latency spikes periodically (CPU throttling)
Symptom: A multi-threaded service (Java, Go, Node workers) with --cpus=1 shows low average CPU in monitoring, but obvious latency spikes, with stalls roughly every 100ms.
Root cause: --cpus is implemented with CFS bandwidth control: each period (100ms by default) the cgroup gets a quota (cpu.max, e.g. 100000 100000). With 8 threads running in parallel, the quota is used up in 12.5ms, and for the remaining 87.5ms the whole cgroup is throttled and requests have to wait. Average utilization hides this. On top of that, runtimes size thread pools by the host core count (GOMAXPROCS, JVM GC threads), which amplifies the problem.
Diagnostic commands
docker inspect -f 'NanoCpus={{.HostConfig.NanoCpus}} Quota={{.HostConfig.CpuQuota}}' api
docker exec api cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/cpu.stat
docker exec api nproc
NanoCpus=1000000000 Quota=0 100000 100000 usage_usec 81234567 nr_periods 120344 nr_throttled 48211 ← 40% of periods throttled throttled_usec 2290144412 16
Fix
Raise --cpus to match real concurrency, or make the runtime quota-aware (Go 1.25+ sets GOMAXPROCS from the cgroup quota by default, older versions can use automaxprocs; the JVM is container-aware and accepts -XX:ActiveProcessorCount); for latency-sensitive services consider pinning cores with --cpuset-cpus or using only --cpu-shares (relative weight, no throttling).
Prevention and best practices
- Monitor the
nr_throttled/nr_periodsratio (cAdvisor metriccontainer_cpu_cfs_throttled_periods_total). - Watch throttling during load tests, not just average CPU.
#25 Log timestamps off by 8 hours / UnicodeEncodeError: 'ascii' codec can't encode characters (time zone and locale)
Symptom: Time inside the container shows UTC and scheduled jobs run at the wrong time; printing non-ASCII text (e.g. Chinese) raises encoding errors or outputs ?; sort order differs from the dev machine.
Root cause: Containers share the kernel clock with the host (the time itself is identical), but time zone and locale are user-space configuration: minimal images usually lack tzdata and locale data and default to UTC and the POSIX/C locale. The TZ environment variable only takes effect if the image has /usr/share/zoneinfo. You cannot (and should not) change the system time from inside a container.
Diagnostic commands
docker exec api sh -c 'date; echo TZ=$TZ; ls /usr/share/zoneinfo 2>/dev/null | head -2; locale 2>/dev/null | head -2' docker exec api python -c 'import sys,locale;print(sys.getfilesystemencoding(), locale.getpreferredencoding())'
Sat Nov 15 03:30:00 UTC 2026 TZ=Asia/Shanghai ← TZ is set but there is no zoneinfo, so it is still UTC LANG= ascii ANSI_X3.4-1968
Fix
RUN apt-get update && apt-get install -y --no-install-recommends tzdata && rm -rf /var/lib/apt/lists/* ENV TZ=Asia/Shanghai LANG=C.UTF-8 PYTHONIOENCODING=utf-8
Or mount it at runtime: -v /etc/localtime:/etc/localtime:ro (only if the host time zone is correct).
Prevention and best practices
- Store and log in UTC on the server side; convert time zones only in the presentation layer.
- Standardize on
LANG=C.UTF-8in images.
"My container died" troubleshooting decision tree
Start from the container status and work through exit codes and resource problems step by step.
Lab 2-A: OOMKilled (#17)
docker run --name lab8-oom --memory 64m --memory-swap 64m python:3.13-slim \
python -c "b=[]; [b.append(bytearray(10*1024*1024)) for _ in range(20)]"
docker inspect -f 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' lab8-oomexit=137 oom=true
--memory 512m and the exit code is 0.docker rm -f lab8-oomLab 2-B: The shell form makes stops slow (#19)
mkdir -p ~/lab8-sig && cd ~/lab8-sig
printf 'FROM python:3.13-slim\nCMD python -c "import time; time.sleep(3600)"\n' > Dockerfile.shell
printf 'FROM python:3.13-slim\nCMD ["python","-c","import signal,sys,time; signal.signal(signal.SIGTERM, lambda *a: sys.exit(0)); time.sleep(3600)"]\n' > Dockerfile.exec
docker build -q -f Dockerfile.shell -t lab8-shell . && docker build -q -f Dockerfile.exec -t lab8-exec .
docker run -d --name lab8-s lab8-shell; docker run -d --name lab8-e lab8-exec
docker exec lab8-s ps -o pid,args 2>/dev/null || docker top lab8-s
time docker stop lab8-s; time docker stop lab8-e
docker inspect -f '{{.Name}} {{.State.ExitCode}}' lab8-s lab8-ereal 0m10.3s real 0m0.4s /lab8-s 137 /lab8-e 0
Slim images may not have ps; use docker top instead. Note: some shells (such as newer dash) exec a single -c command directly, so PID 1 is python; but it has no SIGTERM handler, so as PID 1 the signal is still ignored and it still waits the full 10 seconds. lab8-e uses the exec form and registers a handler, so it exits immediately.
docker rm -f lab8-s lab8-e; docker rmi lab8-shell lab8-exec; rm -rf ~/lab8-sigLab 2-C: CRLF entrypoint script (#21)
mkdir -p ~/lab8-crlf && cd ~/lab8-crlf printf '#!/bin/sh\r\necho hello\r\n' > entrypoint.sh && chmod +x entrypoint.sh printf 'FROM alpine:3.22\nCOPY entrypoint.sh /\nENTRYPOINT ["/entrypoint.sh"]\n' > Dockerfile docker build -q -t lab8-crlf . && docker run --rm lab8-crlf; echo "exit=$?"
exec /entrypoint.sh: no such file or directory exit=255
This error is reported by runc inside the container; docker run may return 255 or 127 depending on the version.
sed -i 's/\r$//' entrypoint.sh && docker build -q -t lab8-crlf . && docker run --rm lab8-crlf prints hello.docker rmi lab8-crlf; rm -rf ~/lab8-crlfLab 2-D: Health check fails because curl is missing (#23)
docker run -d --name lab8-hc --health-cmd 'curl -fs http://127.0.0.1:8000/ || exit 1' \
--health-interval 3s --health-retries 2 python:3.13-slim python -m http.server 8000
sleep 12; docker ps --filter name=lab8-hc --format '{{.Status}}'
docker inspect -f '{{json .State.Health.Log}}' lab8-hc | jq '.[-1].Output'Up 12 seconds (unhealthy) "/bin/sh: 1: curl: not found\n"
docker rm -f lab8-hc
docker run -d --name lab8-hc --health-cmd "python -c \"import urllib.request;urllib.request.urlopen('http://127.0.0.1:8000/',timeout=2)\"" \
--health-interval 3s python:3.13-slim python -m http.server 8000
sleep 8; docker ps --filter name=lab8-hc --format '{{.Status}}' # (healthy)docker rm -f lab8-hcVideo tutorials (titles and channels verified via YouTube oEmbed)
No verified video dedicated to PID 1 signals, OOM and CPU throttling was found. Script:
- Draw Figure 2-1 and explain the 128+N rule case by case.
- Run Lab 2-A live and show
OOMKilled=trueand dmesg. - Run Lab 2-B, compare the 10-second and 0.4-second stops, and show PID 1 with
docker top. - Open
cpu.statand explain nr_throttled and the CFS period.
Official documentation
Module 3 · Part A: Networking, Ports & DNS (Problems 26–38)
- Draw the packet path of a published port: host NIC → nat-table DNAT → docker0/user-defined bridge → veth → the address the container listens on.
- Distinguish the DNS behavior of the default bridge and user-defined networks, and understand how the embedded DNS at 127.0.0.11 forwards queries.
- Handle "environmental" network problems: firewalls, subnet conflicts, MTU, proxies and IPv6.
Type a keyword (e.g. allocated, reset by peer, bad address, EAI_AGAIN) to filter; click a row to jump.
#26 curl: (56) Recv failure: Connection reset by peer (port published, app listens only on 127.0.0.1)
Symptom: After docker run -p 8080:5000 app, curl localhost:8080 returns a reset or (52) Empty reply from server, while docker exec app curl localhost:5000 works.
Root cause: Each container has its own network namespace, and 127.0.0.1 inside a container belongs only to that container. Port publishing DNATs traffic to the container's eth0 address (e.g. 172.18.0.2:5000). If the app binds only to 127.0.0.1 (the default for Flask app.run(), Vite/Next dev servers and Rails dev), nothing listens on eth0 and the connection is refused; through docker-proxy this shows up as a reset/empty reply.
Diagnostic commands
docker port app
PID=$(docker inspect -f '{{.State.Pid}}' app); sudo nsenter -t $PID -n ss -lntp # works even if the image has no ss
docker exec app sh -c 'cat /proc/net/tcp | head -3' # fallback: 0100007F = 127.0.0.1
5000/tcp -> 0.0.0.0:8080
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 127.0.0.1:5000 0.0.0.0:* users:(("python",pid=4012,fd=3))
Fix
Make the app listen on all addresses: flask run --host 0.0.0.0, gunicorn -b 0.0.0.0:5000, vite --host, uvicorn --host 0.0.0.0. To allow access only from the host itself, restrict it on the publish side: -p 127.0.0.1:8080:5000.
Prevention and best practices
- Make the listen address configurable (
HOST=0.0.0.0) and default to 0.0.0.0 in container images. - Put the external security boundary at the port-publishing and firewall layer, not at the app's listen address.
See Lesson 1 Module 5 (Networking), Lesson 3 target-port troubleshooting.
#27 Bind for 0.0.0.0:8080 failed: port is already allocated / Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use
Symptom: Full error: docker: Error response from daemon: driver failed programming external connectivity on endpoint web2 (…): Bind for 0.0.0.0:8080 failed: port is already allocated. (wording varies by version).
Root cause: Two sources: ① port is already allocated: Docker's own port allocator found another container (perhaps an old Compose container that is stopped but not removed, or another Compose project) already publishing the same host port; ② address already in use: a non-Docker process on the host (nginx, apache, another service) already listens on the port, so docker-proxy cannot bind.
Diagnostic commands
docker ps -a --filter publish=8080 --format '{{.Names}} {{.Status}} {{.Ports}}'
sudo ss -lntp 'sport = :8080'
docker compose ls
shop-web-1 Up 3 hours 0.0.0.0:8080->80/tcp
LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:* users:(("docker-proxy",pid=2231,fd=7))
NAME STATUS CONFIG FILES
shop running(2) /srv/shop/compose.yaml
Fix
Stop/remove the container or process holding the port; use a different host port (-p 8081:80); for local development let Docker pick one (-p 80 or -p 127.0.0.1::80, then look it up with docker port).
Prevention and best practices
- With several Compose projects on one host, let a reverse proxy (Traefik/nginx) own 80/443 and do not publish ports for backend services.
- Use
docker compose downrather than just stop, so leftover containers do not hold ports.
#28 Connecting to localhost:5432 inside a container → Connection refused (mistaking localhost for the host or another container)
Symptom: The app is configured with DATABASE_URL=postgres://localhost:5432; it works on the host, but inside a container it fails with psycopg.OperationalError: connection failed: … Connection refused.
Root cause: localhost inside a container is the container's own loopback interface. ① To reach another container: use the service/container name (on the same user-defined network, resolved by the embedded DNS); ② to reach a service on the host: Docker Desktop provides host.docker.internal; on Linux Engine you must map it manually to the special value host-gateway (the bridge gateway address), the host service must listen on that gateway address or 0.0.0.0, and the firewall must allow connections from the container subnet.
Diagnostic commands
docker exec app getent hosts db host.docker.internal
docker network inspect -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge
sudo ss -lntp 'sport = :5432' # does postgres on the host listen only on 127.0.0.1?
172.19.0.3 db (no output for host.docker.internal — it does not exist by default on Linux) 172.17.0.1 LISTEN 0 244 127.0.0.1:5432 0.0.0.0:*
Fix
# reach another container: same network + service name DATABASE_URL=postgres://db:5432/app # reach the host (Linux): docker run --add-host=host.docker.internal:host-gateway … # Compose: extra_hosts: ["host.docker.internal:host-gateway"] # and make the host service listen on 172.17.0.1 or 0.0.0.0 (mind the firewall)
Prevention and best practices
- Inject every dependency address through environment variables, and use service names in Compose.
- Containerize dependencies on the same network where possible, to reduce reliance on host services.
#29 ping: bad address 'db' / could not translate host name "db" (the default bridge network has no container-name DNS)
Symptom: Two containers started separately with docker run (no --network) cannot reach each other by name, but can by IP.
Root cause: The default bridge network is a legacy design: it does not provide automatic DNS by container name (only the deprecated --link writes /etc/hosts). User-defined bridge networks (including the project_default network Compose creates) use the embedded DNS server at 127.0.0.11, which resolves container names, service names and aliases.
Diagnostic commands
docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' api db
docker exec api cat /etc/resolv.conf
bridge bridge nameserver 10.0.0.2 ← the default bridge copies the host DNS; no 127.0.0.11
Fix
docker network create lab8-net docker network connect lab8-net api; docker network connect lab8-net db # can join while running docker exec api getent hosts db
Prevention and best practices
- Always use user-defined networks or Compose; split networks per application for isolation.
- Never hard-code container IPs in configuration; they change when containers are recreated.
#30 getaddrinfo EAI_AGAIN api.example.com / Temporary failure in name resolution (external DNS fails inside containers)
Symptom: Containers can resolve other container names, but resolving external domains fails intermittently or constantly, while it works on the host. More common after connecting to a VPN.
Root cause: On user-defined networks the container's /etc/resolv.conf points to 127.0.0.11; dockerd's embedded DNS answers container names itself and forwards other queries upstream. The upstreams come from the host's resolv.conf: when the host uses systemd-resolved (127.0.0.53), Docker reads the real upstreams from /run/systemd/resolve/resolv.conf. If a VPN client changed the host DNS after Docker read the old values at startup, or the upstream is only reachable via the host's loopback, forwarding fails. On the default bridge, if no usable server remains after loopback addresses are filtered out, Docker falls back to public DNS, which fails when the corporate network blocks it. The exact fallback behavior changes between versions; see the official docs.
Diagnostic commands
docker exec app cat /etc/resolv.conf docker run --rm --network lab8-net busybox nslookup api.example.com docker run --rm --network lab8-net busybox nslookup api.example.com 10.0.0.2 # ask the corporate DNS directly resolvectl status | grep -A2 'DNS Servers'; journalctl -u docker --since -10m | grep -i dns
nameserver 127.0.0.11 options ndots:0 ;; connection timed out; no servers could be reached Server: 10.0.0.2 Address: 10.0.0.2:53 Name: api.example.com Address: 10.20.1.15
Fix
Configure the upstreams explicitly in /etc/docker/daemon.json: {"dns": ["10.0.0.2","10.0.0.3"], "dns-search": ["corp.example.com"]} and restart Docker; for a single container use --dns. After the VPN changes DNS, restart Docker or recreate the networks.
Prevention and best practices
- Pin Docker's upstream DNS on servers instead of relying on dynamic host configuration.
- Configure sensible DNS caching and retries in the application; musl (alpine) and glibc resolve differently (e.g. search domains and TCP fallback), so consider base image differences when troubleshooting.
See Lesson 1 Module 5, Lesson 7 Capturing DNS with tcpdump; official Networking · DNS services.
#31 ufw shows 8080 as denied, yet the container port is reachable from the internet (Docker bypasses ufw)
Symptom: Ops enabled ufw allowing only 22/443, yet ports published with -p 8080:80, even a database published with -p 5432:5432, show up in internet scans.
Root cause: Published ports are DNATed via the iptables nat table PREROUTING → DOCKER chain; once the destination is rewritten to the container IP, packets traverse the FORWARD chain, not the INPUT chain managed by ufw, so ufw rules do not apply. The official docs explicitly describe this incompatibility between Docker and ufw.
Diagnostic commands
sudo iptables -t nat -L DOCKER -n --line-numbers
sudo iptables -L DOCKER-USER -n -v
docker ps --format '{{.Names}} {{.Ports}}' | grep 0.0.0.0
# from another machine: nc -zv <server public IP> 5432
1 DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:5432 to:172.17.0.3:5432 Chain DOCKER-USER (1 references) db 0.0.0.0:5432->5432/tcp
Fix
- For ports that only the host itself needs:
-p 127.0.0.1:5432:5432; do not publish database ports at all, keep them on an internal network. - When you need filtering, put the rules in the
DOCKER-USERchain (Docker never modifies it), e.g. allow only the internal network:iptables -I DOCKER-USER -i eth0 ! -s 10.0.0.0/8 -j DROP(note that after DNAT, matching the original destination port requires conntrack:-m conntrack --ctorigdstport). - In the cloud, also use security groups/NSGs as an outer line of defense.
Prevention and best practices
- Default to the
127.0.0.1:prefix in Compose templates and expose only the reverse proxy. - Scan your public IPs from outside regularly.
See the official Packet filtering and firewalls; Lesson 2 Hardening.
#32 After starting Docker / docker compose up, SSH drops or corporate 172.18.x.x services become unreachable (subnet conflict)
Symptom: After creating a new Compose project, the host can no longer reach some internal subnet, or an SSH session over the VPN suddenly drops.
Root cause: Docker's default bridge uses 172.17.0.0/16, and user-defined networks are allocated from the default address pools (carved out of 172.17–31.0.0/16 and 192.168.0.0/16). Each new network adds a directly connected route to the host routing table; if it overlaps a corporate/VPN subnet, traffic to those addresses is sent into the Docker bridge and the original route stops working.
Diagnostic commands
ip route | grep -E 'docker|br-'
docker network ls -q | xargs docker network inspect -f '{{.Name}} {{range .IPAM.Config}}{{.Subnet}}{{end}}'
ip route get 172.18.5.10
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 172.18.0.0/16 dev br-9a1c… proto kernel scope link src 172.18.0.1 shop_default 172.18.0.0/16 172.18.5.10 dev br-9a1c… src 172.18.0.1 ← should go through the VPN
Fix
{
"bip": "10.250.0.1/24",
"default-address-pools": [ { "base": "10.251.0.0/16", "size": 24 } ]
}
After restarting Docker, existing networks do not change automatically: you need docker compose down and then up (recreating the networks). You can also set ipam.config.subnet explicitly for networks in Compose.
Prevention and best practices
- Distribute the daemon.json address pools centrally during host provisioning (cloud-init/Ansible), and register the ranges with the network team.
See Lesson 7 Advanced networking; official dockerd reference.
#33 curl https://… inside a container hangs in the TLS handshake (no response after * TLSv1.3 (OUT), TLS handshake, Client hello) while small requests work — MTU
Symptom: The host is fine; inside containers HTTPS, git clone and apt-get hang and time out, while ping and small HTTP requests work. Common with VPNs, GRE/VXLAN tunnels, some cloud networks and nested virtualization.
Root cause: The Docker bridge defaults to MTU 1500; if the host's egress path MTU is smaller (e.g. 1400 on a VPN, 1450 on an overlay), large packets from the server (the ServerHello carrying the certificate chain) exceed the path MTU. Normally path MTU discovery relies on ICMP "Fragmentation Needed", but many networks drop ICMP, so large packets are silently discarded — which looks like "the handshake hangs".
Diagnostic commands
ip link show | grep -E 'mtu' | grep -E 'eth0|ens|tun|wg|docker0|br-' docker run --rm --network lab8-net busybox ping -c2 -M do -s 1472 1.1.1.1 2>&1 | tail -2 # if busybox lacks -M, use iputils from alpine docker run --rm --network lab8-net curlimages/curl -v --max-time 10 https://example.com 2>&1 | tail -3
2: ens4: mtu 1460 ... 5: docker0: mtu 1500 ... * TLSv1.3 (OUT), TLS handshake, Client hello (1): * Operation timed out after 10001 milliseconds with 0 bytes received
Fix
docker network create -o com.docker.network.driver.mtu=1400 lab8-net-mtu
# Compose: networks: { default: { driver_opts: { com.docker.network.driver.mtu: "1400" } } }
# default bridge: daemon.json { "mtu": 1400 }
You can also clamp the TCP MSS for forwarded traffic on the host (iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu).
Prevention and best practices
- In tunneled/cloud environments, set the Docker network MTU to "egress MTU − encapsulation overhead".
#34 docker pull: Error response from daemon: Get "https://registry-1.docker.io/v2/": dial tcp …:443: i/o timeout (proxy already set on the host)
Symptom: After export HTTPS_PROXY=… in the shell, curl can reach the internet but docker pull times out; or applications inside containers time out calling external APIs. The error may also be context deadline exceeded.
Root cause: Proxy configuration has three layers that do not inherit from each other: ① dockerd (pulling/pushing images) is a daemon started by systemd and does not read your shell environment; ② builds (see #6); ③ container runtime: processes see only the container's own environment variables. Also, if NO_PROXY omits internal registries or container service names, internal traffic is sent to the proxy too.
Diagnostic commands
docker info --format 'HTTP={{.HTTPProxy}} HTTPS={{.HTTPSProxy}} NO={{.NoProxy}}'
systemctl show docker --property=Environment
docker run --rm alpine env | grep -i proxy
HTTP= HTTPS= NO= Environment=
Fix
{
"proxies": {
"http-proxy": "http://proxy.corp:3128",
"https-proxy": "http://proxy.corp:3128",
"no-proxy": "localhost,127.0.0.1,.corp.example.com,registry.corp"
}
}
{ "proxies": { "default": { "httpProxy": "http://proxy.corp:3128", "httpsProxy": "http://proxy.corp:3128", "noProxy": "localhost,127.0.0.1,db,redis" } } }
After editing daemon.json, run sudo systemctl restart docker; alternatively set Environment= in a systemd drop-in /etc/systemd/system/docker.service.d/http-proxy.conf (do not configure both).
Prevention and best practices
- Put internal registries, service names and the metadata address (169.254.169.254) in NO_PROXY.
- Prefer an internal registry on production servers instead of pulling public images through a proxy.
Official Daemon proxy configuration, CLI proxy; see also Lesson 1 Module 0.
#35 After a firewall script / config management run, all published ports and container egress break at once (iptables rules flushed)
Symptom: After running iptables -F, iptables-restore < rules.v4, an Ansible firewall role or a hardening script, containers cannot reach the internet and published ports are unreachable; restarting Docker fixes it.
Root cause: When starting or creating networks, Docker writes chains such as DOCKER, DOCKER-FORWARD (newer versions) and DOCKER-USER into iptables, plus MASQUERADE (SNAT) and DNAT rules in the nat table. When an external tool overwrites the whole table these rules disappear, and dockerd does not notice. Ubuntu 24.04 uses the iptables-nft backend; mixing iptables-legacy and nft tools also produces "the rules look present but do nothing". Engine 29 offers an experimental nftables backend ("firewall-backend": "nftables"; see the official docs).
Diagnostic commands
sudo iptables -t nat -S | grep -cE 'DOCKER|MASQUERADE' sudo iptables -S FORWARD | head update-alternatives --display iptables | head -3 cat /proc/sys/net/ipv4/ip_forward
0 ← all Docker rules are gone -P FORWARD DROP link currently points to /usr/sbin/iptables-nft 1
Fix
sudo systemctl restart docker rebuilds the rules (containers keep running if live-restore is enabled). Long term: let firewall tools manage only the DOCKER-USER and INPUT chains instead of overwriting whole tables; with firewalld, use the docker zone Docker creates automatically.
Prevention and best practices
- Mark Docker hosts as a special role in configuration management, with firewall templates that explicitly preserve Docker's chains.
- Do not set
"iptables": falseunless you manage container NAT and forwarding entirely yourself.
Official Packet filtering and firewalls; see also Lesson 7 SNAT.
#36 connect ECONNREFUSED ::1:3000 (localhost resolves to IPv6) / containers cannot reach IPv6-only services
Symptom A: A health check or sidecar using localhost:3000 fails with ECONNREFUSED ::1:3000, although the app is clearly listening. Symptom B: Containers get Network is unreachable when calling a service that has only AAAA records.
Root cause: A: in the container's /etc/hosts, localhost maps to both 127.0.0.1 and ::1; runtimes such as Node 17+ no longer force IPv4 first and may try ::1, while the app listens only on IPv4 0.0.0.0. B: Docker networks assign only IPv4 by default; IPv6 must be enabled explicitly per network (--ipv6), and the default bridge needs daemon.json configuration.
Diagnostic commands
docker exec app getent ahosts localhost
docker exec app sh -c 'cat /proc/net/tcp6 | wc -l; cat /proc/net/tcp | grep -c ":0BB8"' # 0BB8 = 3000
docker network inspect -f 'IPv6={{.EnableIPv6}} {{json .IPAM.Config}}' lab8-net
::1 STREAM localhost
127.0.0.1 STREAM localhost
IPv6=false [{"Subnet":"172.20.0.0/16","Gateway":"172.20.0.1"}]
Fix
A: use 127.0.0.1 instead of localhost in checks, or make the app listen on :: (dual stack). B: docker network create --ipv6 lab8-v6 (optionally with --subnet fd00:dead:beef::/64), or enable_ipv6: true in Compose; the host needs an IPv6 egress route.
Prevention and best practices
- Use explicit IPs or service names consistently for health checks and internal calls.
- When publishing ports over IPv6, check the firewall too (ip6tables rules).
Official Use IPv6 networking.
#37 network shared declared as external, but could not be found / services in two Compose projects cannot resolve each other
Symptom: The frontend and backend projects are started with separate Compose files and the frontend cannot resolve api; or docker compose up reports that the external network cannot be found; or after renaming the directory "the data is gone and the network changed".
Root cause: Compose prefixes resources with the project name (the directory name by default; set it with -p/name:/COMPOSE_PROJECT_NAME): network project_default, volume project_data, container project-service-1. Different projects live on different networks by default and are isolated from each other. external: true means "created by someone else; Compose will not create it", so it must already exist with exactly that name (no prefix).
Diagnostic commands
docker compose ls
docker network ls --format '{{.Name}}' | grep -E 'default|shared'
docker compose config | sed -n '/^networks:/,$p'
frontend running(1) ~/frontend/compose.yaml
backend running(2) ~/backend/compose.yaml
backend_default
frontend_default
networks:
shared:
name: shared
external: true
Fix
docker network create shared # create the external network first
# declare it in both projects' compose.yaml:
# networks: { shared: { external: true } }
# and attach the services that need to talk to the shared network; pin the project name with a top-level name: backend
Prevention and best practices
- Pin the project name with a top-level
name:in compose.yaml so volumes do not "vanish" after a directory rename (they just got a different prefix). - Keep cross-project communication to a minimum; multiple projects commonly share one reverse-proxy network.
#38 --network host: service unreachable on Mac/Windows / WARNING: Published ports are discarded when using host network mode
Symptom: The same docker run --network host command is reachable at localhost:8080 on a Linux server but not on Docker Desktop; or on Linux, adding -p as well produces a warning that the ports are discarded.
Root cause: Host mode makes the container share the network namespace of the machine running dockerd. On Linux Engine that is the host; on Docker Desktop, dockerd runs inside a Linux VM, so "host" means the VM's network. Since Desktop 4.34 there is an optional host networking feature (it must be enabled in settings; see the official docs for limitations). Host mode has no NAT, so -p is meaningless and ignored.
Diagnostic commands
docker info --format '{{.OperatingSystem}} {{.KernelVersion}}'
docker inspect -f '{{.HostConfig.NetworkMode}}' app
docker exec app ss -lnt 2>/dev/null | head
Docker Desktop 6.10.x-linuxkit host
Fix
Use bridge + -p for cross-platform dev environments; use host mode only on Linux hosts when you really need it (high performance, many ports, multicast); to try it on Desktop, enable host networking under Settings → Resources → Network.
Prevention and best practices
- Host mode gives up network isolation: port conflicts and exposure apply directly to the host, so use it cautiously in production.
Official Host network driver; see also Lesson 1 Module 5.
"Port unreachable / cannot connect" troubleshooting decision tree
Lab 3-A: Listening only on 127.0.0.1 (#26)
docker run -d --name lab8-lo -p 8080:8000 python:3.13-slim python -m http.server 8000 --bind 127.0.0.1 sleep 2; curl -sS localhost:8080 | head -1
curl: (56) Recv failure: Connection reset by peer
sudo nsenter -t $(docker inspect -f '{{.State.Pid}}' lab8-lo) -n ss -lntLISTEN 0 5 127.0.0.1:8000 0.0.0.0:*
docker rm -f lab8-lo docker run -d --name lab8-lo -p 127.0.0.1:8080:8000 python:3.13-slim python -m http.server 8000 --bind 0.0.0.0 sleep 2; curl -sI localhost:8080 | head -1 # HTTP/1.0 200 OK
docker rm -f lab8-loLab 3-B: The default bridge has no name resolution (#29)
docker run -d --name lab8-db redis:7-alpine docker run --rm busybox ping -c1 lab8-db
ping: bad address 'lab8-db'
docker network create lab8-net docker network connect lab8-net lab8-db docker run --rm --network lab8-net busybox sh -c 'cat /etc/resolv.conf | head -1; ping -c1 lab8-db | head -2'
nameserver 127.0.0.11 PING lab8-db (172.20.0.2): 56 data bytes 64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.08 ms
docker rm -f lab8-db; docker network rm lab8-netLab 3-C: The two kinds of port-conflict errors (#27)
docker run -d --name lab8-p1 -p 8090:80 nginx:alpine docker run -d --name lab8-p2 -p 8090:80 nginx:alpine # conflict inside Docker python3 -m http.server 8091 & sleep 1 docker run -d --name lab8-p3 -p 8091:80 nginx:alpine # conflict with a host process
... Bind for 0.0.0.0:8090 failed: port is already allocated ... Error starting userland proxy: listen tcp4 0.0.0.0:8091: bind: address already in use
The failed containers were still created (Created state) and must be removed. Wording may vary by version.
kill %1; docker rm -f lab8-p1 lab8-p2 lab8-p3Lab 3-D: Inspect the iptables rules Docker writes (#31 / #35)
docker run -d --name lab8-fw -p 8095:80 nginx:alpine sudo iptables -t nat -S DOCKER | grep 8095 sudo iptables -S DOCKER-USER sudo ufw status 2>/dev/null | head -3
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 8095 -j DNAT --to-destination 172.17.0.2:80 -N DOCKER-USER
Think about it: even if ufw denies 8095, DNAT happens in PREROUTING and the packet then traverses FORWARD, so ufw's INPUT rules never match. The exact rule layout changes between versions (Engine 28+ added chains such as DOCKER-FORWARD).
docker rm -f lab8-fwVideo tutorials (titles and channels verified via YouTube oEmbed)
No verified video covering ufw bypass or MTU problems was found. You can record an explanation following Figure 3-1: capture packets first (Lesson 7 tcpdump), then demonstrate each checkpoint.
Official documentation
Module 4 · Part A: Storage, Logs, Daemon & Registry (Problems 39–50)
- Distinguish the lifecycle and permission model of the container writable layer, named volumes, bind mounts and tmpfs.
- Build a "where did the disk go" checklist: logs → images → build cache → volumes → container writable layers.
- Understand the CLI → socket → dockerd → containerd connection chain, plus registry authentication and the TLS trust chain.
Type a keyword (e.g. daemon, x509, denied, manifest, Read-only) to filter; click a row to jump.
#39 All database data is gone after docker rm / compose down
Symptom: While upgrading the image you ran docker rm -f db && docker run … postgres:17, or docker compose down -v, and afterwards the database is empty.
Root cause: Data a container writes to unmounted paths lives in the container's writable layer and is deleted with the container. The official postgres/mysql images declare a VOLUME in their Dockerfile, so without a specified volume an anonymous volume (a long hash name) is created, and a new container does not reuse it automatically; docker rm -v or --rm deletes anonymous volumes; compose down -v deletes the named volumes declared by the project.
Diagnostic commands
docker inspect -f '{{range .Mounts}}{{.Type}} {{.Name}} -> {{.Destination}}{{"\n"}}{{end}}' db
docker volume ls --filter dangling=true
docker image inspect -f '{{json .Config.Volumes}}' postgres:17
volume 3c9f0e1a…(64-char hash) -> /var/lib/postgresql/data ← anonymous volume
DRIVER VOLUME NAME
local 3c9f0e1a… ← the old data may still be here!
{"/var/lib/postgresql/data":{}}
The mount path may change between major image versions (see the image documentation).
Fix
Do not prune yet! A dangling anonymous volume may still hold the data: confirm with docker run --rm -v 3c9f…:/data alpine ls /data, then mount it into the new container. From now on use named volumes: -v pgdata:/var/lib/postgresql/data; in Compose, declare them under the top-level volumes:.
Prevention and best practices
- Always use named volumes + regular backups for stateful data (
docker run --rm -v pgdata:/data:ro -v $PWD:/b alpine tar czf /b/pg.tgz -C /data .; for databases prefer logical backups such as pg_dump). - Be careful with
down -vandvolume prunein production; prefer managed services for production databases.
#40 Error: Cannot find module 'express' (a dev bind mount hides the image's node_modules)
Symptom: The image runs fine on its own; after adding volumes: ["./:/app"] to the Compose dev config, dependencies cannot be found, or Python packages and build artifacts "disappear".
Root cause: A mount covers whatever was at the target path in the container (consistent with Linux mount semantics): the host directory has no node_modules (or one built for the host platform and incompatible), so the /app/node_modules built into the image is hidden. Note the difference: when an empty named volume is mounted for the first time, Docker copies the image's content at that path into the volume; a bind mount never copies.
Diagnostic commands
docker compose exec web ls /app/node_modules | head -3
docker inspect -f '{{range .Mounts}}{{.Type}} {{.Source}} -> {{.Destination}}{{"\n"}}{{end}}' $(docker compose ps -q web)
docker run --rm --entrypoint ls myapp:dev /app/node_modules | head -3 # without the mount, the image does have it
ls: /app/node_modules: No such file or directory bind /home/dev/proj -> /app express ...
Fix
services:
web:
volumes:
- ./:/app
- /app/node_modules # anonymous volume "punches a hole", keeping the image's dependencies
# better: Compose watch syncs only the source code
develop:
watch:
- { action: sync, path: ./src, target: /app/src }
- { action: rebuild, path: package.json }
Prevention and best practices
- Do not bind-mount code in production; for development prefer
docker compose watch. - On Docker Desktop, bind mounts with many small files are slow and syncing is faster (see the Synchronized file shares feature in the official docs).
#41 chown: changing ownership of '/var/lib/postgresql/data': Operation not permitted / mkdir: cannot create directory '/data/x': Permission denied (volume UID mismatch)
Symptom: After bind-mounting a host directory ./data:/data, containers running as non-root (postgres UID 999, node UID 1000, a custom 10001) cannot write to it; or files written by the container belong to a strange UID on the host and developers cannot delete them.
Root cause: Bind mounts do no UID translation at all: the kernel checks permissions by numeric UID/GID, and 999 in the container is 999 on the host. A host directory created automatically by Docker belongs to root. NFS root_squash and SELinux labels (on Fedora/RHEL you get Permission denied even though ls shows correct permissions) produce the same symptom. With rootless Docker and userns-remap, container UIDs map into a subordinate UID range on the host (e.g. 100999), which makes mismatches even more likely.
Diagnostic commands
docker exec db id
ls -ln ./data | head -3; stat -c '%u:%g %a %n' ./data
getenforce 2>/dev/null; ls -Z ./data 2>/dev/null | head -2
docker info --format '{{.SecurityOptions}}'
uid=999(postgres) gid=999(postgres) groups=999(postgres) 0:0 755 ./data Enforcing [name=seccomp,profile=builtin name=selinux name=cgroupns]
Fix
- Grant permissions on the host in advance:
sudo chown -R 999:999 ./data, or run the container as the host user with--user "$(id -u):$(id -g)"(dev scenarios). - Prefer named volumes: on first mount they copy the content and ownership of the image's directory, so permissions are usually right out of the box.
- SELinux: add
:Z(private) or:z(shared) to the mount to relabel it (never on system directories such as /home or /usr).
Prevention and best practices
- Document the runtime UID and the writable paths in the image docs; in Compose, use an init container or an entrypoint that does a one-off chown on the volume directory (then drops privileges).
#42 Disk at 100%: /var/lib/docker/containers/<id>/<id>-json.log is 40GB (logs fill the disk)
Symptom: The host alerts that the disk is full, all containers fail to write and dockerd misbehaves; du reveals one container's JSON log is huge.
Root cause: The default log driver json-file does not rotate by default (no size limit); every line of stdout/stderr is appended. Debug-level logging or an error in a tight loop can fill a disk within hours. Changing logging in daemon.json applies only to newly created containers; existing containers must be recreated.
Diagnostic commands
sudo du -sh /var/lib/docker/containers/*/*-json.log 2>/dev/null | sort -h | tail -3
docker inspect -f '{{.Name}} {{.HostConfig.LogConfig.Type}} {{json .HostConfig.LogConfig.Config}}' $(docker ps -q)
docker info --format '{{.LoggingDriver}}'
docker system df -v | head -20
41G /var/lib/docker/containers/9b1e…/9b1e…-json.log
/api json-file {}
json-file
Fix
# Emergency: truncate (do not rm — dockerd still holds the file handle, so deleting does not free the space)
sudo truncate -s 0 /var/lib/docker/containers/9b1e…/9b1e…-json.log
# Long term: /etc/docker/daemon.json, restart docker, then recreate the containers
# { "log-driver": "local", "log-opts": { "max-size": "10m", "max-file": "5" } }
# or keep json-file and add max-size/max-file
# Per Compose service: logging: { driver: json-file, options: { max-size: "10m", max-file: "3" } }
Prevention and best practices
- Configure rotation when provisioning hosts (the
localdriver rotates by default and uses less space); centralize logs with collectors such as Fluent Bit/Vector. - Overall disk triage order:
docker system df→ logs → images → build cache (#9) → volumes → container writable layers (docker ps -s).
Official Configure logging drivers; see also Lesson 3 Cloud troubleshooting (Log Analytics), Lesson 4 CloudWatch.
#43 OSError: [Errno 30] Read-only file system: '/tmp/x' / nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system)
Symptom: After enabling --read-only for hardening (Compose read_only: true), the app fails to start, or fails to write temporary files while running.
Root cause: --read-only mounts the container's root filesystem read-only, so any path not mounted separately is unwritable. Many programs write to /tmp, /var/run, /var/cache or ~/.cache by default, or generate config files at startup.
Diagnostic commands
docker inspect -f 'ro={{.HostConfig.ReadonlyRootfs}} tmpfs={{json .HostConfig.Tmpfs}}' web
docker logs web 2>&1 | grep -i 'read-only' | head
docker diff web_test_without_ro | head # run a copy without --read-only and see which paths the program writes
ro=true tmpfs=null nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system) C /var/cache/nginx A /var/cache/nginx/client_temp C /var/run A /var/run/nginx.pid
Fix
docker run -d --read-only \ --tmpfs /var/cache/nginx:rw,size=64m --tmpfs /var/run:rw,size=1m --tmpfs /tmp:rw,size=64m \ nginx:alpine # use volumes for paths that must persist; or pick an official nginx-unprivileged-style image
Prevention and best practices
- Find the write paths with
docker diff, then mount tmpfs or volumes on each one. - Use it together with non-root,
--cap-drop ALLandno-new-privilegesas a security baseline (see interview question Q39).
See Lesson 2 Hardening.
#44 Job for docker.service failed … unable to configure the Docker daemon with file /etc/docker/daemon.json: invalid character '}' looking for beginning of object key string
Symptom: After editing daemon.json (adding a registry mirror, log rotation, address pools), systemctl restart docker fails and no container can start. Another common error: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [fd://], from file: [tcp://0.0.0.0:2375]).
Root cause: dockerd parses the JSON strictly at startup: trailing commas, comments and typographic (curly) quotes all fail, and unknown fields cause a failure too. The same option cannot be set both as a command-line flag (-H fd:// in the systemd unit) and in daemon.json.
Diagnostic commands
sudo dockerd --validate --config-file=/etc/docker/daemon.json sudo journalctl -u docker -n 30 --no-pager jq . /etc/docker/daemon.json systemctl cat docker | grep ExecStart
unable to configure the Docker daemon with file /etc/docker/daemon.json: invalid character '}' looking for beginning of object key string ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
Fix
Fix the JSON (validate with jq), then restart once dockerd --validate passes. If you need to listen on TCP, override ExecStart with a systemd drop-in (first an empty ExecStart=, then the new one) instead of setting hosts in two places. If systemd rate-limits the repeatedly failing service, run systemctl reset-failed docker first.
Prevention and best practices
- Distribute daemon.json through configuration management and run
dockerd --validatebefore every change. - Enable
"live-restore": trueso containers keep running while dockerd restarts/upgrades (not supported in Swarm mode). - Never expose
tcp://0.0.0.0:2375without TLS (that is remote root).
Official Troubleshooting the Docker daemon; see also Lesson 1 Module 1 (Architecture).
#45 Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
Symptom: Every docker command prints this line.
Root cause: The CLI is just a REST client that must reach dockerd's API endpoint. Four kinds of causes: ① dockerd is not running (failed to start, see #44, or was stopped); ② the CLI points to the wrong place: the DOCKER_HOST environment variable or docker context points elsewhere (rootless $XDG_RUNTIME_DIR/docker.sock, a remote host, Desktop's socket); ③ the socket file was deleted by mistake; ④ with WSL/Desktop, Desktop is not running or WSL integration is not enabled.
Diagnostic commands
systemctl is-active docker docker.socket containerd docker context ls; echo "DOCKER_HOST=$DOCKER_HOST" ls -l /var/run/docker.sock sudo journalctl -u docker -n 20 --no-pager
failed inactive active NAME DESCRIPTION DOCKER ENDPOINT default * Current DOCKER_HOST based configuration unix:///var/run/docker.sock DOCKER_HOST= ls: cannot access '/var/run/docker.sock': No such file or directory
Fix
sudo systemctl start docker (read the logs to find why it failed); fix the endpoint with docker context use default or unset DOCKER_HOST; in rootless mode check systemctl --user status docker and set DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock; Desktop users should start Desktop and enable the distro under Settings → Resources → WSL integration.
Prevention and best practices
systemctl enable docker containerd; monitor the dockerd process and the/_pingendpoint.
#46 permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: … connect: permission denied
Symptom: Regular users fail to run docker commands but succeed with sudo; CI runners or Jenkins containers with docker.sock mounted still get the error.
Root cause: /var/run/docker.sock is owned by root:docker with mode 660. The user is not in the docker group, or was just added but the current session has not refreshed its group membership; when the socket is mounted into a container, the GID of the user inside the container does not match the host's docker group GID.
Diagnostic commands
ls -ln /var/run/docker.sock id; getent group docker docker run --rm -v /var/run/docker.sock:/var/run/docker.sock --entrypoint id docker:cli
srw-rw---- 1 0 988 0 Nov 15 03:00 /var/run/docker.sock uid=1000(dev) gid=1000(dev) groups=1000(dev),27(sudo) docker:x:988:
Fix
sudo usermod -aG docker $USER, then log in again (or newgrp docker); in containers use --group-add 988 (the GID of the host's docker group). Do not chmod 666 docker.sock.
Prevention and best practices
- Members of the docker group are effectively root (they can
docker run -v /:/host). When you need isolation, use rootless Docker, or builds in CI that do not need the socket (rootless BuildKit, Kaniko-style tools, remote builders). - Audit containers that mount docker.sock (Portainer, Traefik, CI agents) as highly privileged components.
Official Linux post-installation steps, Rootless mode.
#47 denied: requested access to the resource is denied / unauthorized: authentication required (push fails)
Symptom: docker push myapp:1.0 or docker push myorg/myapp:1.0 is rejected; in CI it pushed fine yesterday and today it is unauthorized.
Root cause: ① The image name has no registry host, so myapp:1.0 is interpreted as docker.io/library/myapp (the official-image namespace, which you cannot push to); ② the namespace/repository does not exist or the account lacks write permission (Docker Hub organization team permissions, ACR AcrPush, ECR policies); ③ expired credentials: an ACR az acr login token lasts about 3 hours, an ECR get-login-password token 12 hours; ④ the credential helper (credsStore) fails: error getting credentials - err: exit status 1.
Diagnostic commands
docker image ls --format '{{.Repository}}:{{.Tag}}' | grep myapp
cat ~/.docker/config.json | jq '{auths: (.auths|keys), credsStore, credHelpers}'
docker login myacr.azurecr.io # or az acr login -n myacr / aws ecr get-login-password | docker login ...
myapp:1.0
{ "auths": ["https://index.docker.io/v1/"], "credsStore": "desktop", "credHelpers": null }
Fix
docker tag myapp:1.0 myacr.azurecr.io/team/myapp:1.0 az acr login -n myacr && docker push myacr.azurecr.io/team/myapp:1.0 # in CI, get short-lived credentials on demand via OIDC federation instead of long-lived passwords
Prevention and best practices
- Always write full image references:
registry/namespace/repo:tag. - Use OIDC in CI (GitHub Actions → Azure/AWS) with least privilege (push only to your own repositories).
See Lesson 1 Module 8 (Registry/ACR), Lesson 4 ECR, Lesson 5 OIDC.
#48 manifest for myapp:1.4 not found: manifest unknown: manifest unknown / no matching manifest for linux/arm64/v8 in the manifest list entries
Symptom: Pulling fails during deployment. The full error looks like Error response from daemon: manifest for myacr.azurecr.io/myapp:1.4 not found: manifest unknown: manifest unknown.
Root cause: manifest unknown: the tag does not exist in the repository — a typo, a failed CI push, deleted by a retention policy (acr purge, ECR lifecycle), or pushed to a different repository. no matching manifest: the tag exists, but it is a manifest list/OCI index without an entry for the current platform (e.g. only amd64 was built, but it is pulled on Graviton/Apple Silicon).
Diagnostic commands
docker buildx imagetools inspect myacr.azurecr.io/myapp:1.4 az acr repository show-tags -n myacr --repository myapp --orderby time_desc --top 5 -o tsv docker manifest inspect myacr.azurecr.io/myapp:1.4 | jq '.manifests[].platform' 2>/dev/null
ERROR: myacr.azurecr.io/myapp:1.4: not found
1.3
1.2
{ "architecture": "amd64", "os": "linux" }
Fix
Confirm the CI push succeeded and the tag is correct; restore the deleted version (rebuild or copy from a backup registry); if you need multiple platforms, build a multi-arch image with buildx (see #5); as a stopgap, run under emulation with --platform linux/amd64 (slow).
Prevention and best practices
- Lock release tags and exclude them from retention policies; deploy by digest.
- After pushing, have CI run
imagetools inspectto assert the tag and platforms exist.
#49 tls: failed to verify certificate: x509: certificate signed by unknown authority / http: server gave HTTP response to HTTPS client (private registry)
Symptom: Pulling from or pushing to the company Harbor or a self-hosted registry:2 fails. Older versions may word it as x509: certificate signed by unknown authority without the tls: failed to verify certificate: prefix.
Root cause: It is dockerd (not the CLI) that talks to the registry; by default it requires HTTPS and verifies the server using the system CAs plus the certificates in /etc/docker/certs.d/<host:port>/. Verification fails when the registry uses an internal corporate CA or a self-signed certificate; the second error appears when the registry serves only HTTP. Note that registries on localhost/127.0.0.0/8 are treated as insecure-allowed by default.
Diagnostic commands
openssl s_client -connect registry.corp:5000 -servername registry.corp </dev/null 2>/dev/null | openssl x509 -noout -issuer -subject -enddate
curl -v https://registry.corp:5000/v2/ 2>&1 | grep -iE 'SSL|issuer|HTTP/'
ls /etc/docker/certs.d/ 2>/dev/null; docker info --format '{{json .RegistryConfig.InsecureRegistryCIDRs}}'
issuer=CN = Corp Internal Root CA subject=CN = registry.corp notAfter=Mar 1 00:00:00 2027 GMT * SSL certificate problem: unable to get local issuer certificate
Fix
sudo mkdir -p /etc/docker/certs.d/registry.corp:5000
sudo cp corp-root-ca.crt /etc/docker/certs.d/registry.corp:5000/ca.crt # no dockerd restart needed
docker pull registry.corp:5000/team/app:1.0
# HTTP registries for lab environments only: daemon.json { "insecure-registries": ["registry.lab:5000"] }, then restart
Prevention and best practices
- Use valid TLS certificates on production registries and monitor their expiry; distribute the corporate CA to all Docker hosts and CI runners via configuration management.
- Never use insecure-registries in production.
Official Verify repository client with certificates, insecure-registries.
#50 After upgrading / switching to the containerd image store, all images in docker images are "gone"
Symptom: After enabling the containerd image store in daemon.json ("features": {"containerd-snapshotter": true}) or ticking "Use containerd for pulling and storing images" in Desktop, docker images is empty and old containers will not start; switching back makes the images "come back". Disk usage may also double.
Root cause: Docker has two image stores: the classic graphdriver (overlay2, data in /var/lib/docker/overlay2) and the containerd image store (snapshotters, data managed by containerd). They cannot see each other and nothing is migrated automatically. Since Docker Engine 29, new installs use the containerd image store by default, while hosts upgraded from older versions keep their existing store (see the official docs). The containerd store can natively keep multi-platform images and attestations, which is one source of the size difference.
Diagnostic commands
docker info --format 'Driver={{.Driver}} {{json .DriverStatus}}'
cat /etc/docker/daemon.json
sudo du -sh /var/lib/docker/overlay2 /var/lib/containerd 2>/dev/null
Driver=overlayfs [["driver-type","io.containerd.snapshotter.v1"]]
{ "features": { "containerd-snapshotter": true } }
14G /var/lib/docker/overlay2 ← the old images are still here, just invisible to the current store
2.1G /var/lib/containerd
Fix
If you need the old images: temporarily switch back to the old store, export the images you want to keep with docker save, switch over and docker load them; or simply pull them again from the registry. Clean up the old store only after confirming it is no longer needed (stop Docker and back up first). Volumes are not affected by switching image stores, but containers must be recreated.
Prevention and best practices
- Treat switching image stores as a planned change: first inventory images that exist only locally (never pushed to a registry).
- Production hosts should never depend on images that "exist only locally"; the registry is the source of truth.
Official containerd image store with Docker Engine; see also Lesson 1 Module 3 (Image storage).
Daemon / registry / disk troubleshooting decision tree
Lab 4-A: Anonymous volumes and "data loss" (#39)
docker run -d --name lab8-pg -e POSTGRES_PASSWORD=lab postgres:17-alpine
sleep 8; docker exec lab8-pg psql -U postgres -c 'create table t(x int); insert into t values (42);'
docker inspect -f '{{range .Mounts}}{{.Type}} {{.Name}}{{end}}' lab8-pg
docker rm -f lab8-pg
docker run -d --name lab8-pg -e POSTGRES_PASSWORD=lab postgres:17-alpine; sleep 8
docker exec lab8-pg psql -U postgres -c 'select * from t;'volume 5e0c… (anonymous volume) ERROR: relation "t" does not exist
docker volume ls --filter dangling=true -q | head -3Repeat the lab with a named volume
-v lab8-pgdata:/var/lib/postgresql/data; the data survives removing and recreating the container. (The data path may change in newer major postgres images; see the image documentation.)docker rm -f lab8-pg; docker volume rm lab8-pgdata; after checking the dangling anonymous volumes, docker volume prune (lab VM only).Lab 4-B: Log rotation (#42)
docker run -d --name lab8-log alpine sh -c 'while true; do head -c 2000 /dev/urandom | base64; done'
sleep 10; sudo du -sh $(docker inspect -f '{{.LogPath}}' lab8-log)
docker rm -f lab8-log
docker run -d --name lab8-log --log-opt max-size=5m --log-opt max-file=2 alpine sh -c 'while true; do head -c 2000 /dev/urandom | base64; done'
sleep 20; sudo ls -lh $(dirname $(docker inspect -f '{{.LogPath}}' lab8-log)) | grep json212M /var/lib/docker/containers/…-json.log -rw-r----- 1 root root 4.2M … -json.log -rw-r----- 1 root root 4.8M … -json.log.1
docker rm -f lab8-logLab 4-C: daemon.json syntax error (#44)
sudo cp /etc/docker/daemon.json /tmp/daemon.json.bak 2>/dev/null || echo '{}' | sudo tee /tmp/daemon.json.bak
echo '{ "log-driver": "local", }' | sudo tee /etc/docker/daemon.json
sudo dockerd --validate --config-file=/etc/docker/daemon.json
sudo systemctl restart docker; systemctl is-active docker
sudo journalctl -u docker -n 5 --no-pager | grep -i daemon.jsonunable to configure the Docker daemon with file /etc/docker/daemon.json: invalid character '}' looking for beginning of object key string failed
sudo cp /tmp/daemon.json.bak /etc/docker/daemon.json sudo dockerd --validate --config-file=/etc/docker/daemon.json && sudo systemctl reset-failed docker; sudo systemctl restart docker systemctl is-active docker # active
Lab 4-D: A bind mount hides a directory (#40)
mkdir -p ~/lab8-mask && cd ~/lab8-mask printf 'FROM alpine:3.22\nRUN mkdir -p /app/deps && echo installed > /app/deps/lib.txt\nCMD ["cat","/app/deps/lib.txt"]\n' > Dockerfile docker build -q -t lab8-mask . docker run --rm lab8-mask # installed docker run --rm -v "$PWD":/app lab8-mask # hidden docker run --rm -v "$PWD":/app -v /app/deps lab8-mask # anonymous-volume hole, restored
installed cat: can't open '/app/deps/lib.txt': No such file or directory installed
docker rmi lab8-mask; rm -rf ~/lab8-mask; docker volume prune -f (lab VM only)Video tutorials (titles and channels verified via YouTube oEmbed)
No verified video covering daemon.json troubleshooting, private registry certificates or containerd image store migration was found. Script:
- Figure 4-2: the lifecycles of the four mount types, with a live demo of the anonymous volume from Lab 4-A.
- Top half of Figure 4-1: the five hops from CLI to registry, with one diagnostic command per hop.
- Demonstrate
dockerd --validatecatching a daemon.json error.
Official documentation
Module 5 · Part B: Fundamentals & Architecture (Questions 1–13)
- Explain "what a container is" in terms of kernel mechanisms (namespaces, cgroups, union filesystems).
- Explain the division of labor in docker CLI → dockerd → containerd → shim → runc, and the role of the OCI specifications.
- Answer frequent follow-ups such as Desktop vs Engine, rootless, restart policies and PID 1.
Skim the questions and flag the ones you are unsure about; click a row for the full answer.
Q1. What is the difference between a container and a virtual machine?Junior
30-second answer
A virtual machine virtualizes hardware through a hypervisor, and each VM runs a full guest kernel; a container is an isolated ordinary process on the host that shares the host kernel, with namespaces isolating its view and cgroups limiting its resources. So containers start in milliseconds to seconds with low overhead and high density, but their isolation is weaker than a VM's.
In-depth answer
| Virtual machine | Container | |
|---|---|---|
| Isolation boundary | Hardware virtualization (VT-x/AMD-V), separate kernel | Kernel namespaces + cgroups + seccomp/LSM |
| Startup | Boots an OS, seconds to minutes | fork/exec of one process |
| Image | Whole-disk image, GBs | Layered filesystem, MBs, layers can be shared |
| Kernel | Can run a different OS | Must be compatible with the host kernel (Linux containers need a Linux kernel) |
You can see a container's processes directly in ps aux on the host — the best proof that "a container is a process".
Common follow-up questions
- How do Linux containers run on Mac/Windows? Docker Desktop runs dockerd inside a lightweight Linux VM.
- Can you get both? Kata Containers, Firecracker microVMs and gVisor (a user-space kernel) provide stronger isolation and are common in multi-tenant setups.
Bonus points
Point out that "a container is not a lighter VM but an isolated process"; in production the two are often combined: containers running on cloud VMs.
Common wrong answers
"A container has a stripped-down OS inside" — an image contains only user-space files, no kernel; "containers are fully isolated" — a shared kernel means kernel vulnerabilities can lead to escapes.
See Lesson 1 Module 1.
Q2. What Linux namespaces are there, and what does Docker use them for?Mid
30-second answer
A namespace gives a process a "private" view of a system resource. Docker creates PID, NET, MNT, UTS and IPC namespaces for every container, optionally a USER namespace, and uses a cgroup namespace by default (under cgroup v2).
In-depth answer
- PID: processes in the container are numbered from 1 and cannot see host processes.
- NET: separate interfaces, routes, iptables and port space (so every container can listen on 80).
- MNT: a separate mount table, with the root switched to the image rootfs (pivot_root).
- UTS: separate hostname; IPC: separate shared memory/semaphores.
- USER: container root maps to an unprivileged host UID (userns-remap / rootless).
- cgroup: hides the host cgroup hierarchy. There is also a time namespace, which Docker does not use by default.
PID=$(docker inspect -f '{{.State.Pid}}' web)
sudo ls -l /proc/$PID/ns # each namespace is an inode
sudo nsenter -t $PID -n ip addr # enter only the network namespace for troubleshooting
docker run --pid=host --network=host … # share the host's namespaces
Common follow-up questions
- Can two containers share a namespace? Yes:
--network container:web,--pid container:web(containers in a Kubernetes Pod share NET/IPC). - Can namespaces limit CPU? No, that is the job of cgroups.
Bonus points
Mention using nsenter to troubleshoot distroless images (Lesson 7); name the system calls clone()/unshare()/setns().
Common wrong answers
Confusing namespaces with cgroups; believing namespaces isolate the kernel (the kernel is still shared, and some parameters in /proc/sys remain global).
Q3. What are cgroups? How do v1 and v2 differ?Mid
30-second answer
cgroups (control groups) provide resource limits, accounting and prioritization for a group of processes: CPU, memory, number of PIDs, block IO and more. Docker's --memory, --cpus and --pids-limit all write cgroup files. Modern distributions default to cgroup v2: a unified hierarchy with a single mount point and more consistent interfaces.
In-depth answer
- v1: one tree per controller (/sys/fs/cgroup/memory, /cpu…); a process can sit in different places in different trees, which is complex to manage.
- v2: one unified tree with files such as
memory.max,memory.events,cpu.max,cpu.stat,pids.max; supports PSI (pressure stall information) and more accurate memory accounting. - cgroup driver:
systemd(recommended, co-managed with systemd) orcgroupfs; Kubernetes requires the kubelet and the runtime to match.
docker info --format '{{.CgroupDriver}} v{{.CgroupVersion}}'
docker run --rm --memory 128m --cpus 0.5 alpine cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max
systemd v2 134217728 50000 100000
Common follow-up questions
- What happens when the memory limit is exceeded? OOM kill inside the cgroup, exit code 137 (Part A #17).
- And the CPU limit? The process is not killed but throttled (#24).
Bonus points
Explain the "quota/period" meaning of cpu.max and the resulting throttling; mention container awareness in the Java/Go runtimes.
Common wrong answers
"Exceeding CPU also gets you killed"; "cgroups provide isolation" (cgroups manage resources; isolation comes from namespaces).
Q4. Describe Docker's architecture: what do the docker CLI, dockerd, containerd, shim and runc each do?Mid
30-second answer
The CLI is a REST client that calls dockerd over a socket; dockerd handles high-level features (image builds, networking, volumes, the API) and delegates the container lifecycle to containerd; containerd starts a containerd-shim per container, the shim calls runc to create the container process according to the OCI spec, then runc exits and the shim stays behind to hold the process's stdio and exit code.
In-depth answer
- dockerd: the Docker Engine API, BuildKit (built in), libnetwork (bridges/iptables/embedded DNS), volumes, log drivers.
- containerd: image pull and storage (new Engine 29 installs use the containerd image store by default), snapshots, task management; also the CRI runtime commonly used by Kubernetes.
- shim: keeps containers running when dockerd/containerd restart (together with
live-restore). - runc: the OCI runtime reference implementation; it calls clone/unshare, sets up cgroups, pivot_root and seccomp, then execs the user process. It can be replaced by crun, gVisor (runsc) or Kata.
ps -ef | grep -E 'dockerd|containerd|shim' | grep -v grep
docker info --format '{{.DefaultRuntime}} {{json .Runtimes}}'
Common follow-up questions
- Do containers stop if dockerd dies? Not with live-restore enabled.
- Does Kubernetes still use Docker? 1.24 removed dockershim; the kubelet uses containerd/CRI-O directly via CRI. Images built with Docker (OCI format) still work.
Bonus points
Draw Figure 5-1; mention containerd namespaces (moby vs k8s.io) and the ctr/nerdctl tools.
Common wrong answers
"dockerd forks the container process directly"; "after Kubernetes dropped Docker, Docker images no longer work".
See Lesson 1 Module 1.
Q5. What is the OCI, and which specifications does it define?Mid
30-second answer
The OCI (Open Container Initiative) is an open standards body under the Linux Foundation that defines three specifications: the Image Spec (image format: manifest, config, layers, index), the Runtime Spec (how to run a container from a bundle: config.json + rootfs) and the Distribution Spec (the registry HTTP API). It lets Docker, Podman, containerd, Kubernetes and all kinds of registries interoperate.
In-depth answer
- Image = manifest (references the digests of the config and layers) + config (environment variables, entrypoint, history) + layers (tar deltas). Multi-platform images use an image index that points to several manifests.
- Every object is content-addressed (sha256 digest), so it can be deduplicated and verified.
- The Distribution Spec defines endpoints such as
/v2/<name>/manifests/<ref>and/blobs/; OCI 1.1 added the referrers API for attaching signatures and SBOMs to images.
docker buildx imagetools inspect --raw nginx:alpine | jq '.mediaType, .manifests[0]'
Common follow-up questions
- Is the Docker image format the same as OCI? Docker Image Manifest V2 Schema 2 is the predecessor of OCI and they are largely compatible; BuildKit can output either media type.
- Can Helm charts be stored in a registry? Yes, as OCI artifacts.
Bonus points
Mention the referrers API with cosign/Notation signatures and SBOM attestations; runc is the reference implementation of the Runtime Spec.
Common wrong answers
Treating OCI as a product; believing "OCI only specifies images".
Q6. What is the difference between an image and a container? What is the container's writable layer?Junior
30-second answer
An image is a read-only layered template (filesystem + metadata); a container is a running instance of an image: a thin writable layer on top of the image layers, plus runtime state (processes, network, mounts). One image can start any number of containers, each with its own writable layer.
In-depth answer
- Analogy: the image is a class and the container an object; or the image is an installer/snapshot and the container the running program.
- Copy-on-write (CoW): when a container modifies a file from the image, the file is first copied into the writable layer (copy-up) and then modified; a delete writes a whiteout marker.
docker diffshows the changes in the writable layer;docker ps -sshows its size;docker commitcan freeze the writable layer into a new image (not recommended for production — not reproducible).
Common follow-up questions
- Where does the data go when the container is removed? The writable layer is deleted with it; use volumes for persistence (A #39).
- Why shouldn't a database write to the writable layer? CoW and overlay write performance is poor, and the lifecycle is tied to the container.
Bonus points
Mention that image layers are shared across containers and images, saving disk space and page cache.
Common wrong answers
"A container modifies its image"; "docker commit is the normal way to build images".
See Lesson 1 Module 3.
Q7. What states can a container be in? Walk through the lifecycle commands.Junior
30-second answer
States: created → running ⇄ paused, → restarting, → exited, plus removing and dead. docker run = create + start; stop sends SIGTERM, waits, then SIGKILL; kill sends a signal immediately (SIGKILL by default); pause freezes processes with the cgroup freezer; rm removes the container and its writable layer.
In-depth answer
docker create --name w nginx:alpine; docker inspect -f '{{.State.Status}}' w # created
docker start w; docker pause w; docker inspect -f '{{.State.Status}}' w # paused
docker unpause w; docker stop -t 5 w; docker inspect -f '{{.State.Status}} {{.State.ExitCode}}' w
docker events --filter container=w --since 5m --format '{{.Action}}' # create start pause unpause kill die stop
For how exit codes relate to states, see Figure 2-1 in Part A; dead usually means removal failed (e.g. device busy).
Common follow-up questions
- Difference between stop and kill? stop gives the process a chance to shut down gracefully; kill terminates it immediately (use
-sto choose the signal). - What is pause for? Temporarily freezing processes (e.g. for a consistent snapshot); the processes receive no signal.
Bonus points
Mention that docker events can audit state transitions and monitor die/oom events.
Common wrong answers
"After stop the container is deleted" (that needs rm or --rm); "pause is the same as stop".
Q8. What happens behind the scenes when you run docker run -d -p 8080:80 nginx?Senior
30-second answer
The CLI calls the API → dockerd checks for the image locally and, if missing, pulls it from the registry via containerd (resolve tag → manifest → select platform → download layers and unpack them into snapshots) → creates the container config and writable layer → libnetwork creates a veth pair, attaches it to the bridge, assigns an IP and writes the iptables DNAT → containerd starts a shim, which calls runc to create namespaces and cgroups, mount the rootfs, apply seccomp/capabilities and exec nginx → the CLI returns the container ID.
In-depth answer
- Resolve the reference:
nginx→docker.io/library/nginx:latest. - Pull: GET the manifest (index) → select linux/amd64 → download layer blobs in parallel (verified by digest).
- Create: generate the OCI runtime config (config.json) and prepare the overlay mount (lowerdir = image layers, upperdir = writable layer).
- Network: create a veth pair, move one end into the container netns and rename it eth0, attach the other end to docker0; IPAM assigns an address; port publishing writes nat-table DNAT rules and starts docker-proxy if needed.
- Start: shim → runc create/start → the process becomes the container's PID 1; the log driver starts collecting stdout/stderr.
Common follow-up questions
- What does docker-proxy do? It handles cases iptables cannot cover, such as access via the host's own loopback; it can be disabled with
"userland-proxy": false(with compatibility caveats). - How are layers reused when pulling? Layers with a digest already present locally are skipped.
Bonus points
Structure the answer as five steps — image → storage → network → runtime → logs — and map each step to a Part A failure (#12 #48 #27 #16).
Common wrong answers
Leaving out the network and iptables steps; saying "docker run starts a virtual machine".
Q9. How do Docker Desktop and Docker Engine differ?Junior
30-second answer
Docker Engine is the open-source daemon + CLI on Linux (the Moby project); Docker Desktop is a commercial product for Mac/Windows/Linux desktops that bundles a Linux VM (running Engine), a GUI, Compose, BuildKit, Kubernetes, extensions and more. Desktop requires a paid subscription for companies above a certain size (Docker's official terms are authoritative).
In-depth answer
- Networking differences: on Desktop there is a VM between containers and the host;
host.docker.internalis available; host network mode behaves differently (A #38); port forwarding is done by Desktop's proxy. - File sharing: bind mounts must be shared across the VM, which is slow with many small files.
- Windows: WSL 2 backend; Windows containers can also run (requires switching modes).
- Alternatives: Podman Desktop, Rancher Desktop, Colima, OrbStack and others.
Common follow-up questions
- Do you install Desktop on production servers? No, servers get Docker Engine.
- Why doesn't an image built on a Mac run on the server? Apple Silicon builds arm64 by default (A #5).
Bonus points
Explain the troubleshooting differences caused by "Desktop's localhost is not the Linux host's localhost".
Common wrong answers
"Desktop and Engine are identical; Desktop just adds a UI".
Q10. What is rootless Docker? How does it differ from userns-remap and --user?Senior
30-second answer
Rootless: dockerd and the containers both run as a regular user (user namespaces + slirp4netns/pasta networking + rootless overlay), so even a compromised daemon cannot obtain host root. userns-remap: dockerd still runs as root, but root inside the container maps to an unprivileged subordinate UID on the host. --user: only makes the container process run with a non-zero UID; the daemon and mappings are unchanged.
In-depth answer
| Daemon | Container root on the host | Limitations | |
|---|---|---|---|
| Default | root | root (constrained by capabilities/seccomp) | — |
| --user 10001 | root | UID 10001 | Image must support it |
| userns-remap | root | e.g. 100000 | Volume permissions, some features incompatible |
| rootless | regular user | the user's subordinate UID | Low ports, some network/storage drivers, performance limits (see the official docs) |
dockerd-rootless-setuptool.sh install
export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock
docker info --format '{{.SecurityOptions}}' # includes name=rootless
Common follow-up questions
- Can a rootless container bind port 80? Not by default; adjust
net.ipv4.ip_unprivileged_port_startor use setcap. - What is Podman's advantage? Daemonless + rootless by default.
Bonus points
Frame it as a threat model: docker group membership = root (A #46), and rootless reduces the impact of a compromised daemon.
Common wrong answers
"The USER instruction is rootless".
Official Rootless mode; see also Lesson 2 Hardening.
Q11. How does overlay2 (or the overlayfs snapshotter) work? What does copy-on-write cost?Senior
30-second answer
OverlayFS stacks several read-only lowerdirs (image layers) and one writable upperdir (the container layer) into a single merged view. Reads search from the top down; the first write to a lower-layer file copies up the whole file into the upperdir; deletes are masked with whiteout files. The cost: first writes to large files are slow and write-heavy workloads (databases) perform poorly, so such data belongs on volumes.
In-depth answer
docker inspect -f '{{json .GraphDriver.Data}}' web | jq # with classic overlay2 you can see LowerDir/UpperDir/MergedDir
mount | grep overlay | head -2
- Classic store: dockerd's
overlay2graphdriver; containerd image store: containerd'soverlayfssnapshotter — same principle. - Layer sharing means 100 containers on one host use just one copy of the image on disk and in the page cache.
- Inode consumption, directory rename semantics (redirect_dir) and the
ftype=1requirement on xfs are production details to watch.
Common follow-up questions
- Why doesn't downloading in one layer and deleting in the next shrink the image? The delete is just a whiteout in the upper layer; the data is still in the lower layer (A #7).
- What other storage drivers are there? btrfs, zfs, fuse-overlayfs (the older rootless option), vfs (no CoW, for testing).
Bonus points
Connect copy-up with "logs written to the writable layer bloat the container layer".
Common wrong answers
"Every container gets its own full copy of the image".
Official Storage drivers; see also Lesson 1 Modules 3 and 6.
Q12. Why is PID 1 special in a container? What is the impact of the shell form vs the exec form?Mid
30-second answer
PID 1 has two special duties on Linux: signals without a registered handler are ignored by the kernel (so the default SIGTERM does not kill it), and it must adopt and reap orphaned processes. The shell form CMD node app.js makes /bin/sh PID 1, which does not forward signals, so a stop waits 10 seconds and ends in SIGKILL; the exec form makes the application PID 1 directly.
In-depth answer
CMD ["node","server.js"] # exec form: node is PID 1 ENTRYPOINT ["/entrypoint.sh"] # last line of the script: exec "$@" # to reap zombies or when the app does not handle signals: docker run --init / Compose init: true
Docker's stop sequence: STOPSIGNAL (SIGTERM by default) → grace period → SIGKILL. The application must handle SIGTERM: stop accepting new requests, finish in-flight requests, close connections.
Common follow-up questions
- What does tini do? It is a minimal init: forwards signals to child processes and reaps zombies (A #20).
- Why does this matter in Kubernetes too? Pod deletion also sends SIGTERM, followed by SIGKILL after terminationGracePeriodSeconds.
Bonus points
Tie it to real exit codes: 137 when SIGKILLed, 0 or 143 when SIGTERM is handled correctly.
Common wrong answers
"The exec form and the shell form are just different syntax"; "containers stop slowly because the image is too big".
Q13. What restart policies does Docker have? What is live-restore?Junior
30-second answer
Restart policies: no (default), on-failure[:N] (restart on non-zero exit, optionally limited), always (always restart, also started when dockerd starts), unless-stopped (like always, but a container you stopped manually is not started again after dockerd restarts). live-restore is a daemon option that keeps containers running while dockerd is stopped or upgraded.
In-depth answer
- There is an increasing back-off delay between restarts (starting at 100ms and doubling); a container that runs for more than 10 seconds counts as successful and the delay resets.
- Restart policies look only at process exit, not health: Docker does not automatically restart unhealthy containers (Swarm/orchestrators replace them).
- A container stopped manually with
docker stopis not brought back by its restart policy (until dockerd restarts, when always brings it back).
docker run -d --restart unless-stopped --name api myapp
docker update --restart on-failure:5 api
# /etc/docker/daemon.json: { "live-restore": true }
Common follow-up questions
- Which one in production? unless-stopped is common for single-host services; on-failure:N for batch jobs.
- Limitations of live-restore? Incompatible with Swarm mode; may not apply across major version upgrades (see the official docs).
Bonus points
Point out that "restart policies are no substitute for fixing the problem" and must be paired with alerting (A #14).
Common wrong answers
"unhealthy triggers an automatic restart by Docker".
Official Start containers automatically, Live restore.
Scenario 5-1: Convincing the team to move from VM deployments to containers
Your team runs 12 Java services on 24 VMs, and every release means SSHing into machines to replace jar files. The CTO asks: what would containerization bring? What are the risks? How would you roll it out in phases?
Key points of a reference answer
- Benefits: immutable images (build once, run anywhere), dependencies packaged with the image, rollback in seconds (switch the image tag), higher resource density, integration with CI/CD and orchestrators.
- Risks: shared-kernel isolation is weaker than VMs (multi-tenancy needs extra hardening); the JVM needs container-aware memory/CPU settings; stateful services, logging and monitoring must be redesigned; team skills.
- Phases: ① containerize 1–2 stateless services first, with CI producing images; ② run them on the existing VMs with Compose/systemd and validate observability; ③ introduce a registry, scanning and signing; ④ as scale grows, evaluate a managed container platform or Kubernetes.
- Metrics: release duration, rollback time, resource utilization, time to recover from failures.
Scenario 5-2: "Noisy neighbors" on one host
A 16-core host runs 20 containers; whenever a batch container runs, the latency of the other online services triples. How do you pinpoint and isolate the problem?
Key points of a reference answer
- Pinpoint: use
docker stats, the cgroup filescpu.stat/memory.events/io.statand PSI (cpu.pressure,io.pressure) to tell whether the contention is CPU, memory reclaim or disk IO. - Isolate: give the batch job a lower weight with
--cpus/--cpu-shares, a--memorylimit and block IO limits (--device-read-bpsetc.); pin online services to cores with--cpuset-cpus. - Architecture: schedule batch jobs on dedicated nodes/time windows; use requests/limits and QoS classes in an orchestrator.
- Explain that namespaces do not isolate resource contention — only cgroups can limit it.
Video tutorials (titles and channels verified via YouTube oEmbed)
No verified video dedicated to Docker interview questions was found. Use this module's Mock Interview and record yourself for playback.
Module 6 · Part B: Images & Dockerfile (Questions 14–25)
- Explain the cache-key rules, how instruction order affects caching, and the value of multi-stage builds.
- Distinguish commonly confused instructions: CMD/ENTRYPOINT, COPY/ADD, ARG/ENV.
- Master the key points for tags vs digests, multi-arch, advanced BuildKit features and reproducible builds.
Q14. How do image layers and the build cache work? How do you write a cache-friendly Dockerfile?Mid
30-second answer
Instructions that modify the filesystem (RUN, COPY, ADD) create new layers; the others only change metadata. BuildKit computes a cache key for every step: the parent step + the instruction content, and for COPY/ADD also the checksums of the source files. On a hit the step is reused; once one step misses, everything after it is rebuilt. So put rarely changing steps (system packages, dependency manifests) first and source code last.
In-depth answer
FROM python:3.13-slim WORKDIR /app COPY requirements.txt . RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt COPY . . CMD ["python","-m","app"]
- The RUN cache looks only at the command text, not the outside world:
RUN apt-get updateon its own line hits a stale cache and later installs get old packages, so put it on the same line as install. - CI must export/import the cache (registry, gha, local directory), because each run may use a brand-new builder.
--no-cacherebuilds everything;--no-cache-filter stagedisables the cache for one stage only.
Common follow-up questions
- How does a cache mount differ from the layer cache? A cache mount is a directory persisted across builds that never enters the image; downloads are reused even when layers miss.
- What is mode=max? It exports the cache for all intermediate stages, not just the layers of the final image.
Bonus points
Give the example from A #2 together with a CI cache configuration.
Common wrong answers
"Every instruction creates a layer" (ENV/LABEL and similar create no filesystem layer); "the cache expires over time".
See Lesson 1 Module 4.
Q15. What is the difference between CMD and ENTRYPOINT? How do they combine?Junior
30-second answer
ENTRYPOINT defines "what program the container is"; CMD supplies "default arguments". docker run img args replaces CMD, while ENTRYPOINT can only be overridden with --entrypoint. When both use the exec form, the final command = ENTRYPOINT + CMD.
In-depth answer
| No ENTRYPOINT | ENTRYPOINT ["app"] | |
|---|---|---|
| No CMD | Error (no command) | app |
| CMD ["--port","80"] | --port 80 (treated as the command) | app --port 80 |
| docker run img --debug | --debug | app --debug |
ENTRYPOINT ["/entrypoint.sh"] # initialization (wait for dependencies, render config), then exec "$@" CMD ["gunicorn","-b","0.0.0.0:8000","app:app"]
A shell-form ENTRYPOINT ignores CMD and run arguments, and makes sh PID 1 (signal problems, Q12).
Common follow-up questions
- How does it map to Kubernetes?
commandoverrides ENTRYPOINT,argsoverrides CMD. - And in Compose?
entrypoint:andcommand:.
Bonus points
Volunteer that "setting ENTRYPOINT resets the base image's CMD".
Common wrong answers
"They are exactly the same; use either".
Q16. What is a multi-stage build, and what problem does it solve?Junior
30-second answer
A Dockerfile contains several FROM … AS name lines: earlier stages compile and test, and the last stage takes only the artifacts it needs with COPY --from=. Benefits: the final image contains no compiler or source code, so it is small with a small attack surface, and one file describes the whole flow without external build scripts.
In-depth answer
FROM --platform=$BUILDPLATFORM golang:1.25 AS build ARG TARGETOS TARGETARCH WORKDIR /src COPY go.mod go.sum ./ RUN --mount=type=cache,target=/go/pkg/mod go mod download COPY . . RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /out/app ./cmd/app FROM build AS test RUN go test ./... FROM gcr.io/distroless/static-debian12:nonroot COPY --from=build /out/app /app ENTRYPOINT ["/app"]
- BuildKit builds only the stages the target depends on, and runs independent stages in parallel.
- Run the test stage in CI with
--target test; you can alsoCOPY --from=nginx:alpineto copy from any image.
Common follow-up questions
- Do intermediate stages end up in the final image? No, but they stay in the build cache.
- What happens if a stage name is misspelled? It is pulled as an image (A #4).
Bonus points
Explain multi-arch with $BUILDPLATFORM cross-compilation (Q23).
Common wrong answers
"Multi-stage means merging several images into one".
Q17. What is the difference between COPY and ADD? When should you use ADD?Junior
30-second answer
COPY only copies files from the build context (or another stage/image). ADD additionally supports auto-extracting local tar archives, downloading from URLs and adding Git repositories directly. The official recommendation is to default to COPY for clearer semantics, and use ADD only when you need auto-extraction of a local tar or a remote source (with a checksum).
In-depth answer
COPY --chown=10001:10001 --chmod=0755 run.sh /app/ ADD rootfs.tar.gz / # local tar is auto-extracted ADD --checksum=sha256:<digest> https://example.com/tool.tgz /tmp/ # verified remote file (not auto-extracted) ADD https://github.com/org/repo.git#v1.2.0 /src # Git source (BuildKit)
- Files downloaded from a URL are not extracted; a remote ADD without a checksum makes the build non-reproducible.
COPY --linkmakes the layer independent of previous layers, so it can be reused (rebased) when the base image changes.
Common follow-up questions
- Why not download with ADD? It is opaque, hard to cache and easily brings in unverified content; use
RUN curl -fsSL … && sha256sum -corADD --checksum.
Bonus points
Mention modern flags such as --chown/--chmod/--link/--exclude (some require a recent Dockerfile frontend; see the official docs).
Common wrong answers
"A tar.gz downloaded by ADD is auto-extracted too".
Official Dockerfile reference · ADD.
Q18. What is the difference between ARG and ENV, and what are their scopes?Mid
30-second answer
ARG is a build-time variable passed with --build-arg and not kept in the image's runtime environment; variables set with ENV are written into the image config and visible to later build steps and at runtime. Neither is suitable for passing secrets (ARG values appear in the image history metadata, A #8).
In-depth answer
ARG PY_VERSION=3.13 # an ARG before FROM can only be used in FROM lines
FROM python:${PY_VERSION}-slim
ARG PY_VERSION # redeclare it to use it inside the stage (no value = inherit)
ARG APP_VERSION=dev
ENV APP_VERSION=${APP_VERSION} # convert to ENV if it must be visible at runtime
LABEL org.opencontainers.image.version=${APP_VERSION}
- An ARG is scoped to the stage that declares it, from the declaration to the end of the stage; each stage must declare its own.
- Predefined ARGs:
HTTP_PROXYand friends (not recorded in history) and platform variables such asTARGETPLATFORM/BUILDPLATFORM. -eat runtime can override ENV.
Common follow-up questions
- Does changing an ARG value affect the cache? Yes, it invalidates the first instruction that uses it and every step after it.
- How do you pass secrets?
RUN --mount=type=secret.
Bonus points
Clearly explain the common "ARG before FROM" pitfall.
Common wrong answers
"ARG is safe because it does not appear at runtime".
See Lesson 1 Module 4.
Q19. How do you reduce image size? List your techniques.Mid
30-second answer
① Pick the smallest suitable base image (slim/distroless/alpine); ② multi-stage builds that copy only the artifacts; ③ install and clean caches in the same layer; ④ exclude irrelevant files with .dockerignore; ⑤ skip recommended packages and debugging tools; ⑥ use scratch/distroless static for statically compiled languages.
In-depth answer
docker history --format 'table {{.Size}}\t{{.CreatedBy}}' myapp:1.0 | sort -h -r | head
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive myapp:1.0 # analyze wasted space layer by layer
- apt:
--no-install-recommendsplusrm -rf /var/lib/apt/lists/*; pip:--no-cache-diror a cache mount; npm:npm ci --omit=dev. - "Download, then delete" across different layers does nothing (whiteout, Q11).
- Size is not the only goal: ease of debugging, glibc compatibility and the security patch cadence matter just as much.
Common follow-up questions
- What are the benefits of small images? Faster pulls (scale-out/cold start), lower storage and bandwidth costs, fewer CVEs.
- Is docker-squash a good idea? Flattening layers loses layer sharing; multi-stage is usually better.
Bonus points
Give a quantified example: a Python service from 1.8GB down to 180MB (A #7); and set a size budget in CI.
Common wrong answers
"Just switch everything to alpine" (musl compatibility problems, A #18).
Q20. How do you choose between alpine, slim, distroless and scratch?Mid
30-second answer
slim (trimmed Debian): glibc and the best compatibility — the general-purpose default. alpine: tiny, but uses musl libc, so native extensions/prebuilt binaries may be incompatible and DNS behaves differently. distroless: only the runtime and dependencies, no shell or package manager — small attack surface but hard to debug. scratch: an empty image, suitable only for statically compiled binaries.
In-depth answer
| Image | Typical size | shell | Good for |
|---|---|---|---|
| python:3.13-slim | ~100MB+ | yes | Interpreted languages such as Python/Node |
| alpine | ~5–10MB | yes (busybox) | Tooling images, purely static programs |
| distroless | ~2–50MB | no (:debug variants exist) | Production images for Go/Java/Node |
| scratch | 0 | no | Go/Rust binaries with CGO_ENABLED=0 |
With scratch you must bring your own CA certificates (/etc/ssl/certs), time zone data and a non-root user (numeric UID). Debugging distroless: docker debug, a temporary sidecar, or a Kubernetes ephemeral container.
Common follow-up questions
- How do you troubleshoot without a shell? Enter the namespaces with nsenter, or attach a debug container (Lesson 7).
- What are images like Docker Hardened Images / Chainguard? Continuously patched, minimal commercial/community images (details vary by vendor).
Bonus points
Stress the decision criteria: compatibility > attack surface > size.
Common wrong answers
"distroless is just alpine".
Q21. What is the difference between a tag and a digest? How should production reference images?Mid
30-second answer
A tag is a mutable, human-readable pointer (myapp:1.4, latest) that can be repointed to new content; a digest is the sha256 hash of the content (myapp@sha256:…) and is immutable — if the content changes, the digest changes. Production deployments should reference digests (or immutable tags with tag immutability enabled in the registry) to stay traceable and rollback-friendly.
In-depth answer
docker buildx imagetools inspect myacr.azurecr.io/myapp:1.4 | grep Digest
docker pull myacr.azurecr.io/myapp@sha256:9f2c…
docker image inspect -f '{{json .RepoDigests}}' myapp:1.4
- The digest of a multi-platform image points to the index; each platform has its own manifest digest.
- Tagging strategy: semantic version + Git SHA (
1.4.2,sha-3f2a1c); never deploy with latest. - At the registry level: ECR tag immutability, ACR locks, Harbor immutability rules.
Common follow-up questions
- What is wrong with latest? You do not know which version is running, you cannot roll back, and different nodes may pull different content; in Kubernetes, latest defaults to imagePullPolicy Always.
- How do you make digests human-readable? Record the tag alongside as a comment in the deployment manifest, or use
image: repo:1.4@sha256:…(the tag is ignored and only aids readability).
Bonus points
Tie it to signature verification: signatures are bound to the digest.
Common wrong answers
"Version-number tags are immutable by nature".
Q22. What important features does BuildKit have compared with the classic builder?Senior
30-second answer
BuildKit compiles a Dockerfile into a dependency graph (LLB) and solves it concurrently: independent stages run in parallel and unused stages are skipped. It supports cache mounts, secret mounts, SSH forwarding, remote cache import/export, multi-platform output, multiple output formats (image/OCI tar/local directory), attestations (SBOM/provenance), build checks and heredoc syntax. It is the default builder for docker build.
In-depth answer
# syntax=docker/dockerfile:1 RUN --mount=type=cache,target=/var/cache/apt,sharing=locked apt-get update && apt-get install -y gcc RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci RUN --mount=type=ssh git clone git@github.com:org/private.git RUN <<EOF set -eux ./configure && make EOF
docker buildx build --platform linux/amd64,linux/arm64 \ --cache-from type=registry,ref=REG/app:cache --cache-to type=registry,ref=REG/app:cache,mode=max \ --sbom=true --provenance=mode=max -t REG/app:1.0 --push . docker buildx bake # describe multiple targets in an HCL/Compose file
Common follow-up questions
- What is buildx? The BuildKit CLI plugin that manages builder instances (docker, docker-container, kubernetes and remote drivers).
- What does the # syntax line do? It selects the Dockerfile frontend version, so you can use new syntax without upgrading Docker.
Bonus points
Explain build checks (docker build --check) and what remote builders such as Docker Build Cloud are for.
Common wrong answers
"BuildKit is just a faster version of the old builder".
Q23. How do you build multi-arch (amd64 + arm64) images, and how does it work?Senior
30-second answer
Use docker buildx build --platform linux/amd64,linux/arm64 --push. The result is a manifest list / OCI image index that points to a different image manifest per platform; clients automatically pick the one matching their platform when pulling. There are three ways to build for foreign platforms: QEMU emulation (simple but slow), cross-compilation (fast), and a builder made of several native nodes (fastest).
In-depth answer
docker buildx create --name multi --driver docker-container --use docker run --privileged --rm tonistiigi/binfmt --install arm64 # QEMU docker buildx build --platform linux/amd64,linux/arm64 -t REG/app:1.0 --push . docker buildx imagetools inspect REG/app:1.0 # native nodes: docker buildx create --append --name multi ssh://arm-builder
In the Dockerfile, use FROM --platform=$BUILDPLATFORM so the compile stage runs on the native architecture, then cross-compile per TARGETARCH (see the Q16 example). The classic image store cannot keep multi-platform images locally, so use --push or the containerd image store.
Common follow-up questions
- What is exec format error? An architecture mismatch (A #5).
- What are the risks of QEMU? It is slow, and a few programs misbehave under emulation (A #18).
Bonus points
Mention native ARM runners in CI for speed, and running tests on the target architecture.
Common wrong answers
"Images built on a Mac automatically support every platform".
Official Multi-platform builds.
Q24. How does HEALTHCHECK work, and how does it relate to Kubernetes probes?Mid
30-second answer
HEALTHCHECK makes dockerd run a command inside the container periodically: exit code 0 is healthy, 1 unhealthy, and after retries consecutive failures the status becomes unhealthy; failures during start_period do not count. It is used by Compose's service_healthy condition and by Swarm; Docker itself does not restart a container for being unhealthy; Kubernetes does not use the image's HEALTHCHECK and relies on its own liveness/readiness/startup probes.
In-depth answer
HEALTHCHECK --interval=15s --timeout=3s --start-period=30s --retries=3 \ CMD ["/app/healthcheck"] # tiny static binary, no curl needed
docker inspect -f '{{json .State.Health}}' api | jq '.Status,.Log[-1]'
- A health check should be cheap and check only the service itself, so that downstream dependencies do not cause cascading unhealthy states (A #23).
- In Kubernetes, a failed liveness probe restarts the container, a failed readiness probe removes it from traffic, and the startup probe protects slow starts — three different semantics, whereas HEALTHCHECK has only one.
Common follow-up questions
- What does an exec probe cost? Each run forks a process; too short an interval burns CPU.
- How do you wait for the database in Compose?
depends_on+condition: service_healthy(Q32).
Bonus points
Point out that managed platforms such as Container Apps do not run the image's HEALTHCHECK either (Lesson 3).
Common wrong answers
"Docker automatically restarts unhealthy containers".
See Lesson 2 HEALTHCHECK.
Q25. What does .dockerignore do? How do you achieve reproducible builds?Senior
30-second answer
.dockerignore excludes files from the build context: it speeds up context transfer, avoids leaking .env/.git, and keeps irrelevant files from invalidating the COPY cache. A reproducible build means the same inputs produce the same image: pin base image digests, lock dependency versions, fix timestamps (SOURCE_DATE_EPOCH), and avoid unverified network resources during the build.
In-depth answer
* !src/ !package.json !package-lock.json
export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) docker buildx build --build-arg SOURCE_DATE_EPOCH \ --output type=image,name=REG/app:1.0,push=true,rewrite-timestamp=true . # compare digests after two builds; rewrite-timestamp needs a recent BuildKit (see the official docs)
- Other sources of nondeterminism:
apt-get upgrade, unlocked pip/npm dependencies, file order and permissions, builder version. - Provenance attestations record the build inputs (source commit, base image digest, build arguments) for auditing.
Common follow-up questions
- Where does .dockerignore go? In the context root; you can also write
<name>.Dockerfile.dockerignorefor a specific Dockerfile. - Why does reproducibility matter? Supply-chain security (verifying that binaries come from the declared source), auditability, cache hits.
Bonus points
Mention SLSA levels and provenance, and connect them to the signing practices in Lesson 5.
Common wrong answers
".dockerignore only affects build speed".
Official Reproducible builds (the official docs are authoritative); see also Lesson 5 Supply chain.
Scenario 6-1: Cutting a CI build from 12 minutes to 2
A mixed Node + Python monorepo takes 12 minutes per build on GitHub Actions and produces a 1.6GB image. In what order would you optimize?
Key points of a reference answer
- Measure: find the slow steps with
--progress=plainand the large layers withdocker history. - Context: a
.dockerignore(node_modules, .git, test data). - Instruction order: copy dependency manifests first; cache npm/pip downloads with
RUN --mount=type=cache. - Remote cache:
--cache-to type=gha,mode=maxor a registry cache, with a separate scope per service. - Parallel stages: put the frontend build and backend dependency install in independent stages so BuildKit runs them in parallel; the final image copies only artifacts.
- Size: slim base images,
npm ci --omit=dev; set a size budget. - Multi-arch: native ARM runners instead of QEMU; or build multiple services in parallel with bake.
Scenario 6-2: A critical CVE in the base image
On a Friday afternoon the security team reports a critical OpenSSL vulnerability, and the company has 80 service images. How do you fix it within 24 hours and prove the fix is in place?
Key points of a reference answer
- Find affected images: query SBOMs/scan results (Docker Scout, Trivy, registry scanning) by package name and version instead of guessing one by one.
- Fix: base images are maintained centrally by the platform team (internal golden images); after the digest is updated, Renovate opens PRs for every service automatically; CI rebuilds, tests, signs and pushes.
- Release: roll out in risk-based batches, with deployments referencing the new digests.
- Proof: fresh scan reports, SBOM diffs, the base image digest in provenance; reconcile the inventory of running workloads.
- Improve: centralized base images, automatic weekly rebuilds, and an admission policy that rejects images with critical CVEs.
Video tutorials (titles and channels verified via YouTube oEmbed)
No verified video dedicated to advanced BuildKit features or reproducible builds was found; rely on the official Docker Build documentation.
Module 7 · Part B: Networking, Storage & Compose (Questions 26–38)
- Compare network drivers and explain how port publishing (DNAT) and embedded-DNS service discovery work.
- Compare volume / bind / tmpfs and describe backup and sharing options.
- Master Compose dependency readiness, profiles, multi-file merging, variable precedence, scaling, watch and recreation rules.
Q26. Which network drivers does Docker have, and what is each one for?Junior
30-second answer
bridge (the single-host default; user-defined bridges include DNS), host (shares the host network stack; no isolation, no NAT), none (loopback only), overlay (multi-host; Swarm uses VXLAN), macvlan/ipvlan (containers get IPs directly on the physical subnet, like separate devices). For everyday single-host work, prefer a user-defined bridge.
In-depth answer
| Driver | How it works | Good for | Watch out for |
|---|---|---|---|
| bridge | Linux bridge + veth + NAT | Single-host applications | The default bridge has no DNS (A #29) |
| host | No netns is created | Maximum performance, many ports | Port conflicts; Desktop differences (A #38) |
| overlay | VXLAN encapsulation, UDP 4789 | Swarm across hosts | MTU overhead (A #33) |
| macvlan | Sub-interfaces with their own MAC | Legacy systems that need real IPs | By default the host cannot reach its own macvlan containers; switches may limit the number of MACs |
| ipvlan | Shared MAC, L2/L3 modes | Cloud environments that restrict MACs | — |
docker network create --driver bridge --subnet 10.30.0.0/24 app-net docker network create -d macvlan --subnet 192.168.1.0/24 --gateway 192.168.1.1 -o parent=eth0 lan
Common follow-up questions
- What is an internal network? A network created with
--internalhas no outbound route, which suits database backend networks. - Can one container join several networks? Yes, commonly a gateway container joins both the frontend and backend networks.
Bonus points
Compare along three axes — isolation, performance, reachability — and explain the limits of Docker's network model compared with Kubernetes CNI.
Common wrong answers
"Host mode is more secure"; "the default bridge is the same as a user-defined bridge".
Q27. How is -p 8080:80 port publishing implemented under the hood?Senior
30-second answer
dockerd adds a DNAT rule to the iptables nat table: traffic to destination port 8080 is rewritten to containerIP:80 and then forwarded through the FORWARD chain to the container on the bridge; outbound traffic is SNATed via MASQUERADE in POSTROUTING. docker-proxy (the userland proxy) covers cases iptables cannot, such as the host's loopback address.
In-depth answer
sudo iptables -t nat -S DOCKER | grep 8080 sudo iptables -t nat -S POSTROUTING | grep MASQUERADE sudo conntrack -L -p tcp --dport 8080 2>/dev/null | head -3 ps -ef | grep docker-proxy | grep -v grep
-p 127.0.0.1:8080:80publishes on loopback only;-p 8080:80/udppublishes UDP;-Ppublishes all EXPOSEd ports on random host ports.EXPOSEis only documentation/metadata and publishes nothing by itself.- Because traffic goes through FORWARD rather than INPUT, ufw does not block it by default (A #31); write filtering rules in the DOCKER-USER chain.
- Engine 29 has an experimental nftables backend that works on the same principle (see the official docs).
Common follow-up questions
- Do containers need published ports to talk to each other? No, on the same network they reach container ports directly.
- What happens if you disable the userland proxy? Hairpin NAT is used instead, relying on kernel settings such as
route_localnet(see the official docs).
Bonus points
Draw the PREROUTING → FORWARD → bridge → veth path (Figure 3-1) and explain the role of conntrack.
Common wrong answers
"Docker runs a reverse proxy on the host that forwards all traffic" (docker-proxy is used only in some cases); "EXPOSE makes it reachable from outside".
Official Port publishing and mapping.
Q28. How do containers discover each other? How does the embedded DNS work?Mid
30-second answer
On user-defined networks the container's /etc/resolv.conf points to 127.0.0.11, the embedded DNS provided by dockerd (iptables redirects requests to 127.0.0.11:53 inside the container to dockerd's listening port). It resolves container names, Compose service names and network aliases on the same network, and forwards other names to the upstream DNS.
In-depth answer
docker network create app docker run -d --name db1 --network app --network-alias db postgres:17-alpine docker run -d --name db2 --network app --network-alias db postgres:17-alpine docker run --rm --network app busybox nslookup db # two IPs: round-robin DNS docker run --rm --network app busybox cat /etc/resolv.conf
- In Compose the service name is the DNS name; after scaling, the service name resolves to multiple IPs (Q36).
- Name resolution is scoped to the network: containers not on the same network cannot resolve each other (A #37).
- The default bridge does not provide this (A #29).
Common follow-up questions
- Can round-robin DNS do load balancing? Only coarsely; client-side caching causes imbalance; use a reverse proxy when needed.
- What about Swarm's VIP mode? The service name resolves to a virtual IP load-balanced by IPVS.
Bonus points
Mention how ndots and search domains affect resolving external names, and the analogy with CoreDNS in Kubernetes.
Common wrong answers
"Docker edits /etc/hosts to implement service discovery" (that was the old --link).
See Lesson 1 Module 5.
Q29. What is the difference between a volume, a bind mount and tmpfs, and when do you use each?Junior
30-second answer
Volume: managed by Docker (in /var/lib/docker/volumes by default), independent of the container lifecycle, can use drivers for remote storage — the first choice for persistence in production. Bind mount: mounts any host path into the container — good for mounting source code during development or config files. tmpfs: an in-memory filesystem that disappears when the container stops — good for temporary files and sensitive data.
In-depth answer
docker run -v pgdata:/var/lib/postgresql/data postgres:17-alpine docker run --mount type=bind,src=$PWD/nginx.conf,dst=/etc/nginx/nginx.conf,readonly nginx docker run --mount type=tmpfs,dst=/tmp,tmpfs-size=64m myapp
- An empty volume is populated with the image's content at the target directory on first mount; a bind mount hides it (A #40).
- Bind mounts depend on host paths and UIDs (A #41), so they are less portable, and slow when shared across the VM on Docker Desktop.
- The
--mountsyntax is more explicit than-v: if a bind source does not exist,--mounterrors out while-vsilently creates the directory.
Common follow-up questions
- Read-only mounts?
:roorreadonly. - Side effects of the VOLUME instruction? An anonymous volume is created on every run without a specified volume, and later RUN changes to that directory are discarded.
Bonus points
Point out that tmpfs counts toward the container's memory limit.
Common wrong answers
"Bind mounts and volumes are the same".
See Lesson 1 Module 6.
Q30. How do you back up and migrate Docker volumes? What about database volumes?Mid
30-second answer
The generic method: start a temporary container that mounts the volume (read-only) and a host directory, and tar it up; to restore, untar in reverse. For databases you must not copy the data files while running (they may be inconsistent); use logical backups (pg_dump, mysqldump) or stop writes/snapshot first.
In-depth answer
# back up and restore a file-based volume docker run --rm -v app_uploads:/data:ro -v "$PWD":/backup alpine tar czf /backup/uploads-$(date +%F).tgz -C /data . docker volume create app_uploads_new docker run --rm -v app_uploads_new:/data -v "$PWD":/backup alpine tar xzf /backup/uploads-2026-11-15.tgz -C /data # logical database backup docker exec db pg_dump -U postgres -Fc app > app-$(date +%F).dump
- Migrating to another host: transfer the tar file and restore it there, or use a volume driver with remote storage / cloud disk snapshots.
- Verify backups: restore them to a test environment regularly; encrypt backup files and store them off-site.
Common follow-up questions
- Why do Compose volume names have a prefix? The project-name prefix (A #37); backup scripts must use the actual volume name.
- Can Docker Desktop export volumes? Yes, it has graphical export/import (see the official docs).
Bonus points
Emphasize RPO/RTO and restore drills, not just "we can back up".
Common wrong answers
"Just cp /var/lib/docker/volumes/..." (permissions, consistency, storage driver differences).
Q31. How do containers on multiple hosts share data? What are volume drivers?Senior
30-second answer
A local volume lives on one host only. To share across hosts you can: ① mount NFS/CIFS with the built-in local driver; ② use third-party volume plugins or cloud storage (EFS, Azure Files); ③ preferably, have the application keep shared state in external services (S3/Blob object storage, managed databases) so containers stay stateless.
In-depth answer
docker volume create --driver local \ --opt type=nfs --opt o=addr=10.0.0.10,rw,nfsvers=4.1 --opt device=:/exports/shared shared-nfs docker run -v shared-nfs:/data alpine ls /data
volumes:
shared:
driver: local
driver_opts: { type: nfs, o: "addr=10.0.0.10,rw,nfsvers=4.1", device: ":/exports/shared" }
- Problems with shared filesystems: concurrent write locking, performance, UID mapping (root_squash), single points of failure.
- Do not put databases on NFS (locking and fsync semantics), unless the vendor explicitly supports it.
Common follow-up questions
- What is the Kubernetes equivalent? PersistentVolume / StorageClass / CSI drivers, with RWO/RWX access modes.
Bonus points
Advocate "stateless containers + managed stateful services", as in the object storage approach of Lesson 6.
Common wrong answers
"Put /var/lib/docker on NFS so all hosts share it".
Q32. Does depends_on in Compose guarantee a dependency is "ready"? How do you correctly wait for the database?Mid
30-second answer
The short form depends_on: [db] only guarantees start order (the db container starts first), not that db is accepting connections. To wait for readiness, define a healthcheck for db and use the long form condition: service_healthy; for one-off tasks (migrations) use service_completed_successfully. The application should still implement connection retries.
In-depth answer
services:
db:
image: postgres:17-alpine
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 10
start_period: 10s
migrate:
image: myapp:1.4
command: ["alembic","upgrade","head"]
depends_on: { db: { condition: service_healthy } }
api:
image: myapp:1.4
depends_on:
db: { condition: service_healthy, restart: true }
migrate: { condition: service_completed_successfully }
restart: true: when Compose restarts the dependency, the current service is restarted too.required: false: no error if the dependency does not exist or is not enabled (works with profiles).
Common follow-up questions
- How is this done in Kubernetes? There is no depends_on; use initContainers, readinessProbes and application retries.
- What if db restarts while running? Compose does not handle it automatically; the app must be able to reconnect.
Bonus points
Point out that wait-for-it scripts are the old approach and healthcheck conditions are more declarative.
Common wrong answers
"depends_on waits until the database is available".
Q33. What are Compose profiles for?Junior
30-second answer
Profiles let some services in a compose.yaml stay stopped by default; they start only when their profile is explicitly activated. Good for optional components such as debugging tools (adminer, mailhog), a monitoring stack, one-off tasks and test dependencies.
In-depth answer
services:
api: { image: myapp:1.4 } # no profiles: always starts
adminer:
image: adminer
profiles: ["debug"]
k6:
image: grafana/k6
profiles: ["perf"]
docker compose up -d # api only docker compose --profile debug up -d # api + adminer COMPOSE_PROFILES=debug,perf docker compose up -d docker compose run --rm k6 run /scripts/load.js # naming a service explicitly enables its profile automatically
Common follow-up questions
- Compared with multi-file overrides? Profiles suit "optional services"; multiple files suit "the same service configured differently per environment".
- What if a service without a profile depends on one with a profile? Activate both, or declare
required: falseon the dependency.
Bonus points
Give real groupings such as dev/perf/debug.
Common wrong answers
"Profiles separate production from development config" (multiple files suit that better).
Official Using profiles with Compose.
Q34. How are multiple Compose files merged? How do override, extends and include differ?Mid
30-second answer
-f a.yaml -f b.yaml merges in order, with later files overriding earlier ones; without -f, compose.yaml + compose.override.yaml are loaded automatically. extends lets one service inherit another service's configuration; include brings in another Compose project as a whole (with its own relative paths), which suits splitting up large applications.
In-depth answer
docker compose -f compose.yaml -f compose.prod.yaml config # inspect the merged result first docker compose -f compose.yaml -f compose.prod.yaml up -d
- Merge rules: scalars are overridden; lists such as
ports,exposeanddnsare merged;environmentandlabelsmerge by key;command/entrypointare replaced entirely. The!resetand!overridetags give precise control (see the official docs). - Paths are relative to the directory of the first Compose file; include keeps the included file's own relative paths.
include:
- ../shared/observability/compose.yaml
services:
api:
extends: { file: common.yaml, service: base-python }
Common follow-up questions
- How do you confirm the final configuration?
docker compose config(it also expands variables and validates syntax).
Bonus points
Stress the "base + per-environment override" layout, and print config in CI for review.
Common wrong answers
"The later file completely replaces the earlier one".
Official Use multiple Compose files; see also Lesson 2 Advanced Compose.
Q35. What is the precedence of environment variables in Compose? How do .env and env_file differ?Mid
30-second answer
Two different things: ① interpolation: ${VAR} in compose.yaml is filled from the shell environment and the project directory's .env file (shell wins); ② container environment: environment: and env_file: decide what the container sees. Container environment precedence, roughly from highest to lowest: docker compose run -e → environment (including interpolated values) → env_file → image ENV.
In-depth answer
TAG=1.4.2
LOG_LEVEL=info
services:
api:
image: myacr.azurecr.io/myapp:${TAG:?TAG is required} # error if unset
env_file: [./api.env] # variables in the file go straight into the container
environment:
LOG_LEVEL: ${LOG_LEVEL:-warn} # interpolation with a default
DB_HOST: db
docker compose config | grep -A3 environment # see the interpolated result docker compose --env-file .env.prod up -d # use a different interpolation file docker compose exec api env | sort
.envis used only for interpolation and does not enter containers automatically (unless you reference it in environment or point env_file at it).- Do not put secrets in compose.yaml or in a .env committed to Git; use Compose
secrets:(mounted as files under /run/secrets) or an external secrets service. - The official Environment variables precedence page is authoritative for the exact order.
Common follow-up questions
- Why didn't the container change after editing .env? You need
up -dto recreate the container; and .env is only used for interpolation. - How do you catch missing values?
${VAR:?message}.
Bonus points
Clearly separate the two phases, "interpolation" and "container environment" — most candidates blur them.
Common wrong answers
"Variables in .env are injected into every container automatically".
See Lesson 1 Module 7.
Q36. How do you scale a service with Compose, and how is load distributed?Mid
30-second answer
docker compose up -d --scale worker=3, or set deploy.replicas: 3 on the service. On the same network, the service name resolves to the IPs of all replicas (round-robin DNS). A service that publishes a fixed host port cannot be scaled directly (port conflict); put a reverse proxy (nginx, Traefik) in front or publish a port range.
In-depth answer
services:
web:
image: myapp:1.4
deploy: { replicas: 3 }
expose: ["8000"] # no host port published
proxy:
image: nginx:alpine
ports: ["80:80"]
volumes: ["./nginx.conf:/etc/nginx/nginx.conf:ro"] # upstream web:8000, with resolver 127.0.0.11
- nginx resolves upstreams once at startup by default, so after scaling you need
resolver 127.0.0.11 valid=10swith a variable, or a reload; Traefik discovers containers automatically via its Docker provider. - Compose is a single-host tool: no cross-host scheduling, autoscaling or self-healing onto other nodes.
Common follow-up questions
- Can container_name be used with scale? No, container names must be unique.
- How do you get real high availability? Multiple hosts + an orchestrator (Swarm/Kubernetes/managed services).
Bonus points
Point out that round-robin DNS plus client connection reuse leads to uneven load; long-lived connections need L7 load balancing.
Common wrong answers
"--scale load-balances automatically and works across hosts".
See Lesson 6 Gateway.
Q37. How do you get hot reload in development? Compose watch vs bind mounts — how do you choose?Junior
30-second answer
The traditional approach is bind-mounting the source directory plus the app's own hot reload; Compose watch (docker compose watch or up --watch) watches host files and, according to rules, runs sync (copy files into the container), rebuild (rebuild the image) or sync+restart. Watch avoids hiding dependency directories, UID problems and the performance cost of sharing files across a VM.
In-depth answer
services:
web:
build: .
develop:
watch:
- action: sync
path: ./src
target: /app/src
ignore: [node_modules/]
- action: rebuild
path: package.json
- action: sync+restart
path: ./config
target: /app/config
- Bind mounts are simple and bidirectional, but they hide node_modules (A #40) and are slow for large directories on Desktop.
- Watch is one-way (host → container) and needs tools such as
stat/mkdirin the image plus write permission on the target directory (see the official docs). - Dev Containers are another option: the whole development environment lives inside a container (Lesson 7).
Common follow-up questions
- Can you use watch in production? No, production images should be immutable.
Bonus points
Explain that changes to dependency files need a rebuild, not a sync.
Common wrong answers
"Deploy code with bind mounts in production too — updates are easier".
Official Use Compose Watch; see also Lesson 7 Dev Containers.
Q38. When does docker compose up recreate containers? How do up, restart and --force-recreate differ?Mid
30-second answer
up compares each service's configuration hash (image, environment variables, ports, volumes, etc.) with the label on the existing container, and recreates the container only when the config changed or the image was updated; otherwise it leaves it alone. restart only restarts the process and does not apply changes to compose.yaml. --force-recreate always recreates; --no-recreate never does.
In-depth answer
docker compose up -d # recreate only services whose config changed
docker compose pull && docker compose up -d # after pulling new images, services whose image changed are recreated
docker compose up -d --build api # rebuild and recreate as needed
docker compose up -d --no-deps api # handle only api, leave its dependencies alone
docker inspect -f '{{index .Config.Labels "com.docker.compose.config-hash"}}' $(docker compose ps -q api)
- Changing an interpolated value in .env also changes the config hash and triggers a recreate.
- Changes to the file contents of a bind mount do not change the config and do not trigger a recreate (restart, or have the app reload).
- A recreate means a brief interruption; zero downtime on a single host needs multiple replicas + a proxy replacing them one by one (Q47).
Common follow-up questions
- Difference between stop and down? stop keeps the containers; down removes containers and networks (add
-vto remove volumes).
Bonus points
Mentioning the config-hash label shows you have looked at how Compose works internally.
Common wrong answers
"After editing compose.yaml, running restart applies the change".
Scenario 7-1: Designing a single-host Compose deployment for a SaaS product
A small customer wants an on-premises deployment: Web, API, Worker, PostgreSQL and Redis on a single 8-core 32GB Linux server they provide, with one-command upgrades, backups and only port 443 exposed. Describe your design.
Key points of a reference answer
- Networks: frontend (proxy, web, api) and backend (api, worker, db, redis,
internal: true); only the proxy publishes 443, and the database publishes no ports. - Storage: named volumes for db and redis; named volumes or object storage for uploads; daily pg_dump + volume backups, stored off-site, with regular restore drills.
- Readiness: db/redis healthchecks; a one-off migrate service;
depends_onconditions for api. - Upgrades: images referenced by version tag + digest,
docker compose pull && up -d; automatic backup before upgrading; keep the previous compose file for rollback. - Operations: log rotation (
localdriver), resource limits,restart: unless-stopped,live-restore; health checks and alerting endpoints. - Security: non-root, read-only root + tmpfs, secrets mounted as files, automatic TLS certificate renewal (Traefik/Caddy).
Scenario 7-2: Several environments on one machine
A test server must run three identical application stacks at once: dev, qa and staging. How do you avoid conflicts between ports, networks and volumes?
Key points of a reference answer
- Use different project names:
docker compose -p shop-qa …, so networks and volumes get different prefixes automatically. - Ports via interpolation:
ports: ["${HTTP_PORT}:80"]with one--env-fileper environment; better still, a shared reverse proxy routes by domain and the environments publish no ports. - Do not use
container_name(it would conflict). - Make the address pools large enough to avoid subnet conflicts (A #32).
- Resource limits keep one environment from dragging down the whole machine.
Video tutorials (titles and channels verified via YouTube oEmbed)
For what is new in Compose v5, the official Compose release notes are authoritative; the videos above may be based on older versions.
Module 8 · Part B: Security, Production & Orchestration (Questions 39–50)
- Present a practical container security baseline and explain the threat each option defends against.
- Explain where image scanning, SBOMs, signing and secrets management fit in CI/CD.
- Answer open-ended questions on orchestrator choice, Compose to Kubernetes, zero-downtime releases and production incident troubleshooting.
Q39. How do you run containers with least privilege? List your security baseline.Mid
30-second answer
A non-root user (numeric UID), --cap-drop ALL adding back only the capabilities you need, --security-opt no-new-privileges, a read-only root filesystem + tmpfs, resource limits (memory/CPU/PIDs), no --privileged, no mounted docker.sock, keep the default seccomp and AppArmor/SELinux profiles, and publish only the ports you need.
In-depth answer
docker run -d --name api \ --user 10001:10001 --read-only --tmpfs /tmp:size=64m \ --cap-drop ALL --cap-add NET_BIND_SERVICE \ --security-opt no-new-privileges \ --memory 512m --cpus 1 --pids-limit 200 \ -p 127.0.0.1:8000:8000 myapp@sha256:…
| Option | What it defends against |
|---|---|
| Non-root | The attacker's privileges inside the container after a compromise; with user namespaces it also reduces the impact of an escape |
| cap-drop | Abuse of default capabilities such as NET_RAW (forging packets), CHOWN, SETUID |
| no-new-privileges | Privilege escalation via setuid binaries |
| read-only | Dropping malicious files, tampering with programs |
| pids-limit / memory | Fork bombs, resource exhaustion hurting neighbors |
Common follow-up questions
- Why is --privileged dangerous? It grants all capabilities, access to all devices and lifts seccomp/AppArmor restrictions — almost equivalent to host root.
- What is the Kubernetes equivalent? securityContext and the Pod Security Standards (restricted).
Bonus points
Explain that the default seccomp profile blocks many dangerous system calls; demonstrate NET_RAW with docker run --rm --cap-drop ALL alpine ping.
Common wrong answers
"Containers are already a secure sandbox; no extra configuration is needed".
See Lesson 2 Hardening; official Docker Engine security.
Q40. What are image vulnerability scanning and SBOMs, and how are they used in CI/CD?Mid
30-second answer
An SBOM (software bill of materials) lists every package and version in an image (SPDX/CycloneDX format); a vulnerability scan matches those packages against CVE databases. In CI: generate an SBOM attestation at build time, scan and gate on high-severity vulnerabilities that have a fix; keep scanning published images in the registry, because new CVEs appear every day.
In-depth answer
docker buildx build --sbom=true --provenance=mode=max -t REG/app:1.0 --push . docker scout cves REG/app:1.0 --only-severity critical,high docker scout recommendations REG/app:1.0 # recommends safer base images trivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed REG/app:1.0
- Keep gating pragmatic: block only "high severity + fix available" and record and track the rest, or teams will bypass the gate.
- The fundamental way to reduce vulnerabilities is minimal base images + regular rebuilds (Q20, Scenario 6-2).
- VEX statements can mark CVEs as "not affected" to reduce noise.
Common follow-up questions
- Does passing the scan mean it is secure? No: scans only cover known vulnerabilities in identified packages, not misconfigurations, business-logic flaws or self-compiled binaries.
Bonus points
Distinguish "build-time scanning (shift left)" from "continuous runtime scanning".
Common wrong answers
"Require zero CVEs before going live" (unrealistic).
Q41. How do you ensure the deployed image is exactly the one CI built? Talk about image signing and attestations.Senior
30-second answer
After building, CI signs the image digest (Sigstore cosign keyless signing with an OIDC identity, or Notation + certificates) and attaches provenance (build origin attestation) and an SBOM. The deployment side (a Kubernetes admission controller such as Kyverno/Ratify, or the deploy script) verifies the signature and signer identity before pulling, allowing only images from the designated repository and workflow.
In-depth answer
# in GitHub Actions (id-token: write), keyless signing of the digest cosign sign --yes REG/app@sha256:9f2c… # verify before deploying: the signer must be this repository's workflow on main cosign verify REG/app@sha256:9f2c… \ --certificate-identity-regexp 'https://github.com/org/app/.github/workflows/release.yml@refs/heads/main' \ --certificate-oidc-issuer https://token.actions.githubusercontent.com
- Signatures are bound to the digest, not the tag (tags are mutable, Q21).
- Signatures and attestations are stored in the registry as OCI artifacts (OCI 1.1 referrers).
- The old Docker Content Trust (Notary v1) is no longer recommended; follow the official docs for current options.
Common follow-up questions
- What does signing protect against? A tampered registry, malicious images pushed with leaked credentials, accidentally deploying images that did not come from CI.
- What is SLSA? A supply-chain security levels framework, with provenance as its core evidence.
Bonus points
Say "verify the identity, not just that a signature exists".
Common wrong answers
"Using a private registry is enough".
Q42. How should secrets (passwords, API keys) be managed for containers?Mid
30-second answer
Principle: secrets never go into images or Git, and preferably not into environment variables. At build time use BuildKit secret mounts; at runtime use the platform's secret mechanism to mount them as files (Compose/Swarm secrets → /run/secrets/, Kubernetes Secrets + external secret management); in the cloud use managed identities to access Key Vault/Secrets Manager directly, with rotation support.
In-depth answer
services:
api:
image: myapp:1.4
secrets: [db_password]
environment:
DB_PASSWORD_FILE: /run/secrets/db_password # the app reads the file
secrets:
db_password:
file: ./secrets/db_password.txt # never committed to Git
- Risks of environment variables: visible in
docker inspect, inherited by child processes, and may be printed by error logs or crash reports. - The official postgres/mysql images support the
*_FILEconvention. - Best in the cloud: managed identity/workload identity + Key Vault/Secrets Manager, so the app holds no long-lived credentials (Lessons 3 and 4).
Common follow-up questions
- Are Kubernetes Secrets secure? By default they are only base64-encoded in etcd; enable encryption at rest and RBAC, or use External Secrets/CSI drivers with an external vault.
- What if a secret leaks? Rotate it immediately, audit access logs, and purge it from images and Git history.
Bonus points
Emphasize rotation and short-lived credentials (OIDC).
Common wrong answers
"Put it in an ENV in the Dockerfile — the image is private, so it is fine".
Q43. How should container logs be collected? How do you build observability?Mid
30-second answer
Applications write structured (JSON) logs to stdout/stderr, and a log driver or a node-level collector (Fluent Bit, Vector, OpenTelemetry Collector) gathers them and ships them to a central platform. Metrics use Prometheus/cAdvisor or OpenTelemetry, and tracing uses OpenTelemetry. Configure rotation for the log driver.
In-depth answer
- Log drivers:
json-file(default, rotation must be configured),local(the recommended local driver),journald,syslog,fluentd,awslogs,gcplogsand more. With a remote driver,docker logscan still read a local cache via "dual logging" (see the official docs). - Delivery mode:
mode=non-blocking+max-buffer-sizekeeps a stuck log backend from blocking the application (at the cost of possibly losing logs). - The three pillars: logs (what happened), metrics (how many/how fast), traces (which services were involved), correlated by trace_id.
docker run --log-driver local --log-opt max-size=10m --log-opt max-file=5 myapp docker run --log-driver fluentd --log-opt fluentd-address=127.0.0.1:24224 --log-opt mode=non-blocking myapp
Common follow-up questions
- Why not let the app write log files? The files sit in the writable layer or a volume and need extra rotation and collection, which goes against the twelve-factor principles.
- What do you alert on? Restart counts, OOM events, health status, error rates and latency (RED/USE methods).
Bonus points
Tell the production incident about log rotation from A #42.
Common wrong answers
"Just look at docker logs" (no centralization; logs are lost when the host fails).
See Lesson 3 Cloud troubleshooting (Log Analytics), Lesson 4 CloudWatch; official Configure logging drivers.
Q44. How do you set container resource limits in production? What happens when memory and CPU limits are exceeded?Mid
30-second answer
Memory is an incompressible resource: exceeding --memory triggers an OOM kill inside the cgroup (137). CPU is compressible: exceeding --cpus gets the process throttled (slowed down), not killed. Also limit the number of PIDs and, where needed, disk IO and ulimits. Derive limits from load-test data and pair them with container-aware runtime settings.
In-depth answer
services:
api:
image: myapp:1.4
deploy:
resources:
limits: { cpus: "1.0", memory: 512M, pids: 200 }
reservations: { cpus: "0.25", memory: 256M }
ulimits: { nofile: { soft: 65536, hard: 65536 } }
- JVM:
-XX:MaxRAMPercentage=75; Node:--max-old-space-size; Go: GOMEMLIMIT and GOMAXPROCS. - Setting
--memory-swapequal to--memorydisables swap;--memory-reservationis a soft limit. - Kubernetes: requests are used for scheduling and limits are the ceiling; the QoS class affects eviction order under node memory pressure.
Common follow-up questions
- Are CPU limits always good? They can cause throttling and tail latency (A #24); latency-sensitive services may set only requests/shares.
- How do you choose limit values? Load tests + the P99 peak from production monitoring, plus headroom.
Bonus points
Name observation tools such as memory.events and cpu.stat.
Common wrong answers
"Set no limits and let containers use what they want — best performance" (noisy neighbors, one container can take down the host).
Q45. How do you choose between single-host Docker/Compose, Docker Swarm and Kubernetes?Mid
30-second answer
Choose by scale and needs: single-host Compose suits a few services where a single point of failure is acceptable (internal tools, on-prem deliveries); Swarm is built into Docker and simple to configure, suitable for small multi-host setups, but its ecosystem and community investment are limited; Kubernetes is the de facto standard for multiple teams, large scale and a rich ecosystem (autoscaling, service mesh, GitOps), but it is operationally complex; if you do not want to run it yourself, pick a managed service (AKS/EKS/GKE, Container Apps, ECS/Fargate, Cloud Run).
In-depth answer
| Compose | Swarm | Kubernetes | |
|---|---|---|---|
| Multi-host | No | Yes | Yes |
| Self-healing / scheduling | Restart policies only | Yes | Yes, the most complete |
| Scaling | Manual | Manual replica count | HPA/VPA/KEDA/cluster autoscaling |
| Learning/operations cost | Low | Low–medium | High |
| Ecosystem | — | Small | Huge (CNCF) |
Common follow-up questions
- Why didn't your team use Kubernetes? Answer honestly about the cost vs team-size trade-off.
- Is Swarm still maintained? Swarm mode is still shipped in Docker Engine (see the official docs), but few new projects choose it.
Bonus points
Give decision criteria (number of services, number of teams, SLA, compliance, cloud vendor) rather than "Kubernetes is the best".
Common wrong answers
"Kubernetes has replaced Docker" (Kubernetes orchestrates containers; Docker builds and runs them — different layers).
See Lesson 3 Platform choice, Lesson 4 ECS, Kubernetes in 8 hours.
Q46. How do you migrate a Compose application to Kubernetes? How do the concepts map?Mid
30-second answer
service → Deployment (stateless) or StatefulSet (stateful) + Service; ports → Service/Ingress (or Gateway API); environment → ConfigMap; secrets → Secret; volumes → PVC; healthcheck → liveness/readiness/startup probes; depends_on → no direct equivalent, use initContainers and application retries; deploy.resources → requests/limits. Kompose can generate a first draft, but it needs human review.
In-depth answer
- The image does not change: the same OCI image runs directly on Kubernetes.
- What you need to add: probes, resource requests, securityContext (runAsNonRoot needs a numeric UID), PodDisruptionBudget, HPA, NetworkPolicy.
- Local development can keep using Compose; manage deployment manifests with Helm/Kustomize and deliver them with GitOps (Argo CD/Flux).
kompose convert -f compose.yaml -o k8s/ # for reference only kubectl apply -k k8s/overlays/staging
Common follow-up questions
- The Compose latest image cannot be pulled in kind? latest defaults to imagePullPolicy Always (Lesson 3).
- Do you migrate the database too? Prefer a managed database; if you must self-host, use an Operator and StatefulSets.
Bonus points
Point out that Kubernetes ignores HEALTHCHECK, so it must be rewritten as probes.
Common wrong answers
"One Compose service maps to one Pod" (bare Pods have no self-healing or rolling updates).
Q47. How do you achieve zero-downtime releases with Docker? How do blue-green and rolling differ?Senior
30-second answer
The key to zero downtime: the new version receives traffic only once it is ready, and the old version shuts down gracefully only after its traffic has been drained. On single-host Compose you can use a reverse proxy + two sets of replicas (blue-green) or replace replicas one by one (rolling); orchestrators have built-in rolling updates (Kubernetes Deployments, Swarm update_config, Container Apps revision traffic splitting). Prerequisites: the app handles SIGTERM, has readiness checks, and database migrations are backward compatible.
In-depth answer
- Blue-green: two complete environments, switch the routing; fast rollback, double the resources.
- Rolling: replace batch by batch; small resource footprint, but old and new versions coexist for a while.
- Canary: shift a percentage of traffic, watch the metrics, then go to 100%.
- Database: use the expand/contract pattern so old and new versions both work (Lesson 6).
# Swarm-style rolling update (start the new task before stopping the old one) docker service update --image REG/app:1.5 --update-order start-first --update-parallelism 1 --update-delay 10s app # single-host Compose blue-green: start the green project → health checks pass → switch the proxy upstream and reload → stop blue docker compose -p app-green up -d && ./wait-healthy.sh app-green && ./switch-proxy.sh green && docker compose -p app-blue down
Common follow-up questions
- What about long-lived connections (WebSocket)? Extend the grace period, drain connections, have clients reconnect.
- How do you roll back? Switch back to the previous image digest and traffic; migrations must be reversible or backward compatible.
Bonus points
Mention coordinating the load balancer deregistration delay with SIGTERM handling (drain traffic first, then stop the process), and automated metric-based release decisions.
Common wrong answers
"docker compose up -d is zero downtime" (recreating a single replica causes an interruption).
See Lesson 2 Graceful shutdown, Lesson 3 Revisions and traffic, Lesson 6 Migrations.
Q48. How is Docker used in CI/CD? How do DinD and mounting docker.sock differ?Senior
30-second answer
A typical pipeline: checkout → build (buildx + remote cache) → test (unit/integration tests in containers) → scan → generate SBOM/sign → push (short-lived OIDC credentials) → deploy (by digest). There are three ways to build images inside a CI container: mounting the host's docker.sock (fast, shared cache, but equals host root and jobs affect each other), DinD (a privileged docker:dind container running its own dockerd — better isolation but needs privileged), and daemonless/remote builders (rootless BuildKit, the Kubernetes driver, cloud build services).
In-depth answer
permissions: { id-token: write, contents: read, packages: write }
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
- uses: docker/build-push-action@v6
with:
push: true
tags: ghcr.io/org/app:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
sbom: true
provenance: mode=max
Use the latest released version of each action.
- Integration tests:
docker compose -f compose.test.yaml up --abort-on-container-exit --exit-code-from tests, or Testcontainers. - The same image (same digest) is promoted from testing all the way to production; never rebuild per environment.
Common follow-up questions
- Why is mounting docker.sock risky? CI jobs can start privileged containers and mount the host root directory (A #46).
- How do you speed it up? Remote caches, native multi-arch runners, parallel builds with bake.
Bonus points
"Build once, promote everywhere" and password-less pushes with OIDC.
Common wrong answers
"Build a separate image per environment to inject configuration" (configuration should be injected at runtime).
Q49. A container fails in production. How do you troubleshoot it?Senior
30-second answer
Stop the bleeding first, then find the root cause: confirm the blast radius → roll back or scale out to restore service → preserve evidence (logs, inspect output, core dumps) → work through the layers: state and exit code → logs → configuration and recent changes → resources (OOM, throttling, disk) → network (DNS, ports, firewall) → dependent services → go deeper inside the container/namespaces (nsenter, tcpdump, strace) → postmortem and prevention.
In-depth answer
docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'
docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}}' api
docker logs --since 30m -t api | tail -100
docker events --since 1h --filter type=container --filter event=die --filter event=oom
docker stats --no-stream; df -h /var/lib/docker; docker system df
sudo nsenter -t $(docker inspect -f '{{.State.Pid}}' api) -n tcpdump -i eth0 -c 50 port 5432
- "What changed recently" is often the fastest lead: image digest, configuration, infrastructure, dependent services.
- Use the layered approach from Part A: build / runtime / network / storage and daemon.
- Afterwards: a timeline, the root cause (5 Whys), action items (alerts, tests, automated safeguards), in a blameless postmortem.
Common follow-up questions
- Tell me about a real incident you handled. Use STAR: situation, actions, result, improvements; back it with data (MTTR, number of users affected).
Bonus points
Mention balancing "restore first, diagnose later" with "preserve the evidence", and the mechanisms that keep the problem from recurring.
Common wrong answers
"Restart it and see; if it works, done" (no root cause, no prevention).
See Lesson 7 Deep troubleshooting and Part A of this lesson.
Q50. How do container escapes happen? What can you do to strengthen isolation?Senior
30-second answer
The main escape routes: ① dangerous configuration (--privileged, mounting docker.sock or the host root, --pid=host, excessive capabilities); ② kernel vulnerabilities (containers share the kernel); ③ runtime vulnerabilities (such as the historical runc CVE-2019-5736). Hardening: eliminate dangerous configuration, patch the kernel and runtime promptly, seccomp/AppArmor/SELinux, user namespaces or rootless, and sandboxed runtimes (gVisor, Kata Containers) for untrusted workloads.
In-depth answer
- Defense in depth: trusted images (signing, scanning) → least-privilege runtime (Q39) → kernel-level LSM and seccomp → user namespaces so container root is not host root → sandboxed runtimes with a separate/user-space kernel → host hardening and runtime detection (Falco etc.).
- A container with docker.sock mounted needs only
docker run -v /:/host --privilegedto control the host.
docker info --format '{{.SecurityOptions}}'
docker run --rm --runtime=runsc alpine dmesg # after installing and registering gVisor, shows output from the user-space kernel
docker run --rm --security-opt seccomp=./custom.json myapp
Common follow-up questions
- How do you detect suspicious behavior at runtime? Runtime security tools based on system calls/eBPF detect unexpected shells and sensitive file access.
- What about multi-tenant platforms? Isolate tenants with microVMs/sandboxed runtimes rather than relying on namespaces alone.
Bonus points
Cite specific CVEs and describe the process for "promptly updating runc/containerd/the kernel".
Common wrong answers
"If you are not root in the container, escape is impossible" (kernel vulnerabilities and misconfiguration can still lead to escapes).
See Lesson 2 Hardening; official Seccomp security profiles.
Scenario 8-1: A security audit finds 40% of containers running as root
The company runs 200 services on Docker hosts and Kubernetes. The audit requires remediation within a quarter. How do you drive it without disrupting the business?
Key points of a reference answer
- Inventory: automatically collect User, capabilities, privileged and mounts for every container (docker inspect / kube-bench / a policy engine in audit mode).
- Prioritize: handle high-risk items such as privileged, mounted docker.sock and hostPath first, then ordinary root.
- Provide a "paved road": standard base images with a built-in non-root user (numeric UID), docs and example Dockerfiles, and fixes for common issues (A #22, #41, #43).
- Policy: Kubernetes Pod Security Admission in warn/audit first, then enforce; on Docker hosts, check Dockerfiles in CI (USER instruction).
- Exception process: components that truly need privileges (CNI, monitoring agents) are registered, approved and monitored more closely.
- Metrics: a weekly compliance-rate dashboard.
Scenario 8-2: 3 a.m., widespread 502s on the order service
Alerts show a 40% error rate on the order API, and the last release was yesterday afternoon. As the on-call engineer, what do you do?
Key points of a reference answer
- Confirm the blast radius and when it started; check dashboards: error rate, latency, restart counts, resources.
- Check container state: are they restarting (exit code, OOMKilled), are they unhealthy?
- If it is release-related (new digest), roll back first to restore service; if not, scale out/shift traffic to stop the bleeding.
- Work through the layers: errors in the logs (connection pool exhausted? database timeouts? DNS failures?), is the disk full (logs), are upstream dependencies failing, conntrack table/SNAT port exhaustion (Lesson 7).
- Preserve the evidence and write a postmortem after recovery: timeline, root cause, improvements (alert thresholds, capacity, chaos testing).
Scenario 8-3: Choosing an orchestration platform
A 30-person startup with 15 microservices, all on AWS, and only 2 operations engineers asks whether they should adopt Kubernetes.
Key points of a reference answer
- Consider operations capacity: two people running self-managed Kubernetes is risky; prefer managed options: ECS on Fargate (no nodes to manage) or EKS + managed node groups / Auto Mode.
- If the team already has Kubernetes experience, or needs the Helm ecosystem or multi-cloud portability, EKS is an option; otherwise ECS is simpler (Lesson 4).
- Either way, container images, CI/CD, observability and IaC are reusable; keep apps twelve-factor to ease future migration.
- Give decision criteria and migration triggers (number of services, number of teams, specific requirements).
Video tutorials (titles and channels verified via YouTube oEmbed)
No verified video dedicated to container escapes and signature verification was found. Script: walk through the five layers of Figure 8-1 from the outside in, giving a real "what happens when this layer is missing" example for each (a mounted docker.sock, runc CVE-2019-5736, a token leaked through ARG).
Problem Cheat Sheet + Interview Flashcards
A · 50 production problems at a glance
Type a keyword to filter (e.g. 137, dns, x509). Click a number for the details in its module.
B · 50 interview flashcards
Recall the answer, then expand to compare with the key point; for details, see "Question Details" in the module.
General command card
Status and logs
docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' C
docker logs --tail 100 -t C
docker events --since 1h --filter event=die --filter event=oom
journalctl -u docker --since -10mResources and disk
docker stats --no-stream docker system df -v docker buildx du docker exec C cat /sys/fs/cgroup/memory.events /sys/fs/cgroup/cpu.stat df -h /var/lib/docker; df -i /var/lib/docker
Networking
docker port C
sudo nsenter -t $(docker inspect -f '{{.State.Pid}}' C) -n ss -lntp
docker network inspect NET
sudo iptables -t nat -S DOCKER; sudo iptables -S DOCKER-USER
docker run --rm --network NET busybox nslookup NAMEBuilds, images and registries
docker build --progress=plain . 2>&1 | tail -60 docker build --check . docker history --no-trunc IMG docker buildx imagetools inspect REG/IMG:TAG sudo dockerd --validate --config-file=/etc/docker/daemon.json
Final Drills + Mock Interview
1. Mixed failure drills
Each scenario combines several Part A problems. Write down your first command and diagnosis before expanding the answer.
Scenario 1: after a new release the container restarts every 40 seconds; docker ps shows Up 38 seconds (health: starting) → Restarting
$ docker inspect -f 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}}' api
exit=137 oom=true restarts=23
$ docker inspect -f '{{.HostConfig.Memory}}' api
268435456
$ docker logs --tail 3 api
Picked up JAVA_TOOL_OPTIONS: -Xmx512m
Answer: The JVM heap is set to 512MB while the container limit is only 256MB, so it OOMs shortly after starting (#17), and the restart policy creates a loop (#14). Fix: remove the hard-coded -Xmx, use -XX:MaxRAMPercentage=75, raise memory to 768MB based on load-test results, and alert on OOM events.
Scenario 2: an image developed on a Mac is pushed to ACR and the Container Apps revision fails; running it on a local x86 test machine shows just one line of error
$ docker run --rm myacr.azurecr.io/api:2.1 exec /app/start.sh: exec format error $ docker buildx imagetools inspect myacr.azurecr.io/api:2.1 | grep Platform Platform: linux/arm64
Answer: Architecture mismatch (#5). Build linux/amd64,linux/arm64 consistently in CI and assert the platforms with imagetools after pushing; also check that start.sh uses LF line endings (if the error is no such file or directory, it is #21).
Scenario 3: after ops added a ufw rule, the security team still finds Redis 6379 open from the internet
$ sudo ufw status | grep 6379
6379 DENY Anywhere
$ docker ps --format '{{.Names}} {{.Ports}}' | grep redis
redis 0.0.0.0:6379->6379/tcp
Answer: Ports published by Docker go through the FORWARD chain after nat DNAT and bypass ufw (#31). Fix: do not publish Redis at all, keep it on an internal network (Compose internal: true); if it must be published, use 127.0.0.1:6379:6379; put filtering rules in DOCKER-USER; back it up with cloud security groups; enable authentication on Redis.
Scenario 4: on Monday morning every service fails to write and dockerd responds very slowly
$ df -h /var/lib/docker /dev/sdb1 100G 100G 0 100% $ docker system df Build Cache 1120 0 41.2GB 41.2GB $ sudo du -sh /var/lib/docker/containers/*/*-json.log | sort -h | tail -1 38G /var/lib/docker/containers/7c…/7c…-json.log
Answer: Logs not rotated (#42) + accumulated build cache (#9). Emergency: truncate -s 0 the huge log and docker builder prune --filter until=72h; long term: set the local log driver or max-size in daemon.json and recreate the containers; builder GC; disk usage alerts. Do not rm the log file.
Scenario 5: after connecting to the corporate VPN, the API in a developer's local Compose project times out on every third-party call, but reaching db works
$ docker compose exec api getent hosts api.partner.com (no output, returns after about 5 seconds) $ docker compose exec api getent hosts db 172.18.0.3 db $ ip route | grep 172.18 172.18.0.0/16 dev br-41d… ← the VPN also pushes a 172.18.0.0/16 route
Answer: Two problems stacked: external DNS forwarding fails (#30, the VPN changed the host DNS) and the Docker subnet clashes with the VPN subnet (#32). Fix: configure dns and default-address-pools (avoiding corporate ranges) in daemon.json, restart Docker and compose down/up to recreate the networks. If HTTPS handshakes hang, also check the MTU (#33).
Scenario 6: CI suddenly fails across the board, although the same code built fine last week
#4 [internal] load metadata for docker.io/library/python:3.13 #4 ERROR: failed to authorize: ... 429 Too Many Requests --- Another batch of jobs: #9 [4/7] RUN pip install -r requirements.txt #9 ERROR: ... error: subprocess-exited-with-error ... gcc: not found
Answer: ① Docker Hub rate limiting (#12): log in from CI + pull-through cache/internal registry. ② Base image tag drift (#11): python:3.13 now points to a new distro release or variant, so prebuilt wheels no longer apply and a compiler is needed. Fix: pin -slim-bookworm@sha256:…, lock dependencies, and let Renovate upgrade automatically through CI.
Scenario 7: after hardening (non-root + read-only root), both nginx and file uploads break
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system) api: PermissionError: [Errno 13] Permission denied: '/data/uploads/a.png' $ ls -ln ./data drwxr-xr-x 2 0 0 4096 Nov 15 03:00 uploads
Answer: A read-only root needs tmpfs mounts for its write paths (#43); the bind-mounted host directory belongs to root, so container UID 10001 cannot write to it (#41, #22). Fix: mount tmpfs at /var/cache/nginx and /var/run for nginx; switch the upload directory to a named volume or chown 10001:10001; use docker diff to find every write path.
Scenario 8: every release causes about 10 seconds of 502s, even with two replicas
$ docker image inspect -f '{{json .Config.Cmd}}' api:3.0
["/bin/sh","-c","node server.js"]
$ time docker stop shop-api-1
real 0m10.2s
$ docker inspect -f '{{.State.ExitCode}}' shop-api-1
137
Answer: The shell form makes sh PID 1, which does not forward SIGTERM (#19), so the process is SIGKILLed and in-flight requests are cut off; on top of that, single-host Compose up -d replaces both replicas at once. Fix: exec form + graceful SIGTERM shutdown; a reverse proxy + one-by-one replacement (or Swarm start-first); stop containers only after the proxy health check has drained them (interview question Q47).
2. Full mock interview (10 random questions out of 50)
Each question has a 2-minute countdown: answer out loud first (you can jot notes in the text box), then reveal the reference answer and rate yourself "Got it / Partial / Missed". At the end you see the round score and the cumulative mastery per module. Self-ratings are saved in this browser.
3. Final quiz (12 questions)
Sources and Versions
Official documentation sources
| Topic | What this lesson relies on | Source (docs.docker.com, accessed 2026-11-15) |
|---|---|---|
| Build context and .dockerignore | COPY is relative to the context root; .dockerignore rules | Build context |
| Build cache | Cache invalidation cascades; cache mounts; external cache backends | Docker build cache · Cache storage backends |
| Build secrets | RUN --mount=type=secret / ssh | Build secrets |
| Build checks | docker build --check; rules such as SecretsUsedInArgOrEnv | Build checks |
| Multi-platform | buildx, QEMU, cross-compilation, image store limitations | Multi-platform builds |
| Build garbage collection | builder prune; daemon.json builder.gc | Build garbage collection |
| Docker Hub limits | Rate limits per account/IP; how to query the remaining quota | Usage and limits |
| docker run exit codes | Meaning of 125 / 126 / 127; --init | docker container run |
| Resource limits | --memory, --cpus, OOM behavior | Resource constraints |
| Restart policies | Back-off doubling from 100ms; reset after 10 seconds of running | Start containers automatically |
| HEALTHCHECK | Options and states; start-interval | Dockerfile reference |
| Networking and DNS | Default bridge vs user-defined networks; embedded DNS | Networking overview · Bridge driver |
| Firewalls | Incompatibility with ufw; the DOCKER-USER chain; nftables (experimental) | Packet filtering and firewalls |
| Port publishing | Publish addresses, docker-proxy | Port publishing and mapping |
| IPv6 | --ipv6 networks, daemon configuration | Use IPv6 networking |
| Proxies | daemon.json proxies; CLI config.json proxies | Daemon proxy · CLI proxy |
| Host networking | Optional on Desktop 4.34+ | Host network driver |
| Storage | volume / bind / tmpfs behavior; empty volumes copy image content | Volumes · Bind mounts · tmpfs |
| Logging | json-file does not rotate by default; local driver; daemon settings affect only new containers | Configure logging drivers |
| Daemon | dockerd --validate; flag vs config-file conflicts; live-restore | Troubleshoot the daemon · Live restore |
| Socket permissions / rootless | docker group equals root; rootless limitations | Post-installation · Rootless mode |
| Private registry certificates | /etc/docker/certs.d; insecure-registries | Verify repository client with certificates |
| containerd image store | The two stores cannot see each other; new Engine 29 installs default to the containerd store | containerd image store · Engine release notes |
| Compose | depends_on conditions, profiles, multiple files, variable precedence, watch | Startup order · Profiles · Multiple files · Env precedence · Watch |
| Security | capabilities, seccomp, AppArmor | Docker Engine security · Seccomp |
Video verification
All videos were verified on 2026-11-15 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) for title and channel name; oEmbed returns neither duration nor publication date, so these are not shown. Verified: Fireship "Docker in 100 Seconds" (Gjnup-PuquQ), "100+ Docker Concepts you Need to Know" (rIrNIzy6U_g), "Learn Docker in 7 Easy Steps - Full Beginner's Tutorial" (gAkwW2tuIqE); TechWorld with Nana "Docker Tutorial for Beginners [FULL COURSE in 3 Hours]" (3c-iBn73dDE), "Docker Crash Course for Absolute Beginners [NEW]" (pg19Z8LL06w), "Docker Volumes explained in 6 minutes" (p2PH_YPCsis), "Ultimate Docker Compose Tutorial" (SXwC9fSwct8), "Kubernetes Crash Course for Absolute Beginners [NEW]" (s_o8dwzRlu4), "GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker" (R8_veQiYBjI); NetworkChuck "Docker networking is CRAZY!! (you NEED to learn it)" (bKFMS5C4CG0), "you need to learn Docker RIGHT NOW!! // Docker Containers 101" (eGz9DS-aIeY), "Docker Compose will BLOW your MIND!! (a tutorial)" (DM65_JyGxCo); Christian Lempa "Docker Networking Tutorial, ALL Network Types explained!" (5grbXvV_DSk); freeCodeCamp.org "Docker Tutorial for Beginners - A Full DevOps Course on How to Run Applications in Containers" (fqMOX6JJhGo); Programming with Mosh "Docker Compose Tutorial" (HG6yIjZapSA); IBM Technology "Containerization Explained" (0qotVMX-J5s), "Kubernetes vs. Docker: It's Not an Either/Or Question" (2vMEQ5zs1ko); Nick Janetakis "Virtual Machines vs Docker Containers - Dive Into Docker" (TvnZTi_gaNc). No verified video dedicated to Docker production troubleshooting or Docker interview questions was found; the relevant tabs provide scripts/storyboards instead.
About the audio
The Audio tabs use the browser's built-in Web Speech API and upload no data. An English (en-US) voice must be installed on the system; without one, read the scripts directly or use them as input for another TTS tool.
Known limitations
- Error messages follow the common wording of Docker Engine 28/29; wording differs between versions (and between the classic builder and BuildKit), as noted in the entries.
- All "sample output" is illustrative; IDs, sizes, times and IPs will differ in your environment. The labs were written from the official docs and were not run on every version.
- Details marked "see the official docs" include: exact Docker Hub quotas, the embedded DNS upstream fallback behavior, the nftables backend, Desktop host networking limitations,
RUN --mount=type=secret,env=,rewrite-timestamp, Compose!reset/!override, live-restore across version upgrades, rootless limitations and more. - Docker Desktop subscription terms and the features of commercial images (Hardened Images etc.) are defined by Docker's official pages.
- Mock interview self-ratings are stored only in this browser's localStorage and are lost if you clear site data.