Docker & Containers
Master container fundamentals that power modern platforms. Build lean, secure images. Orchestrate multi-service apps. Enforce security at every layer from development to production.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components & Concepts · WSL Hands-On Lab · Real-World Project — Startup → Enterprise · Troubleshooting Guide · Deep Dive: Image Optimization & Security Patterns · Predict the Result: Exit Codes and Memory Limits
- Why it matters
- A required lesson for DevOps Engineer, Cloud Engineer, DevSecOps Engineer, Container/Kubernetes Engineer, Release / CI-CD Engineer, MLOps / LLMOps Engineer. Recommended for SRE, Platform Engineer, FinOps / Cloud Optimization, Observability Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: WSL Hands-On Lab: Run curl -fsSL https://get.docker.com | sh. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 7 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 04.1
Docker sits on top of containerd and runc. Containers isolate processes using Linux namespaces and control resources via cgroups v2. Images are built from read-only layers using OverlayFS union mounts. The Docker daemon manages the lifecycle on the host.
pid,net,mnt,uts,ipc,user] CG[cgroups v2] OV[OverlayFS layers] end App --> Daemon DockerCLI --> Daemon Daemon --> containerd --> runc runc --> NS runc --> CG runc --> OV
Image Layers & Caching
Each instruction in a Dockerfile creates a layer. Docker reuses layers when possible. Order instructions from least-changing (base image, dependencies) to most-changing (source code) for best cache performance.
Networking Models
bridge (default isolated), host (shares host network), overlay (Swarm / Kubernetes), macvlan (direct L2). Always create custom bridge networks for multi-container apps instead of relying on default bridge.
Choose user-defined bridge or host networking
Assumptions: Docker Engine 26.1+ with Linux containers on a single host. Desktop host mode requires Docker Desktop 4.34+ and opt-in settings; its TCP/UDP layer-4 support differs from native Linux. This is a decision exercise, not a benchmark.
| Criterion | User-defined bridge | Host |
|---|---|---|
| Isolation | Private container network namespace and IP. | Shares host network; no separate container IP. |
| Ports | Publish only needed ports; bind to 127.0.0.1 for local access. Reuse internal ports with different host ports. | Publishing is ignored; host port conflicts must be managed. |
| Discovery | Service names and aliases resolve within the shared user-defined network. | No bridge service-name discovery; configure reachable addresses explicitly. |
| Performance | Bridge/publishing may add overhead; measure the workload. | Avoids NAT and per-port userland proxy. No universal percentage or latency guarantee. |
| Decision | Choose for API + database isolation and service DNS. | Consider when many ports or measured network overhead justify reduced isolation. |
Check your choice: An API needs database DNS and two copies listening internally on 3000: choose bridge. A Linux service needs thousands of ports: evaluate host mode after checking port conflicts and exposure. Neither mode supplies multi-host discovery. Recover from a host port conflict by choosing a free application port or returning to bridge with explicit publishing; verify with docker inspect --format '{{.HostConfig.NetworkMode}}' api and application connectivity checks.
Official references: Bridge driver; Host driver and Desktop limitations.
Core Components & Concepts 04.2
| Concept | Key Primitives | Production Notes |
|---|---|---|
| Dockerfile | FROM, RUN, COPY --chown, CMD, ENTRYPOINT, USER, HEALTHCHECK | Multi-stage + non-root + read-only rootfs |
| Compose | services, volumes, networks, profiles, depends_on | Use compose v2, healthchecks, restart policies |
| Volumes | Named volumes vs bind mounts | Prefer named volumes in prod; backup with docker cp |
| Networking | docker network create mynet | Use DNS names between services inside custom networks |
| Security | Trivy, docker scout, cosign, --cap-drop, read-only | Scan in pipeline; sign images; run rootless |
docker buildx with --cache-from and --cache-to in CI for massive speed gains on subsequent builds.WSL Hands-On Lab 04.3
Full End-to-End: Install → Build → Optimize → Scan → Compose → Rootless
$ curl -fsSL https://get.docker.com | sh $ sudo usermod -aG docker $USER && newgrp docker $ docker run hello-world
Optimized Multi-Stage Dockerfile (Node example)
# syntax=docker/dockerfile:1
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force
FROM node:20-alpine AS runner
RUN apk add --no-cache dumb-init
ENV NODE_ENV=production
USER node
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node . .
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s CMD node -e "require('http').get('http://localhost:3000/health', r => process.exit(r.statusCode === 200 ? 0 : 1))"
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "server.js"]$ docker build -t myapi:prod . $ docker images | grep myapi $ # Install trivy $ curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin $ trivy image --severity HIGH,CRITICAL myapi:prod
docker-compose.yml — 3-tier teaching template
services:
api:
build: .
environment:
DB_HOST: db
DB_USER: app
DB_NAME: appdb
DB_PASSWORD_FILE: /run/secrets/db_password
secrets: [db_password]
depends_on: { db: { condition: service_healthy } }
networks: [appnet]
read_only: true
security_opt: ["no-new-privileges:true"]
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
POSTGRES_DB: appdb
secrets: [db_password]
volumes: [pgdata:/var/lib/postgresql/data]
healthcheck: { test: ["CMD-SHELL", "pg_isready -U app"], interval: 10s }
networks: [appnet]
redis:
image: redis:7-alpine
networks: [appnet]
nginx:
image: nginx:alpine
ports: ["80:80"]
volumes: ["./nginx.conf:/etc/nginx/conf.d/default.conf:ro"]
depends_on: [api]
networks: [appnet]
secrets:
db_password:
file: ./secrets/db_password.txt
volumes: { pgdata: {} }
networks: { appnet: { driver: bridge } }Local file-backed secrets
Assumptions: Compose v2.20+, Linux containers, PostgreSQL 16 official image, and the preceding Node 20 teaching app. The API must implement DB_PASSWORD_FILE; Compose does not interpret arbitrary _FILE variables. The fragment below supplies connection options to your existing PostgreSQL client (dependency and server.js required).
const fs = require('node:fs');
const dbOptions = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
database: process.env.DB_NAME,
password: fs.readFileSync(process.env.DB_PASSWORD_FILE, 'utf8').trimEnd()
};
// Pass dbOptions to your installed PostgreSQL client; never log it.# Disposable Ubuntu/WSL project on Linux filesystem, not /mnt/c
# Stop if secrets already exists; never replace an existing secret
test ! -e secrets || exit 1
umask 077
mkdir secrets
chmod 700 secrets
printf '%s' 'SIMULATED-NOT-A-CREDENTIAL' > secrets/db_password.txt
chmod 600 secrets/db_password.txt
printf '%s\n' 'secrets/' >> .gitignore
printf '%s\n' 'secrets/' >> .dockerignore
stat -c '%a %u:%g' secrets secrets/db_password.txt
docker compose config --quietModes 0700/0600 restrict directory access and file reads to the owner; Windows-mounted files may not honor Linux modes. Standalone Compose binds the plaintext file at /run/secrets/db_password, rather than providing Swarm's encrypted secret store or automatic rotation. Root and daemon administrators can still read it. File-backed secret uid, gid and mode remapping is not implemented by Compose.
Non-root reader check: The preceding image uses UID 1000 (node). On native Linux, 0600 must be owned by the runtime reader; do not solve denial with 0644. If your host UID differs, use a dedicated protected staging file owned by the chosen runtime UID or adapt the image user to your host UID. Verify with docker compose run --rm --no-deps api node -e "require('fs').accessSync('/run/secrets/db_password', require('fs').constants.R_OK)" when a local daemon is available; this prints no secret. PostgreSQL's entrypoint supports POSTGRES_PASSWORD_FILE at initialization. Changing the file does not change an existing database password: coordinate database-side rotation and app recreation. Do not delete existing pgdata as recovery.
The template still requires your API, lockfile and nginx.conf. After a disposable exercise, use docker compose down (keep volumes), then remove only the inert secret file. Live mount permissions and database initialization were not run for this buildout.
Official references: Compose secrets; File-backed permission limits; PostgreSQL image initialization; Node 20 file reader.
$ docker compose up -d --build $ docker compose ps $ docker compose logs --tail 100 --since 10m --timestamps api $ # Rootless experiment (requires Docker 20.10+) $ dockerd-rootless-setuptool.sh install
Resource metrics and bounded logs
Assumptions: Engine 26.1+, Compose v2.20+, an existing local API container, and a logging driver that supports reads. No daemon is started here. Select the Compose container ID instead of assuming its name is api.
# Inspect an existing service, without streaming
api_id=$(docker compose ps -q api)
test -n "$api_id" || exit 1
docker stats --no-stream --format 'table {{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.NetIO}} {{.BlockIO}}' "$api_id"
docker logs --tail 100 --since 10m --timestamps "$api_id"
docker inspect --format 'oom={{.State.OOMKilled}} exit={{.State.ExitCode}} memory={{.HostConfig.Memory}}' "$api_id"--no-stream gives a snapshot; CPU is not a latency measurement and can exceed 100% across cores. On Linux, the CLI subtracts cache from memory usage. Network/block I/O totals require repeated snapshots to infer rates. Combining a time window and a line limit bounds retained history; omit --follow for a finite inspection.
Simulated diagnosis exercise, not recorded output: A hypothetical API has 98.4% CPU and 480 MiB / 512 MiB memory; the bounded five-minute window shows repeated database timeouts. Decide whether to restart or investigate dependency/retry behavior first. High CPU plus timeouts does not prove recursion or OOM. Check database health, retry frequency, traffic and OOMKilled; compare another snapshot after traffic falls. Fix excessive retry concurrency/backoff and the dependency before restarting a disposable service. Resource caps contain damage but can increase throttling and do not cure a leak. If an authorized local test uses docker compose restart api, verify health, repeated resource snapshots and reduced timeout frequency afterward. Restart does not apply changed Compose limits; recreate only the affected disposable service after reviewing docker compose config. Roll back the changed retry/limit configuration if latency worsens. No measured result is claimed here.
Official references: stats semantics; Bounded logs; Compose service settings.
Bound retention and ship logs
Engine 26.1+, standalone Compose v2.20+: this per-service fragment limits json-file retention. It is an alternative to syslog below, not a second simultaneous driver.
services:
api:
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"The default json-file driver does not rotate unless configured. Options are strings; retention is approximately three 10 MB files per container, not a host-wide quota. Set equivalent defaults in daemon.json only during an authorized maintenance change: daemon defaults require restart and affect newly created containers. Do not edit or truncate Docker's managed log files. Check disk capacity and the selected configuration with docker inspect --format '{{json .HostConfig.LogConfig}}' "$api_id". Applying a service change requires recreation; preserve volumes and restore the prior fragment if needed.
Official references: json-file rotation and lifecycle.
Minimal shipping alternative: Assume an already configured local syslog receiver accepts TCP on the Docker daemon host at 127.0.0.1:514. This is configuration-only; no receiver is launched. On Desktop, daemon loopback belongs to its VM, so a desktop-host receiver needs a reachable address. Plain TCP supplies no encryption; keep this local or use an authenticated TLS receiver for remote traffic.
services:
api:
logging:
driver: syslog
options:
syslog-address: "tcp://127.0.0.1:514"
syslog-format: rfc5424
tag: "docker/{{.Name}}"Verify and recover: Review the merged Compose configuration, confirm receiver reachability, then emit a unique non-sensitive application log marker in an authorized disposable test. Search the receiver for that marker and container tag; inspect LogConfig and use bounded docker logs if the local dual-logging cache is enabled. A reachable socket alone does not prove delivery. An unavailable receiver can prevent container startup; restore json-file and recreate the disposable service if that happens. Receiver retention is separate from the bounded local cache; forwarding and restart recovery remain uncaptured.
Official references: syslog driver; Remote-driver local cache.
Lab Checklist — Track Progress
- Install Docker Engine in WSL2 and validate with hello-world
- Write naive Dockerfile and measure final image size
- Rewrite using multi-stage, alpine, non-root, HEALTHCHECK
- Scan final image with Trivy, document HIGH/CRITICAL fixes
- Create full docker-compose.yml for 3-tier app with healthchecks
- Run compose stack and validate inter-service networking
- Complete Play with Docker + Killercoda Docker fundamentals labs
Real-World Project — Startup → Enterprise 04.4
Containerize Express API for a single service
One Dockerfile, .dockerignore, basic CI build. Push to GHCR. Deploy manually or with simple compose on a VM.
Multi-service Compose with postgres, redis, nginx reverse proxy
Environment-specific compose overrides, named volumes, custom bridge networks, healthchecks, rolling updates via compose.
Rootless containers + read-only filesystems + distroless + OCI compliance
Run daemon rootless, drop all capabilities except NET_BIND_SERVICE, use chainguard or distroless images, sign every image with cosign, enforce image signing in admission controller.
Troubleshooting Guide 04.5
Container exits immediately or won't start
docker logs <id> docker inspect <id> | jq '.[0].State' docker run --rm -it --entrypoint sh myimage
Image size is huge (800MB+)
Use dive tool. Combine RUN commands. Use alpine or distroless. Remove apt/yum caches in same layer.
Cannot connect between containers
Confirm they are on same custom network. Use service names for DNS. Check exposed vs published ports.
Volume permission denied errors
Match container UID/GID to host folder owner or use init container chown. Prefer named volumes managed by Docker.
Container keeps restarting (CrashLoop)
Read logs. Increase restart policy grace. Add liveness/readiness probes. Check resource limits causing OOM.
Isolated permission drill: diagnose, recover and clean up
Simulated exercise; commands not executed here. Assumptions: Engine 26.1+, preloaded alpine:3.20, Ubuntu/WSL Linux filesystem, rootful local daemon without user-namespace remapping, and Bash with GNU mktemp/stat. Rootless/remapped UIDs and SELinux require different analysis; this drill does not change host ownership or security settings.
Predict why UID 10001 cannot create a file in a host-user-owned 0700 directory. The temporary path is unique; no fixed container name, privileged mode, root chown or recursive deletion is used.
#!/usr/bin/env bash
set -eu
scratch=$(mktemp -d /tmp/da-docker-perm.XXXXXX)
cleanup() {
rm -f -- "$scratch/probe"
rmdir -- "$scratch"
}
trap cleanup EXIT
host_uid=$(id -u)
host_gid=$(id -g)
if [ "$host_uid" -eq 10001 ] || [ "$host_uid" -eq 0 ]; then
echo 'Use a non-root host user whose UID differs from 10001.'
exit 1
fi
chmod 700 "$scratch"
stat -c '%u:%g %a' "$scratch"
# --pull never prevents downloads; --network none isolates the drill
set +e
docker run --rm --pull never --network none --read-only --cap-drop ALL \
--user 10001:10001 --mount "type=bind,src=$scratch,dst=/data" \
alpine:3.20 sh -c 'id; touch /data/probe'
status=$?
set -e
test "$status" -eq 1
test ! -e "$scratch/probe"
# Resolve by running with the directory owner's UID, without chmod 777
docker run --rm --pull never --network none --read-only --cap-drop ALL \
--user "$host_uid:$host_gid" --mount "type=bind,src=$scratch,dst=/data" \
alpine:3.20 sh -c 'touch /data/probe; test -f /data/probe'
test -f "$scratch/probe"
stat -c '%u:%g %a' "$scratch/probe"
cleanup
trap - EXIT
test ! -e "$scratch"Expected, simulated: the first touch reports permission denied and exits 1; the retry exits 0 and creates a host-UID-owned probe. Mode 0700 permits only the owner to traverse/write the directory. Confirm actual exit status, owner and file presence; exit 125 instead indicates a Docker setup/image error, not the intended DAC failure. Stop and verify the local image/context before retrying. If the successful write fails, inspect host UID, mount source and namespace mapping rather than loosening permissions.
A named volume still needs correct ownership: a fresh empty volume is not automatically writable by every non-root UID. Initialize only a dedicated volume for the application UID or use image-created target ownership, then verify with the real runtime user. Never chown an existing production volume blindly. The EXIT trap removes only the probe and empty scratch directory; rmdir fails visibly if unexpected files remain. All containers are foreground and auto-removed. Live DAC output and named-volume initialization remain unrecorded.
Official references: Bind mount behavior; Named volume initialization; docker run options.
30-Day Learning Roadmap 04.6
- Every instruction & cache rules
- Multi-stage patterns
- Small base images
- Non-root users
- Compose file deep dive
- Custom networks
- Volumes & secrets
- Healthchecks & depends
- Trivy + Grype + dockle
- Rootless + capabilities
- Distroless images
- Image signing
- GHCR / ECR / Harbor
- Buildx + cache export
- Cosign + SBOM
- Registry policies
Deep Dive: Image Optimization & Security Patterns 04.7
Layer Optimization Techniques
Combine RUN commands. Use .dockerignore aggressively. Copy only what is needed. Use build args for environment-specific layers. Leverage BuildKit cache mounts for npm/yarn/pip.
# syntax=docker/dockerfile:1
RUN --mount=type=cache,target=/root/.npm npm ciSecurity Hardening Checklist
- Non-root user in final stage
- Read-only root filesystem
- Drop all capabilities except required
- No package managers in prod image
- Signed images + SBOM
Predict the Result: Exit Codes and Memory Limits 04.8
Recorded from a real run of scripts/recordings/docker.sh; every output below is pasted from scripts/recordings/docker.out. Cover the output, predict it, then compare.
Environment: Docker Engine 26.1.5 on Linux, image alpine:3.20.
# The container exits with 3. What does the shell see? $ docker run --rm alpine:3.20 sh -c 'exit 3'; echo $? 3 # A process tries to use far more than its 32 MiB limit $ docker run --rm --memory 32m --memory-swap 32m alpine:3.20 sh -c 'head -c 200m /dev/zero | tail > /dev/null'; echo $? Killed 137 # The limit as Docker stores it, in bytes $ docker run -d --name mem-demo --memory 64m alpine:3.20 sleep 300 > /dev/null && docker inspect -f '{{.HostConfig.Memory}} {{.State.Status}}' mem-demo 67108864 running # PID 1 is sleep, which does not handle SIGTERM. Stop with a 2 second grace period $ docker stop -t 2 mem-demo > /dev/null && docker inspect -f '{{.State.ExitCode}}' mem-demo 137
Exit 137 is 128 + 9: the process was killed with SIGKILL, here by the kernel OOM killer and then by docker stop after the grace period. Seeing 137 on every deploy means the app ignores SIGTERM and loses in-flight work; give it a signal handler or an init such as docker run --init.