Skip to content
Derar Sattouf

A Docker Course for Working Developers (2026)

Updated DevOps & cloud

A Docker Course for Working Developers (2026)

This is a single-page Docker course for working developers: people who ship Next.js, Laravel, Python, Node, Go or Rust apps and want to stop saying "works on my machine." It starts with what a container actually is, a process with a restricted view of the system, and it spends real time on the parts most tutorials skip: sharing images and environments, Dev Containers, security hardening, production operations and a troubleshooting playbook.

A container is a normal Linux process, isolated with namespaces, limited with cgroups and given a layered filesystem from an image. It isn't a lightweight VM, because it shares the host kernel. An image is an immutable stack of layers plus metadata (OCI format); a container is a running or stopped instance of one, with a thin writable layer on top.

Write Dockerfiles for the cache: copy the dependency manifests first, install, then copy the source. Use multi-stage builds, a non-root user and .dockerignore, and reach for BuildKit's cache mounts, secret mounts, heredocs and multi-platform builds with buildx. Persist data in volumes rather than the container filesystem, and keep bind mounts for dev. Use user-defined networks, where containers find each other by service name, publish only the ports you need, and bind to 127.0.0.1 when a port is just for local use.

Compose (compose.yaml) covers multi-service dev and small production setups: docker compose watch for the dev loop, healthchecks plus depends_on: condition: service_healthy for startup order. To share images, push to a registry (Docker Hub, GHCR, ECR and so on), tag with semver plus the git SHA, deploy by digest, build multi-arch with buildx, and sign and attest in CI. Dev Containers (devcontainer.json) give the whole team, CI and AI agents the same environment.

Hardening means non-root, --cap-drop=ALL, --read-only, no-new-privileges, no secrets in layers, no casual mounting of /var/run/docker.sock, and scanning your images. In production, watch PID 1 and signals (init: true), healthchecks, log rotation and resource limits. Compose on a VPS is a legitimate production choice; graduate to Kubernetes when you need multi-node scheduling.

Each module has learning objectives, labs with exact commands and expected output, a list of common mistakes and a recap checklist.

Docker moves fast, so versions are stated where they matter, and where a detail is likely to drift the text says to check the current docs. As of late 2026 the baseline is Docker Engine 29.x (the containerd image store is the default for new installs), Docker Compose v2 (the docker compose plugin; the Compose Specification file is conventionally named compose.yaml), BuildKit as the default builder, and Docker Desktop 4.x. The commands target those versions. If something behaves differently on your machine, check docker version and the official docs.

Course map

ModuleTopicCore skill
1Mental model and installationExplain containers, images, runtimes; install Docker
2CLI fundamentalsRun, inspect, debug, clean up containers
3Images and base imagesChoose a base (Alpine, slim, distroless, scratch)
4Dockerfile masteryWrite fast, small, cache-friendly production Dockerfiles
5StorageVolumes, bind mounts, tmpfs, backups, permissions
6NetworkingBridge, host, overlay, DNS, debugging
7Docker ComposeMulti-service stacks, watch, profiles, secrets
8Sharing images and environmentsRegistries, tags, multi-arch, save/load, contexts, CI
9Dev ContainersReproducible dev environments for teams and agents
10SecurityHarden images and runtime, rootless, scanning
11Production and opsLogging, signals, deploy to a VPS, CI/CD
12Troubleshooting playbookDiagnose the 15 most common failures
13Modern and AI featuresModel Runner, MCP, agent stacks, sandboxes
14Cheat sheets and capstonePut it all together

Module 1: The mental model and installation

Learning objectives

  • Explain what a container is in terms of namespaces, cgroups and union filesystems.
  • Distinguish images from containers, layers from snapshots, registries from repositories.
  • Name the components of the Docker stack: CLI, dockerd, containerd, runc.
  • Install Docker on macOS, Linux and Windows and verify it works.

Containers versus virtual machines

A virtual machine virtualises hardware: a hypervisor runs a full guest operating system with its own kernel. A container virtualises the operating system view: every container on a host shares the host kernel, but each sees its own process tree, network stack, mounts and hostname.

PropertyVirtual machineContainer
Isolation boundaryHypervisor, separate kernelKernel namespaces and cgroups, shared kernel
StartupSeconds to minutesMilliseconds to seconds
Typical sizeGBsMBs to hundreds of MBs
OverheadGuest OS memory and CPUNear-native
Security boundaryStrongWeaker (kernel is shared); needs hardening
Best forDifferent OSes, strong tenant isolationPackaging and running app processes consistently

Consequence for macOS and Windows: Linux containers need a Linux kernel. Docker Desktop therefore runs a lightweight Linux VM (Apple Virtualization framework or QEMU on macOS, WSL 2 or Hyper-V on Windows) and your containers run inside it. On Linux, containers run directly on the host kernel.

The three kernel features behind containers

Namespaces give a process its own view of a resource.

NamespaceIsolates
pidProcess IDs (the container's first process is PID 1)
netNetwork interfaces, routing tables, ports
mntMount points and filesystem view
utsHostname and domain name
ipcSystem V IPC and POSIX message queues
userUID/GID mappings (used by rootless mode and userns-remap)
cgroupThe view of the cgroup hierarchy

Control groups (cgroups) limit and account for resources: CPU, memory, block I/O, number of processes. When you pass --memory=512m, Docker writes a cgroup limit, and the kernel OOM-kills the process if it exceeds it.

Union / overlay filesystems stack read-only layers and a writable layer into one view. Docker uses overlay2 on Linux (or the containerd overlayfs snapshotter when the containerd image store is enabled). Files in lower layers are shared between containers; writes go to the top layer using copy-on-write.

You can see namespaces yourself:

docker run --rm alpine ps
PID   USER     TIME  COMMAND
    1 root      0:00 ps

Inside the container the process thinks it is PID 1. On the host, the same process has a different PID.

Images, layers, containers

  • An image is a read-only template: a manifest, a config (entrypoint, env, user, exposed ports) and an ordered list of layers (compressed tar archives of filesystem diffs), all addressed by SHA-256 digests.
  • A container is an image plus a thin writable layer plus runtime configuration (namespaces, cgroup limits, network, mounts). Remove the container and its writable layer is gone.
  • A registry stores images (Docker Hub, GHCR, ECR...). A repository is a named collection of tags, for example library/nginx. A tag is a mutable pointer (nginx:1.27); a digest (nginx@sha256:...) is an immutable content address.

Layers are content-addressed, so two images that share a base share those layer bytes on disk and on the wire.

The OCI standards

The Open Container Initiative defines three specs that make Docker images portable across tools (Podman, containerd, Kubernetes, BuildKit):

SpecDefines
Image specImage manifest, config, layer format
Runtime specHow a runtime starts a container from a filesystem bundle (config.json)
Distribution specThe HTTP API registries implement for push and pull

A "Docker image" today is an OCI image. Anything that speaks OCI can run it.

Docker architecture

 docker CLI  --(REST API over unix socket /var/run/docker.sock)-->  dockerd
                                                                      |
                                                                  containerd   (image store, snapshots, container lifecycle)
                                                                      |
                                                              containerd-shim
                                                                      |
                                                                    runc       (creates namespaces + cgroups, execs the process)
                                                                      |
                                                              your container process
ComponentRole
docker CLIClient. Talks to the daemon API. Also does docker compose, docker buildx as plugins.
dockerdThe Docker daemon: API, networks, volumes, build orchestration, plugins
containerdHigh-level runtime: pulls images, manages snapshots, supervises containers. Also used directly by Kubernetes.
runcLow-level OCI runtime that actually creates the container
BuildKitThe build engine behind docker build and docker buildx build

Important consequence: access to the Docker socket equals root on the host (module 10). The CLI is just an API client; DOCKER_HOST or docker context point it at any daemon, local or remote.

Installing Docker

macOS. Install Docker Desktop (Apple silicon and Intel builds exist). Alternatives that provide a Docker-compatible engine:

ToolNotes
Docker DesktopOfficial GUI, includes Engine, Compose, buildx, Scout, Model Runner, Kubernetes toggle. Licensing terms apply to larger companies; check the current subscription terms.
OrbStackFast, light macOS-native alternative with a Docker-compatible engine
ColimaOpen source, CLI-driven, Lima VM running Docker or containerd
PodmanDaemonless, rootless-first engine with a mostly compatible CLI (podman), supports Compose via podman compose
# Colima example (Homebrew)
brew install colima docker docker-compose
colima start --cpu 4 --memory 8

Windows. Install Docker Desktop with the WSL 2 backend. Keep your project files inside the WSL filesystem (~/code), not under /mnt/c, for much faster bind mounts and file watching.

Linux. Install Docker Engine from Docker's official apt/dnf repository (not the distro's old docker.io package unless you accept its version). Verify the exact repository commands on the current install page for your distro: the install docs.

# Ubuntu / Debian: convenience script (fine for dev machines, review it first)
curl -fsSL https://get.docker.com -o get-docker.sh
less get-docker.sh
sudo sh get-docker.sh

# Run docker without sudo (membership of the docker group is root-equivalent!)
sudo usermod -aG docker "$USER"
newgrp docker

Check the install:

docker version
docker compose version
docker buildx version
docker run --rm hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.

Lab 1: See the kernel features

# 1. Start a container and look at its isolated process view
docker run -d --name lab1 --memory 128m --cpus 0.5 nginx:1.27-alpine

# 2. Processes inside vs host
docker top lab1

# 3. Resource limits recorded by Docker
docker inspect lab1 --format '{{.HostConfig.Memory}} bytes, {{.HostConfig.NanoCpus}} nanoCPUs'

# 4. Clean up
docker rm -f lab1
134217728 bytes, 500000000 nanoCPUs

Common mistakes in module 1

  • Treating containers like VMs: SSH-ing in, installing things by hand, expecting state to persist.
  • Adding your user to the docker group without realising it is equivalent to root.
  • On Windows, keeping code on the Windows filesystem and mounting it into WSL containers (slow).
  • Expecting Linux containers to run natively on macOS/Windows with no VM.
  • Assuming latest means newest or stable. It is just a tag.

Recap checklist

  • I can explain namespaces, cgroups and overlay layers in one sentence each.
  • I know the difference between an image, a container, a tag and a digest.
  • I can name CLI, dockerd, containerd, runc and BuildKit and their jobs.
  • docker run --rm hello-world works on my machine.

Module 2: CLI fundamentals

Learning objectives

  • Run containers interactively and detached; publish ports; set env vars; name and label them.
  • Inspect, log, exec into and copy files from containers.
  • Apply restart policies and resource limits.
  • Clean up safely and measure disk usage.

Command structure

Modern Docker uses docker <object> <verb>. The old short forms still work.

ModernShortMeaning
docker container rundocker runCreate and start a container
docker container lsdocker psList running containers (-a for all)
docker image lsdocker imagesList images
docker container rmdocker rmRemove container
docker image rmdocker rmiRemove image

docker run in depth

docker run [OPTIONS] IMAGE [COMMAND] [ARGS...]
FlagPurposeExample
-dDetached (background)docker run -d nginx
-itInteractive TTYdocker run -it ubuntu:24.04 bash
--rmDelete container when it exitsdocker run --rm alpine echo hi
--nameName the container--name web
-p host:containerPublish a port-p 8080:80, -p 127.0.0.1:8080:80
-PPublish all EXPOSEd ports to random host ports
-e KEY=valueEnvironment variable-e NODE_ENV=production
--env-fileEnv vars from a file--env-file .env
-v / --mountMount a volume or bind mountmodule 5
--networkAttach to a networkmodule 6
--restartRestart policy--restart unless-stopped
--memory, --cpusResource limits--memory 512m --cpus 1.5
--userRun as a user--user 1000:1000
--workdir, -wWorking directory
--entrypointOverride the image entrypoint
--labelAdd metadata--label app=blog
--initRun a tiny init as PID 1 (reaps zombies, forwards signals)
--read-onlyRead-only root filesystemmodule 10
--platformChoose architecture--platform linux/amd64

Always publish with an explicit bind address when a port is only for local use. -p 8080:80 binds to 0.0.0.0 and can bypass host firewalls such as ufw because Docker manipulates iptables/nftables itself. Prefer -p 127.0.0.1:8080:80.

Lifecycle

created --start--> running --stop--> exited --rm--> (gone)
                     |  ^
                  pause unpause
docker create --name web nginx:1.27-alpine   # create without starting
docker start web
docker stop web          # SIGTERM, then SIGKILL after 10s (change with -t)
docker restart web
docker kill web          # SIGKILL immediately
docker rm web            # remove (add -f to force-remove a running one)

Observing containers

docker ps                      # running
docker ps -a                   # all, including exited
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
docker logs -f --tail 100 web  # follow last 100 lines
docker logs --since 10m web
docker inspect web             # full JSON
docker inspect -f '{{.State.Health.Status}}' web
docker stats --no-stream       # CPU, memory, network, I/O snapshot
docker top web                 # processes
docker port web                # published ports
docker events                  # live daemon events

Getting inside

docker exec -it web sh                      # shell in a running container
docker exec web nginx -t                    # one-off command
docker exec -u root -it web sh              # as a specific user
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
docker cp ./index.html web:/usr/share/nginx/html/index.html

docker exec starts a new process in the existing container's namespaces; docker attach connects to the main process's stdin/stdout. Prefer exec.

Restart policies

PolicyBehaviour
no (default)Never restart
on-failure[:max]Restart only on non-zero exit, optional max retries
alwaysAlways restart, including after daemon restart
unless-stoppedLike always, but not if you stopped it manually

For servers, unless-stopped is the usual choice. Restart policies do not replace healthchecks: a hung process that never exits will not be restarted by Docker alone (Swarm and orchestrators act on health; plain Docker only marks it unhealthy).

Resource limits

docker run -d --name api \
  --memory 512m --memory-swap 512m \
  --cpus 1.0 \
  --pids-limit 200 \
  my-api:1.0.0
  • --memory is a hard cap; exceeding it triggers an OOM kill (check docker inspect -f '{{.State.OOMKilled}}' api).
  • --memory-swap equal to --memory disables swap for the container.
  • --cpus 1.0 limits CPU time to one core's worth.
  • --pids-limit protects against fork bombs.

Cleanup and disk usage

docker system df            # what is using space
docker system df -v         # per-image and per-volume detail
docker container prune      # remove stopped containers
docker image prune          # remove dangling images
docker image prune -a       # remove all images not used by a container
docker volume prune         # remove unused local volumes (data loss risk!)
docker builder prune        # remove build cache
docker system prune         # stopped containers, unused networks, dangling images, build cache
docker system prune -a --volumes   # aggressive; deletes unused volumes too

Use --filter "until=168h" to prune only things older than a week. Never run docker volume prune or --volumes on a machine whose database lives in an unattached named volume.

Lab 2: Run, inspect, break and fix

# 1. Detached nginx on a local-only port, with a label
docker run -d --name web -p 127.0.0.1:8080:80 --label course=docker nginx:1.27-alpine

# 2. Verify
curl -sI http://127.0.0.1:8080 | head -n 1

# 3. Logs and stats
docker logs web --tail 3
docker stats --no-stream web

# 4. Exec and edit the page
docker exec web sh -c 'echo "<h1>Hello Docker</h1>" > /usr/share/nginx/html/index.html'
curl -s http://127.0.0.1:8080

# 5. Filter by label, then clean up
docker ps --filter label=course=docker
docker rm -f web
HTTP/1.1 200 OK
<h1>Hello Docker</h1>

Now prove the writable layer is ephemeral: run the same container again, and curl the page. The default nginx page is back, because your edit lived in the deleted container's layer.

Common mistakes in module 2

  • Running databases without a volume and losing data on docker rm.
  • Publishing database ports (-p 5432:5432) on 0.0.0.0 on a public server.
  • Using docker run and forgetting --rm for throwaway containers, filling the disk with exited containers.
  • Using docker attach and killing the container with Ctrl+C.
  • Running docker system prune -a --volumes casually.

Recap checklist

  • I can run detached/interactive containers with ports, env and names.
  • I can read logs, exec in, copy files and inspect state.
  • I know the four restart policies and the memory/CPU flags.
  • I know what each prune command deletes.

Module 3: Images and base images

Learning objectives

  • Read image names, tags and digests; pull and pin images.
  • Inspect layers and understand what makes images large.
  • Choose between Alpine, Debian slim, Ubuntu, distroless, scratch and hardened minimal images.

Anatomy of an image reference

registry.example.com:5000 / team / api : 1.4.2 @sha256:3b1f...
└──── registry ─────────┘   └repo path┘ └tag┘   └── digest ──┘
PartDefault if omitted
Registrydocker.io (Docker Hub)
Namespacelibrary/ for official images (nginx is docker.io/library/nginx)
Taglatest
Digestnone (tag is resolved at pull time)

Tags are mutable, digests are not. node:22-alpine today and in three months are different images. For reproducible production deploys, pin the digest (usually via your CI output, or by Renovate/Dependabot updating it):

FROM node:22-alpine@sha256:REPLACE_WITH_REAL_DIGEST
docker pull node:22-alpine
docker image inspect node:22-alpine --format '{{index .RepoDigests 0}}'
docker buildx imagetools inspect node:22-alpine      # shows manifest list per platform

Inspecting layers and size

docker image ls
docker history node:22-alpine
docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' my-api:1.0.0
docker image inspect my-api:1.0.0 --format '{{json .RootFS.Layers}}'

dive gives an interactive per-layer file view and an efficiency score:

dive my-api:1.0.0
# or without installing (mounts the Docker socket: see module 10 for the risk):
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest my-api:1.0.0

What contributes to image size:

SourceFix
Large base imageSlim, distroless or Alpine base
Build tools left in the final image (compilers, git)Multi-stage builds
Dev dependenciesnpm ci --omit=dev, pip install --no-cache-dir, composer install --no-dev
Package manager caches (/var/lib/apt/lists, ~/.cache)Clean in the same RUN, or use cache mounts
Copying the whole context (.git, node_modules, tests).dockerignore, targeted COPY
chown -R or chmod -R in a separate layerUse COPY --chown, --chmod
Files deleted in a later layerThey still exist in the earlier layer; delete in the same layer

Deleting a file in a later layer does not shrink the image: layers are additive.

Base images in depth

The base image decides your size, your CVE count, your debuggability and your compatibility. The main families:

Alpine Linux

Alpine is a tiny distro (a base image is roughly 5 MB) built on musl libc and busybox instead of glibc and GNU coreutils, with the apk package manager.

Strengths: very small, fast pulls, small attack surface, huge package set.

Pitfalls to know before choosing it:

PitfallWhat happensMitigation
musl vs glibcPrebuilt binaries and wheels built for glibc (manylinux) may not run or need compiling from sourceUse -slim Debian for Python/Node native modules, or install gcompat (partial)
Native Node modulesnode-gyp builds need python3 make g++; prebuilt binaries for musl may be missing for some packagesCheck the library supports musl; install build deps in a build stage
Python wheelsMany wheels are manylinux only; pip compiles from source on Alpine (slow, big). Some packages publish musllinux wheels, check per packageUse python:3.x-slim
DNS behaviourmusl's resolver historically differed from glibc (search domains, parallel queries, TCP fallback); this has caused odd resolution problems in some orchestrated setupsTest DNS under your orchestrator; keep Alpine current; use slim if you hit odd resolution issues
Locale and i18nmusl has minimal locale support; LC_*, iconv and collation differUse Debian if you need full locales
PerformanceSome libc functions and the allocator behave differently and can be slower for certain workloadsBenchmark your workload
Busybox toolsls, sed, grep, date, ps differ from GNU versions; scripts using GNU flags breakInstall coreutils or bash, or write POSIX sh
DebuggingMissing bash, curl, straceapk add --no-cache bash curl in debug images only

When Alpine is a good fit: statically linked Go binaries, Node apps with pure JavaScript dependencies, simple Python apps without compiled wheels, sidecars, nginx.

When to avoid it: scientific Python (numpy, pandas, torch), apps relying on glibc-only binaries, Java with native libraries, anything where reproducible performance matters more than megabytes.

FROM alpine:3.22
RUN apk add --no-cache ca-certificates tzdata

(Check the current Alpine release number on Docker Hub before copying.)

Debian slim

debian:bookworm-slim (and python:3.13-slim, node:22-slim) use glibc and apt but strip docs, man pages and extras. Typically 70 to 250 MB depending on the language runtime. It is the best default for most application images: wide compatibility, predictable behaviour, easy debugging, and security patches from Debian. (Debian "trixie" is the newer release; verify which suites the official images currently default to.)

Ubuntu

ubuntu:24.04 is larger than Debian slim. Choose it when you need packages or tooling parity with Ubuntu servers, or vendor software certified on Ubuntu. For application runtime images, Debian slim is usually enough.

Distroless

Google's gcr.io/distroless/* images contain only your runtime (static, base, cc, nodejs, python3, java) plus certificates, timezone data and a nonroot user. No shell, no package manager. Strengths: tiny attack surface, few CVEs, hard for attackers to pivot. Weaknesses: you cannot docker exec ... sh; debug with the :debug tag variants (which include busybox) or docker debug (Docker Desktop and subscription features; verify availability).

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
ENTRYPOINT ["/server"]

scratch

FROM scratch is an empty image. It works for fully static binaries (Go with CGO_ENABLED=0, Rust with a musl target). You must copy in CA certificates and timezone data yourself if you need them, and a numeric USER 65532:65532 works without any /etc/passwd entry.

Minimal / hardened images (Chainguard, Wolfi, Docker Hardened Images)

Chainguard Images (built on the Wolfi "undistro", glibc based, apk format) and Docker Hardened Images (DHI) are rebuilt continuously to keep known CVEs near zero, ship SBOMs and provenance, and often include a -dev variant with a shell for build stages. Docker announced in December 2025 that its Hardened Images catalog is free and open source under Apache 2.0 (DHI Community, with a paid Enterprise tier); pulling typically requires registry login. Chainguard's free tier is limited to certain tags, with paid pinned versions. Both policies change, so verify current terms and image names on the vendors' sites.

Comparison and decision table

BaseApprox. sizelibcShellCompatibilityCVE surfaceDebuggabilityUse for
alpine~5 MBmuslbusybox ashMediumLowGood (apk)Go, simple Node, sidecars
debian:bookworm-slim~30-75 MBglibcbashHighMediumExcellentDefault for most apps
ubuntu:24.04~30-80 MBglibcbashHighMediumExcellentUbuntu parity, vendor software
distroless2-50 MBglibc (base/cc) or none (static)none (use :debug)Medium-HighVery lowHardProduction runtime stage
scratch0nonenoneStatic binaries onlyMinimalHardestGo and Rust static binaries
Hardened / Wolfi~5-60 MBglibc-dev variants onlyHighNear zeroMediumSecurity-sensitive production

Sizes are indicative; check docker image ls for real numbers.

How to choose, in order:

  1. Static binary (Go, Rust)? distroless/static or scratch.
  2. Compiled dependencies or ML/data science? Debian slim.
  3. Pure-JS Node or simple Python, size matters, and tests pass? Alpine is fine; otherwise slim.
  4. Strict security or compliance posture? Distroless or a hardened image, with a debug variant for build stages.
  5. Not sure? *-slim. You can optimise later with measurements.

Lab 3: Measure the difference

docker pull node:22
docker pull node:22-slim
docker pull node:22-alpine
docker image ls --format 'table {{.Repository}}:{{.Tag}}\t{{.Size}}' | grep '^node'
node:22          1.1GB
node:22-slim     ~250MB
node:22-alpine   ~160MB

(Exact numbers vary by release and by whether the containerd image store reports compressed or uncompressed size.) Then see the libc difference:

docker run --rm alpine:3 sh -c 'head -n 2 /etc/os-release; ls /lib/ld-musl*'
docker run --rm debian:bookworm-slim sh -c 'ldd --version | head -n 1'

Common mistakes in module 3

  • Using latest in production. Pin to a version, ideally a digest.
  • Picking Alpine for Python data science and then waiting 20 minutes for compiled wheels.
  • Using ubuntu or full node:22 as a runtime image.
  • Assuming a smaller image is automatically more secure or faster.
  • Forgetting CA certificates and timezone data in scratch images.

Recap checklist

  • I can read an image reference and explain tag vs digest.
  • I can inspect layers with docker history and dive.
  • I can list three Alpine pitfalls and when to choose slim instead.
  • I know when distroless, scratch and hardened images fit.

Module 4: Dockerfile mastery

Learning objectives

  • Use every common Dockerfile instruction correctly.
  • Order instructions for maximum cache reuse.
  • Write multi-stage builds and use BuildKit features: cache, secret and ssh mounts, heredocs.
  • Build multi-platform images with buildx.
  • Produce complete production Dockerfiles for Node/Next.js, Python, Laravel, Go and Rust.

The instructions, one by one

InstructionPurposeNotes
FROMBase image / start a stageFROM image AS name; FROM --platform=$BUILDPLATFORM for cross builds
RUNExecute a command during build, creating a layerCombine related commands; use && and clean up in the same layer
COPYCopy files from context or another stagePreferred. Supports --from=stage, --chown, --chmod, --link
ADDLike COPY, plus URL download and tar auto-extractionUse only when you need those. ADD --checksum=sha256:... for URLs
WORKDIRSet the working directory (creates it)Prefer to RUN cd
ENVEnvironment variable, persists into the image and containersDo not put secrets in it
ARGBuild-time variableNot available at runtime unless copied to ENV; visible in docker history
EXPOSEDocument a portDoes not publish it
USERSet the user for later instructions and runtimeUse a non-root user
ENTRYPOINTThe executable that always runsExec form
CMDDefault arguments (or command if no ENTRYPOINT)Overridable at docker run
HEALTHCHECKCommand to test container health--interval, --timeout, --start-period, --retries; HEALTHCHECK NONE disables
LABELMetadataUse OCI keys: org.opencontainers.image.source, .version, .revision
VOLUMEDeclare a mount pointCreates anonymous volumes; often better to avoid in the Dockerfile
STOPSIGNALSignal sent by docker stopDefault SIGTERM; nginx graceful quit is SIGQUIT
SHELLChange the default shell for shell-form commandsFor example SHELL ["/bin/bash", "-euo", "pipefail", "-c"]
ONBUILDTrigger instruction when the image is used as a baseRarely recommended; hides behaviour

ENV vs ARG

ARGENV
Available during buildyesyes
Available in running containernoyes
Overridable--build-arg KEY=valuedocker run -e KEY=value
Persists in image metadatavisible in historyvisible in docker inspect
Secretsnevernever

Predefined args such as TARGETPLATFORM, TARGETARCH and BUILDPLATFORM become available when you declare them with ARG in the stage.

COPY vs ADD

Use COPY for local files. ADD is justified for extracting a local tarball into the image, or fetching a remote file with an integrity check:

ADD --checksum=sha256:REPLACE_WITH_REAL_SHA256 https://example.com/tool.tar.gz /opt/

For remote downloads in general, RUN curl ... && sha256sum -c is equally good and more explicit.

ENTRYPOINT vs CMD, shell vs exec form

FormSyntaxBehaviour
ExecCMD ["node", "server.js"]Runs the process directly as PID 1. Receives signals. Preferred.
ShellCMD node server.jsRuns as /bin/sh -c "node server.js". The shell is PID 1 and often does not forward SIGTERM, so docker stop waits 10 s then kills.

Combinations:

ENTRYPOINTCMDResult
none["node","app.js"]node app.js
["node"]["app.js"]node app.js; docker run img other.js runs node other.js
["./entrypoint.sh"]["serve"]script receives serve; end the script with exec "$@" so the app becomes PID 1

A typical entrypoint script:

#!/bin/sh
set -e
# run migrations or wait for dependencies here
exec "$@"

HEALTHCHECK

HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
  CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1

The check command must exist in the image. In distroless images, ship a tiny healthcheck binary or define the check in Compose or Kubernetes instead.

.dockerignore

The build context (everything sent to the builder) should be small. Create .dockerignore:

.git
node_modules
.next
dist
build
vendor
__pycache__
*.pyc
.venv
.env
.env.*
!.env.example
Dockerfile*
compose*.yaml
docker-compose*.yml
*.md
.vscode
.idea
coverage
tests

Excluding .env files here also prevents accidentally copying secrets into layers. Adjust it per project: for Laravel, do not ignore vendor if you rely on it, and do not ignore tests if a build stage runs them.

Layer caching

BuildKit caches each instruction. If an instruction and its inputs (for COPY, file contents) are unchanged, the layer is reused. The first changed layer invalidates everything after it. So order from least to most frequently changing:

# Good: dependencies change rarely, source changes constantly
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# Bad: any source change reinstalls all dependencies
COPY . .
RUN npm ci && npm run build

Other cache rules:

  • RUN apt-get update must be in the same RUN as apt-get install, otherwise a stale cached package index causes failures.
  • A RUN is cached by its command text, not by what the network returns. RUN git clone ... or RUN curl latest can be stale; pin versions or bust the cache deliberately with an ARG.
  • COPY . . is invalidated by any file change in the context, including files you did not mean to include. Keep .dockerignore tight.

Multi-stage builds

Use one stage to build and a clean stage to run:

# syntax=docker/dockerfile:1
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server

FROM gcr.io/distroless/static-debian12:nonroot AS runtime
COPY --from=build /out/server /server
ENTRYPOINT ["/server"]

Useful variants:

docker build --target build -t myapp:build .      # stop at a named stage (for tests or debugging)
docker build --build-arg APP_VERSION=1.4.2 -t myapp .

BuildKit skips stages nothing depends on and builds independent stages in parallel.

BuildKit features

Start the Dockerfile with # syntax=docker/dockerfile:1 to get the current stable frontend features.

Cache mounts persist package manager caches between builds without bloating layers:

RUN --mount=type=cache,target=/root/.npm npm ci
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    rm -f /etc/apt/apt.conf.d/docker-clean \
 && apt-get update && apt-get install -y --no-install-recommends curl

On Debian images the docker-clean apt config auto-deletes downloaded packages, which defeats an apt cache mount, hence the rm above (verify against the current Docker docs for your base).

Secret mounts expose a secret to one RUN without writing it into any layer:

RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci
docker build --secret id=npm_token,env=NPM_TOKEN -t myapp .
# or from a file:
docker build --secret id=npm_token,src=$HOME/.npm_token -t myapp .

SSH mounts forward your agent for private Git dependencies:

RUN --mount=type=ssh git clone git@github.com:your-org/private.git /src/private
docker build --ssh default -t myapp .

Bind mounts in RUN read files from the context or another stage without copying them into a layer:

RUN --mount=type=bind,source=package.json,target=package.json \
    --mount=type=bind,source=package-lock.json,target=package-lock.json \
    --mount=type=cache,target=/root/.npm \
    npm ci

Heredocs let you write multi-line scripts and files cleanly:

RUN <<EOF
set -eux
apt-get update
apt-get install -y --no-install-recommends ca-certificates curl
rm -rf /var/lib/apt/lists/*
EOF

COPY <<EOF /etc/app/config.json
{ "logLevel": "info" }
EOF

COPY --link makes layer copies independent of earlier layers, improving cache reuse when the base changes:

COPY --link --from=build /app/dist ./dist

Multi-platform builds

Apple silicon laptops build linux/arm64; most servers are linux/amd64. Build for both with buildx:

docker buildx create --name multi --driver docker-container --use
docker buildx inspect --bootstrap
docker buildx build --platform linux/amd64,linux/arm64 \
  -t ghcr.io/your-org/api:1.0.0 --push .

There are three ways to get a non-native architecture:

  1. QEMU emulation via binfmt: works anywhere, slow.
  2. Native builder nodes per architecture: fast, needs two machines (or Docker Build Cloud).
  3. Cross-compilation in the build stage with --platform=$BUILDPLATFORM: fastest for Go and Rust.
FROM --platform=$BUILDPLATFORM golang:1.25 AS build
ARG TARGETOS TARGETARCH
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /out/server ./cmd/server

On Linux CI, install QEMU handlers with docker run --privileged --rm tonistiigi/binfmt --install all (or use docker/setup-qemu-action in GitHub Actions). Multi-platform results usually cannot be loaded into the classic local image store with --load; use --push, or --output type=oci, or enable the containerd image store.

Reproducibility

  • Pin base images by digest and apt/apk packages by version where practical.
  • Use lock files (package-lock.json, uv.lock, composer.lock, Cargo.lock, go.sum) and frozen installs (npm ci, uv sync --frozen, composer install).
  • Set SOURCE_DATE_EPOCH for reproducible timestamps (BuildKit supports it; verify the exact options in the BuildKit docs).
  • Add provenance and SBOM attestations in CI (module 8).

Production Dockerfile: Node.js and Next.js

Next.js with output: "standalone" in next.config.ts produces a minimal server bundle.

# syntax=docker/dockerfile:1
ARG NODE_VERSION=22

FROM node:${NODE_VERSION}-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

FROM node:${NODE_VERSION}-bookworm-slim AS build
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM node:${NODE_VERSION}-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3000 \
    HOSTNAME=0.0.0.0
RUN groupadd --system --gid 1001 nodejs \
 && useradd --system --uid 1001 --gid nodejs nextjs
COPY --from=build --chown=nextjs:nodejs /app/public ./public
COPY --from=build --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=build --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s \
  CMD node -e "fetch('http://127.0.0.1:3000/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.js"]

Notes: NEXT_PUBLIC_* variables are inlined at build time, so pass them as build args to the build stage. Server-only secrets must be read at runtime from env, never baked in. For a plain Node API, replace the .next copies with dist and a pruned node_modules (npm prune --omit=dev).

Production Dockerfile: Python with uv

# syntax=docker/dockerfile:1
FROM python:3.13-slim-bookworm AS build
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --frozen --no-install-project --no-dev
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev

FROM python:3.13-slim-bookworm AS runtime
ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1
RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --no-create-home app
WORKDIR /app
COPY --from=build --chown=app:app /app /app
USER app
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Pin uv to a version tag instead of latest for reproducibility (verify the current release). With plain pip: create a venv in the build stage, run pip install --no-cache-dir -r requirements.txt, and copy the venv across. The venv path must be identical in both stages, which is why both use /app/.venv.

Production Dockerfile: PHP / Laravel (php-fpm + nginx)

Two containers is the cleanest pattern (one process per container): app runs php-fpm, web runs nginx and serves static files. Build both from one Dockerfile with targets.

# syntax=docker/dockerfile:1
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/cache \
    composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --optimize --classmap-authoritative --no-dev

FROM node:22-bookworm-slim AS assets
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY resources ./resources
COPY vite.config.js ./
COPY public ./public
RUN npm run build

FROM php:8.4-fpm-bookworm AS app
RUN apt-get update && apt-get install -y --no-install-recommends \
      libicu-dev libzip-dev libpq-dev \
 && docker-php-ext-install -j"$(nproc)" intl zip pdo_mysql pdo_pgsql opcache pcntl \
 && rm -rf /var/lib/apt/lists/*
COPY docker/php/opcache.ini /usr/local/etc/php/conf.d/opcache.ini
WORKDIR /var/www/html
COPY --from=vendor --chown=www-data:www-data /app ./
COPY --from=assets --chown=www-data:www-data /app/public/build ./public/build
RUN mkdir -p storage/framework/cache storage/framework/sessions storage/framework/views storage/logs bootstrap/cache \
 && chown -R www-data:www-data storage bootstrap/cache
USER www-data
EXPOSE 9000
CMD ["php-fpm"]

FROM nginx:1.27-alpine AS web
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=app /var/www/html/public /var/www/html/public
EXPOSE 80

docker/php/opcache.ini:

opcache.enable=1
opcache.memory_consumption=192
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
opcache.jit=tracing
opcache.jit_buffer_size=64M

docker/nginx/default.conf:

server {
    listen 80;
    server_name _;
    root /var/www/html/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass app:9000;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Build the two targets: docker build --target app -t your-org/laravel-app . and docker build --target web -t your-org/laravel-web .. Run php artisan config:cache, route:cache and view:cache at container start (an entrypoint script) rather than at build time, because configuration depends on runtime env. opcache.validate_timestamps=0 means code changes need a new container, which is exactly what you want in production. Adjust the PHP extension list to your app.

Production Dockerfile: Go

# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM golang:1.25-bookworm 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 --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
EXPOSE 8080
USER nonroot:nonroot
ENTRYPOINT ["/server"]

Check the current Go version tag on Docker Hub; 1.25 is an example.

Production Dockerfile: Rust with cargo-chef

cargo-chef computes a "recipe" of your dependencies so they are compiled in a cached layer, separate from your own code.

# syntax=docker/dockerfile:1
FROM rust:1-bookworm AS chef
RUN cargo install cargo-chef --locked
WORKDIR /app

FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN cargo build --release --bin server && cp target/release/server /server

FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
COPY --from=builder /server /server
EXPOSE 8080
ENTRYPOINT ["/server"]

Use distroless/cc because default Rust targets link glibc dynamically. For a scratch image, build with the x86_64-unknown-linux-musl target. With cargo-chef the dependency layer lives in the image layer cache, so in CI persist it with cache-from and cache-to (module 8). Replace server with your binary name.

Lab 4: Cache behaviour, hands on

mkdir -p ~/docker-lab4 && cd ~/docker-lab4
cat > package.json <<'JSON'
{ "name": "lab4", "version": "1.0.0", "dependencies": { "left-pad": "1.3.0" } }
JSON
echo 'console.log("v1")' > index.js
cat > Dockerfile <<'DOCKER'
FROM node:22-alpine
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["node", "index.js"]
DOCKER

docker build -t lab4 . 2>&1 | tail -n 5
echo 'console.log("v2")' > index.js
docker build -t lab4 . 2>&1 | grep -E 'CACHED|RUN|COPY'
docker run --rm lab4
#5 [2/4] COPY package.json ./
#5 CACHED
#6 [3/4] RUN npm install
#6 CACHED
v2

The npm install layer is CACHED on the second build because only index.js changed. Now edit package.json and rebuild: the install layer reruns.

Common mistakes in module 4

  • COPY . . before installing dependencies.
  • RUN apt-get update on its own line.
  • Shell-form CMD so the app never sees SIGTERM.
  • Running as root in the final stage.
  • Passing secrets with ARG or ENV. They stay in image metadata. Use --mount=type=secret.
  • Using ADD for local copies; forgetting .dockerignore.
  • Leaving compilers and dev dependencies in the runtime stage.
  • Building multi-arch with QEMU for Go or Rust when cross-compiling would be far faster.

Recap checklist

  • My Dockerfile starts with # syntax=docker/dockerfile:1, installs deps before copying source and has a .dockerignore.
  • Final stage is minimal, non-root, with exec-form CMD and a healthcheck.
  • No secrets in ARG, ENV or COPY.
  • I can build for amd64 and arm64 with buildx.

Module 5: Storage

Learning objectives

  • Choose between volumes, bind mounts and tmpfs.
  • Persist database data, back it up and restore it.
  • Diagnose permission and UID problems.

Why storage needs thought

A container's writable layer is deleted with the container and is slower than a mount (copy-on-write). Anything that must outlive the container, or be written heavily, belongs on a mount.

TypeWhere data livesManaged byBest for
Named volumeDocker area (/var/lib/docker/volumes/... on Linux; inside the VM on Desktop)DockerDatabases, uploads, anything persistent
Anonymous volumeSame, with a random nameDockerRarely wanted; created by VOLUME in a Dockerfile
Bind mountAny host path you chooseYouSource code in dev, config files
tmpfsHost RAM (Linux only)KernelSecrets in memory, scratch space, /tmp with --read-only

Syntax: -v vs --mount

--mount is explicit and errors on mistakes; -v silently creates a missing host directory.

# Named volume
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:17
docker run -d --name db --mount type=volume,source=pgdata,target=/var/lib/postgresql/data postgres:17

# Bind mount (read-only)
docker run --rm -v "$PWD/site":/usr/share/nginx/html:ro nginx:1.27-alpine
docker run --rm --mount type=bind,source="$PWD/site",target=/usr/share/nginx/html,readonly nginx:1.27-alpine

# tmpfs
docker run --rm --tmpfs /tmp:rw,size=64m,mode=1777 alpine df -h /tmp

Note: the postgres image changed its data directory layout in recent major versions (the volume mount point for version 18 and later differs from older releases). Check the image's Docker Hub page for the correct mount path for your version.

Managing volumes

docker volume create pgdata
docker volume ls
docker volume inspect pgdata
docker volume rm pgdata
docker volume prune          # removes volumes not referenced by any container

A named volume is initialised from the image's content at the mount path the first time it is mounted empty. A bind mount hides whatever the image had at that path. This is why bind-mounting ./node_modules or an empty folder over /app breaks things.

Persisting a database

docker run -d --name pg \
  -e POSTGRES_PASSWORD=devpassword \
  -v pgdata:/var/lib/postgresql/data \
  -p 127.0.0.1:5432:5432 \
  postgres:17

docker exec -it pg psql -U postgres -c "CREATE TABLE t(id int); INSERT INTO t VALUES (1);"
docker rm -f pg                                # container gone
docker run -d --name pg2 -e POSTGRES_PASSWORD=devpassword -v pgdata:/var/lib/postgresql/data postgres:17
sleep 5
docker exec pg2 psql -U postgres -c "SELECT * FROM t;"
 id 
----
  1
(1 row)

The data survived because the volume did.

Backups and restores

Filesystem-level backup of a volume using a throwaway container (stop the writer first for consistency):

docker run --rm -v pgdata:/data:ro -v "$PWD":/backup alpine \
  tar czf /backup/pgdata-$(date +%F).tar.gz -C /data .

# Restore into a fresh volume
docker volume create pgdata_restored
docker run --rm -v pgdata_restored:/data -v "$PWD":/backup alpine \
  tar xzf /backup/pgdata-2026-11-11.tar.gz -C /data

Logical backup (preferred for databases, consistent without stopping):

docker exec pg pg_dump -U postgres -Fc appdb > appdb.dump
docker exec -i pg pg_restore -U postgres -d appdb --clean --if-exists < appdb.dump
# MySQL
docker exec mysql sh -c 'mysqldump -uroot -p"$MYSQL_ROOT_PASSWORD" appdb' > appdb.sql

Schedule logical dumps from a sidecar or host cron and copy them off the machine. A backup that lives on the same disk as the data is not a backup.

Permissions and UID problems

Files on bind mounts keep their host numeric UID/GID. If the container user is UID 1000 but the host files belong to UID 501 (macOS) or root, writes fail with permission denied.

SymptomCauseFix
EACCES writing to a bind mount on LinuxContainer UID differs from host ownerRun with --user "$(id -u):$(id -g)", or chown the host dir to the container UID
Files created by the container are owned by root on the hostContainer runs as rootRun as non-root, or fix ownership after
Named volume is root-owned, app is non-rootVolume was initialised before USER or from empty root-owned dirchown in the Dockerfile (create the directory and chown before the volume is first mounted), or fix with a one-off docker run --rm -v vol:/d alpine chown -R 1000:1000 /d
Works on macOS, fails on Linux CIDocker Desktop translates ownership on macOS bind mountsFix UIDs explicitly; do not rely on translation
SELinux host (Fedora, RHEL) denies accessMissing labelAdd :z or :Z to the bind mount (-v ./data:/data:Z)

Compose example:

services:
  app:
    user: "${UID:-1000}:${GID:-1000}"
    volumes:
      - ./data:/app/data

Export UID and GID yourself (export UID GID=$(id -g)), since bash treats UID as a read-only shell variable that is not always exported.

Volume drivers and remote storage

The default local driver stores on the host. Plugins add other backends. The local driver can also mount NFS or CIFS directly:

docker volume create --driver local \
  --opt type=nfs --opt o=addr=10.0.0.5,rw,nfsvers=4 \
  --opt device=:/exports/media media

Network volumes trade speed and locking semantics for portability. Never put a database data directory on NFS unless you know exactly why it is safe.

Performance on macOS and Windows

Bind mounts cross a VM boundary and are slower than named volumes. Docker Desktop uses VirtioFS by default on current versions, which is much faster than the old osxfs, but file-heavy workloads (node_modules, vendor, PHP) are still slow. Tips:

  • Put dependency directories in named volumes (node_modules, vendor) and mount only source code.
  • Use docker compose watch (module 7) to sync or rebuild instead of bind-mounting.
  • On Windows keep the repo inside WSL 2.

Lab 5: Persist, back up, restore

docker volume create labdata
docker run --rm -v labdata:/data alpine sh -c 'echo important > /data/note.txt'
docker run --rm -v labdata:/data:ro -v "$PWD":/backup alpine tar czf /backup/labdata.tgz -C /data .
docker volume rm labdata
docker volume create labdata
docker run --rm -v labdata:/data -v "$PWD":/backup alpine tar xzf /backup/labdata.tgz -C /data
docker run --rm -v labdata:/data alpine cat /data/note.txt
important

Common mistakes in module 5

  • Running a database with no volume.
  • Bind-mounting over a directory the image populated (/app/node_modules).
  • Putting secrets or a database on a bind mount in a shared directory.
  • Expecting docker compose down to delete volumes (it does not, unless you pass -v).
  • Running docker compose down -v on production by habit.

Recap checklist

  • I use named volumes for persistent data and bind mounts for dev source.
  • I can back up and restore a volume and take a logical DB dump.
  • I can fix a UID/permission mismatch.

Module 6: Networking

Learning objectives

  • Understand bridge, host, none, overlay and macvlan drivers.
  • Use user-defined networks and built-in DNS for service discovery.
  • Publish ports safely; reach the host from a container.
  • Debug connectivity with the right tools.

Network drivers

DriverWhat it doesTypical use
bridgePrivate virtual switch on one host; NAT to the outsideDefault single-host networking
hostContainer shares the host network stack (no isolation, no port mapping)Performance-sensitive or many-port apps (Linux; on Desktop requires opt-in support, verify current docs)
noneNo networking except loopbackIsolated batch jobs
overlayMulti-host network (Swarm) over VXLANSwarm services
macvlanContainer gets its own MAC and LAN IPLegacy apps that must appear as physical hosts
ipvlanLike macvlan, shares host MACNetworks that limit MAC addresses

Default bridge vs user-defined bridge

The default bridge network (docker0) has no automatic DNS between containers. A user-defined bridge provides:

  • Automatic DNS: containers resolve each other by name and service alias.
  • Better isolation: only containers on the same network can talk.
  • Attach and detach containers on the fly.

Always create your own network (Compose does this for you).

docker network create appnet
docker run -d --name api --network appnet nginx:1.27-alpine
docker run --rm --network appnet alpine sh -c 'wget -qO- http://api | head -n 3'
<!DOCTYPE html>
<html>
<head>

Port publishing

-p 8080:80                  # host 8080 -> container 80, all interfaces
-p 127.0.0.1:8080:80        # loopback only (recommended for local use)
-p 8080:80/udp              # UDP
-p 8000-8010:8000-8010      # ranges
-P                          # all EXPOSEd ports to random host ports

Container-to-container traffic on the same user-defined network needs no published port. Publish only what outside clients must reach, and put a reverse proxy in front.

Important: Docker inserts its own firewall rules, so published ports are often reachable even if ufw says they are blocked. Bind to 127.0.0.1 or put the host behind a cloud firewall. Docker Engine 29 adds experimental nftables support; check the current docs if you use nftables-based firewalls.

Reaching the host and the outside

FromToHow
ContainerHost servicehost.docker.internal (built in on Desktop; on Linux add --add-host=host.docker.internal:host-gateway or extra_hosts: ["host.docker.internal:host-gateway"])
ContainerInternetNAT through the host by default
HostContainerPublished port, or the container IP on Linux (docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' name)
ContainerAnother containerName on a shared user-defined network

A service listening on 127.0.0.1 on the host is not reachable via host.docker.internal unless it binds to 0.0.0.0 or the gateway address.

DNS and service discovery

Inside a user-defined network, Docker's embedded DNS server (127.0.0.11) resolves container names, Compose service names and --network-alias values. Multiple containers sharing an alias get round-robin DNS.

docker run -d --name web1 --network appnet --network-alias web nginx:1.27-alpine
docker run -d --name web2 --network appnet --network-alias web nginx:1.27-alpine
docker run --rm --network appnet alpine nslookup web
Name:   web
Address: 172.18.0.3
Name:   web
Address: 172.18.0.4

Multiple networks and isolation

Use separate networks to enforce tiers: a reverse proxy on frontend, the app on both, the database only on backend.

docker network create frontend
docker network create --internal backend      # --internal: no outbound internet
docker network connect frontend api
docker network connect backend api

IPv6

Enable IPv6 on a user-defined network with docker network create --ipv6 mynet (recent Engine versions can allocate a ULA subnet automatically; verify the exact flags for your version) or set "ipv6": true and a fixed-cidr-v6 in /etc/docker/daemon.json for the default bridge. In Compose, set enable_ipv6: true on the network.

Debugging networking

nicolaka/netshoot is a container full of network tools (curl, dig, nslookup, tcpdump, ss, iperf, traceroute). Attach it to the target's network namespace:

docker run -it --rm --network container:api nicolaka/netshoot
# inside:
ss -tlnp
curl -v http://localhost:80
dig api
tcpdump -i eth0 port 80

Checklist when "it can't connect":

  1. Is the process listening on 0.0.0.0 (not 127.0.0.1) inside the container?
  2. Are both containers on the same user-defined network?
  3. Are you using the container port (not the published host port) for container-to-container calls?
  4. Does the name resolve? (nslookup, getent hosts name)
  5. Is the port published and bound to the right interface? (docker port, ss -tlnp on host)

Lab 6: A two-tier network

docker network create labnet
docker run -d --name backend --network labnet hashicorp/http-echo -text="hello from backend"
docker run --rm --network labnet curlimages/curl -s http://backend:5678
docker run --rm curlimages/curl -s --max-time 3 http://backend:5678 || echo "unreachable from default bridge"
docker rm -f backend && docker network rm labnet
hello from backend
curl: (6) Could not resolve host: backend
unreachable from default bridge

Common mistakes in module 6

  • Apps binding to localhost inside the container (invisible to other containers and to published ports). Bind 0.0.0.0.
  • Calling localhost:5432 from the app container to reach the database container. Use the service name.
  • Using the default bridge and expecting name resolution.
  • Publishing every service port to 0.0.0.0 on a public server.
  • Using --link (deprecated).

Recap checklist

  • I create user-defined networks and use service names for discovery.
  • I publish only necessary ports, bound to the right interface.
  • I can reach the host with host.docker.internal.
  • I can debug with netshoot.

Module 7: Docker Compose

Learning objectives

  • Write a complete compose.yaml with services, networks, volumes, env, healthchecks and profiles.
  • Use overrides, include, extends, secrets and configs.
  • Use docker compose watch for development.
  • Build realistic stacks: Next.js + Postgres, and a Laravel stack.

Compose v2 and the file name

Compose is now the docker compose plugin (v2+), implementing the Compose Specification. The preferred file name is compose.yaml (also supported: compose.yml, docker-compose.yaml, docker-compose.yml). The top-level version: key is obsolete and ignored; do not add it. Overrides are read from compose.override.yaml automatically.

docker compose up -d --build     # create networks/volumes, build, start
docker compose ps
docker compose logs -f web
docker compose exec web sh
docker compose run --rm web npm test    # one-off container
docker compose stop | start | restart
docker compose down              # stop and remove containers, networks
docker compose down -v           # ...and named volumes (data loss)
docker compose config            # validate and print the resolved file
docker compose pull | push | build
docker compose up -d --scale worker=3
docker compose watch

Anatomy

name: myapp                      # project name (optional; defaults to directory name)

services:
  web:
    image: ghcr.io/your-org/web:1.0.0
    build:
      context: .
      dockerfile: Dockerfile
      target: runtime
      args:
        NEXT_PUBLIC_API_URL: https://api.example.com
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      NODE_ENV: production
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/app
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/api/health"]
      interval: 15s
      timeout: 3s
      retries: 5
      start_period: 20s
    restart: unless-stopped
    networks: [frontend, backend]
    volumes:
      - uploads:/app/uploads
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 512M
    init: true
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]

networks:
  frontend:
  backend:
    internal: true

volumes:
  uploads:

Key points:

FeatureNotes
depends_onShort form only orders start. Use condition: service_healthy (needs a healthcheck on the dependency), service_started, or service_completed_successfully for init jobs.
portsAlways quote "host:container" strings so YAML does not parse them as sexagesimal numbers.
environment vs env_fileenvironment wins over env_file. Interpolation ${VAR:-default} comes from the shell or a project .env file.
deploy.resourcesHonoured by docker compose (not only Swarm) in Compose v2 for limits.
init: trueRuns a tiny init (tini) as PID 1.
restartSame policies as docker run.

Environment variables and .env

Two different things share the name .env:

  1. Interpolation: Compose reads .env in the project directory to substitute ${VAR} inside compose.yaml.
  2. Container env: env_file: and environment: set variables inside containers.

Precedence (highest first): docker compose run -e, shell environment, environment: in the file, env_file:, image ENV. Use ${VAR:?error message} to fail fast when something is missing and ${VAR:-default} for defaults. Never commit real .env files.

Profiles

Profiles make services optional:

services:
  web:
    image: nginx:1.27-alpine
  mailpit:
    image: axllent/mailpit
    profiles: [dev]
  adminer:
    image: adminer
    profiles: [debug]
docker compose up -d                      # only web
docker compose --profile dev up -d        # web + mailpit
COMPOSE_PROFILES=dev,debug docker compose up -d

Overrides, include and extends

compose.yaml holds the shared base; compose.override.yaml is merged automatically for local dev. For production use explicit files:

docker compose -f compose.yaml -f compose.prod.yaml up -d

Merge rules: scalars are replaced; mappings are merged; lists such as ports and volumes are appended (use !reset and !override YAML tags to change that; verify support in your Compose version).

# compose.yaml
include:
  - path: ./infra/db.compose.yaml
  - path: ./infra/observability.compose.yaml

services:
  api:
    extends:
      file: ./common-services.yaml
      service: node-base

include pulls in whole sub-applications (each resolved relative to its own file); extends reuses a single service definition.

Healthchecks that make depends_on real

ServiceHealthcheck test
PostgreSQL["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
MySQL / MariaDB["CMD", "mysqladmin", "ping", "-h", "127.0.0.1"]
Redis["CMD", "redis-cli", "ping"]
HTTP app["CMD", "wget", "-qO-", "http://127.0.0.1:PORT/health"]
nginx["CMD", "wget", "-qO-", "http://127.0.0.1/"]

Note the doubled $$ to stop Compose from interpolating a variable that should be read inside the container.

Secrets and configs

Compose secrets mount files under /run/secrets/<name> (in-memory file mount, not an env var):

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt
  api_key:
    environment: API_KEY      # take from a shell variable

configs: work the same way for non-secret configuration files (nginx.conf, prometheus.yml). Many official images support the *_FILE convention (Postgres, MySQL, MariaDB); your own app should accept it too.

docker compose watch for development

develop.watch syncs files into running containers or rebuilds the image on change, without bind-mounting node_modules:

services:
  web:
    build: .
    ports: ["3000:3000"]
    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
ActionBehaviour
syncCopy changed files into the container (works with hot reload dev servers)
rebuildRebuild the image and recreate the service
sync+restartSync, then restart the container (for config files)
sync+execSync, then run a command inside the container (available in newer Compose versions; verify)
docker compose up --watch        # start and watch
docker compose watch             # watch services that are already running

Scaling and limits

docker compose up -d --scale worker=3

You cannot scale a service that publishes a fixed host port (conflict); put a reverse proxy in front and drop the ports mapping on the scaled service. deploy.replicas also works. Always set CPU and memory limits (deploy.resources.limits) for anything not trusted to behave.

Complete example: web + db + cache + worker + reverse proxy

name: shop

services:
  proxy:
    image: caddy:2-alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      web:
        condition: service_healthy
    networks: [edge, app]
    restart: unless-stopped

  web:
    build:
      context: .
      target: runtime
    environment:
      DATABASE_URL: postgres://shop:${DB_PASSWORD:?set DB_PASSWORD}@db:5432/shop
      REDIS_URL: redis://cache:6379
      NODE_ENV: production
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
      interval: 15s
      timeout: 3s
      start_period: 20s
    networks: [app, data]
    restart: unless-stopped
    init: true

  worker:
    build:
      context: .
      target: runtime
    command: ["node", "worker.js"]
    environment:
      DATABASE_URL: postgres://shop:${DB_PASSWORD}@db:5432/shop
      REDIS_URL: redis://cache:6379
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
    networks: [data]
    restart: unless-stopped
    init: true
    deploy:
      resources:
        limits:
          memory: 384M

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

  cache:
    image: redis:7-alpine
    command: ["redis-server", "--appendonly", "yes", "--maxmemory", "128mb", "--maxmemory-policy", "allkeys-lru"]
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 5
    networks: [data]
    restart: unless-stopped

networks:
  edge:
  app:
  data:
    internal: true

volumes:
  pgdata:
  redisdata:
  caddy_data:
  caddy_config:

Caddyfile:

shop.example.com {
    encode zstd gzip
    reverse_proxy web:3000
}

Caddy obtains and renews TLS certificates automatically for a public DNS name pointing at the server. The data network is internal, so Postgres and Redis cannot reach the internet and are not reachable from outside.

Example: Next.js + Postgres (development)

# compose.yaml
services:
  web:
    build:
      context: .
      target: dev
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DATABASE_URL: postgres://app:app@db:5432/app
      WATCHPACK_POLLING: "true"
    depends_on:
      db:
        condition: service_healthy
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: package.json

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: app
    ports:
      - "127.0.0.1:5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 10

volumes:
  pgdata:

The dev target in the Dockerfile:

FROM node:22-bookworm-slim AS dev
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev", "--", "--hostname", "0.0.0.0"]

Run docker compose up --watch. Edit a file in src/ and watch it sync.

Example: Laravel stack

name: laravel

x-php: &php
  build:
    context: .
    target: app
  environment: &php-env
    APP_ENV: ${APP_ENV:-production}
    APP_KEY: ${APP_KEY:?set APP_KEY}
    DB_CONNECTION: mysql
    DB_HOST: mysql
    DB_DATABASE: laravel
    DB_USERNAME: laravel
    DB_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}
    REDIS_HOST: redis
    CACHE_STORE: redis
    QUEUE_CONNECTION: redis
    SESSION_DRIVER: redis
  depends_on:
    mysql:
      condition: service_healthy
    redis:
      condition: service_healthy
  restart: unless-stopped
  init: true

services:
  app:
    <<: *php
    volumes:
      - storage:/var/www/html/storage/app

  web:
    build:
      context: .
      target: web
    ports:
      - "8080:80"
    depends_on: [app]
    restart: unless-stopped

  queue:
    <<: *php
    command: ["php", "artisan", "queue:work", "--tries=3", "--timeout=90", "--sleep=3"]
    volumes:
      - storage:/var/www/html/storage/app
    stop_grace_period: 60s

  scheduler:
    <<: *php
    command: ["php", "artisan", "schedule:work"]

  mysql:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?set DB_ROOT_PASSWORD}
    volumes:
      - mysqldata:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-p${DB_ROOT_PASSWORD}"]
      interval: 10s
      timeout: 5s
      retries: 10
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 5
    restart: unless-stopped

volumes:
  mysqldata:
  redisdata:
  storage:

The YAML anchors (&php, <<: *php) avoid repeating the shared service definition. Run migrations as a one-off: docker compose run --rm app php artisan migrate --force. For local dev, add a compose.override.yaml that bind-mounts the source and enables Xdebug.

Lab 7: Compose with a health-gated start

mkdir -p ~/docker-lab7 && cd ~/docker-lab7
cat > compose.yaml <<'YAML'
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: dev
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 3s
      timeout: 3s
      retries: 10
  app:
    image: postgres:17-alpine
    command: ["psql", "postgresql://postgres:dev@db:5432/postgres", "-c", "select 'connected' as status"]
    depends_on:
      db:
        condition: service_healthy
YAML
docker compose up --abort-on-container-exit
docker compose down -v
app-1  |   status
app-1  | -----------
app-1  |  connected
app-1 exited with code 0

app only starts after db reports healthy.

Common mistakes in module 7

  • Adding version: (obsolete) or naming files inconsistently.
  • Using depends_on without healthchecks and then racing the database.
  • Unquoted port mappings (22:22 can be misparsed in YAML 1.1).
  • Using localhost as the DB host inside a container.
  • Committing .env with secrets; using docker compose down -v on production.
  • Using latest tags in compose files that deploy to production.
  • Publishing database ports in production compose files.

Recap checklist

  • I can write a multi-service compose.yaml with healthchecks and gated starts.
  • I know the override file, profiles, include and extends.
  • I can use docker compose watch for dev.
  • I handle secrets via files or env interpolation, not committed values.

Module 8: Sharing images and containers

Learning objectives

  • Push and pull images with Docker Hub, GHCR, ECR, Artifact Registry, ACR, Harbor or a self-hosted registry.
  • Design a tagging strategy and deploy by digest.
  • Build and publish multi-arch images.
  • Move images without a registry (save/load) and know why commit and export are different.
  • Share running environments with Compose, Docker Context, Dev Containers, and CI.
  • Sign images and attach SBOM and provenance.

Registries compared

RegistryHostNotes
Docker Hubdocker.ioDefault; public and private repos; free-tier pull rate limits apply (check current limits and authenticate pulls in CI)
GitHub Container Registryghcr.ioTied to GitHub repos/orgs, works with GITHUB_TOKEN in Actions
Amazon ECRACCOUNT.dkr.ecr.REGION.amazonaws.comIAM auth, lifecycle policies, scanning
Google Artifact RegistryREGION-docker.pkg.devReplaces the older Container Registry (gcr.io); IAM auth
Azure Container RegistryNAME.azurecr.ioAzure AD auth, geo-replication
GitLab Container Registryregistry.gitlab.comPer-project
Self-hosted registry:2your hostSimple, no UI/RBAC
Harboryour hostCNCF project: RBAC, scanning, replication, proxy cache, signing

Login, credentials and credential helpers

docker login                        # Docker Hub
docker login ghcr.io -u YOUR_USER   # paste a token when prompted
echo "$TOKEN" | docker login ghcr.io -u YOUR_USER --password-stdin
docker logout ghcr.io

Use --password-stdin so the token never lands in shell history or ps. Docker stores credentials in ~/.docker/config.json; by default that can be a base64 file, which is not encryption. Configure a credential helper (osxkeychain, wincred, pass, secretservice; Docker Desktop configures one for you) so tokens live in the OS keychain:

{
  "credsStore": "osxkeychain",
  "credHelpers": {
    "123456789012.dkr.ecr.eu-west-1.amazonaws.com": "ecr-login"
  }
}

Prefer short-lived tokens: aws ecr get-login-password | docker login --username AWS --password-stdin ..., or gcloud auth configure-docker, or OIDC in CI. Use scoped access tokens, not your account password.

Tagging strategy

TagExampleMutable?Use
Semver exactapi:1.4.2Treat as immutableReleases
Semver minor/majorapi:1.4, api:1MovesConvenience for consumers
Git SHAapi:sha-3f9c2abImmutableTraceability, deploys from CI
Branchapi:mainMovesStaging environments
latestapi:latestMovesConvenience only; never deploy it
Digestapi@sha256:...ImmutableProduction deploys

Rules of thumb: push semver + sha-<short> on every release; deploy the digest that CI printed; use registry immutability settings where available (ECR and Harbor can enforce immutable tags).

docker tag my-api:dev ghcr.io/your-org/api:1.4.2
docker tag my-api:dev ghcr.io/your-org/api:sha-$(git rev-parse --short HEAD)
docker push ghcr.io/your-org/api --all-tags
docker pull ghcr.io/your-org/api:1.4.2
docker buildx imagetools inspect ghcr.io/your-org/api:1.4.2

Private registries, a self-hosted registry and pull-through caches

A minimal private registry for a lab or air-gapped LAN:

docker run -d --name registry --restart unless-stopped \
  -p 127.0.0.1:5000:5000 \
  -v registrydata:/var/lib/registry \
  registry:2

docker tag alpine:3 localhost:5000/alpine:3
docker push localhost:5000/alpine:3
docker pull localhost:5000/alpine:3
curl -s http://localhost:5000/v2/_catalog
{"repositories":["alpine"]}

localhost is treated as a secure registry by Docker. For any other host you need TLS (and optionally auth); do not mark plain-HTTP registries as insecure-registries outside a closed lab.

A pull-through cache (mirror) avoids Docker Hub rate limits and speeds up CI. Run registry:2 with a proxy config and point the daemon at it:

# registry-config.yml
version: 0.1
storage:
  filesystem:
    rootdirectory: /var/lib/registry
http:
  addr: :5000
proxy:
  remoteurl: https://registry-1.docker.io
{
  "registry-mirrors": ["https://mirror.internal.example.com"]
}

(Place the second snippet in /etc/docker/daemon.json and restart the daemon.) Harbor offers proxy-cache projects with a UI and auth.

Multi-arch images and manifests

A multi-arch tag points to a manifest list / OCI index that references one image per platform. Clients pull the matching entry automatically.

docker buildx build --platform linux/amd64,linux/arm64 \
  -t ghcr.io/your-org/api:1.4.2 --push .

docker buildx imagetools inspect ghcr.io/your-org/api:1.4.2
Name:      ghcr.io/your-org/api:1.4.2
MediaType: application/vnd.oci.image.index.v1+json
Manifests:
  Name:      ghcr.io/your-org/api:1.4.2@sha256:...
  Platform:  linux/amd64
  Name:      ghcr.io/your-org/api:1.4.2@sha256:...
  Platform:  linux/arm64

If you build each architecture on native runners, stitch them into one tag:

docker buildx imagetools create -t ghcr.io/your-org/api:1.4.2 \
  ghcr.io/your-org/api:1.4.2-amd64 \
  ghcr.io/your-org/api:1.4.2-arm64

Moving images without a registry: save, load, export, import, commit

CommandOperates onPreservesTypical use
docker save / docker loadImagesLayers, tags, history, metadataAir-gapped transfer, backup, USB handover
docker export / docker importA container filesystemFlat filesystem only (no history, no ENV/CMD, no volumes)Seed a new base image, forensics
docker commitA container to a new imageWritable-layer changesQuick experiments, debugging snapshots. Not for production: it is not reproducible
# Air-gapped transfer
docker save -o api-1.4.2.tar ghcr.io/your-org/api:1.4.2 redis:7-alpine
gzip api-1.4.2.tar
scp api-1.4.2.tar.gz server:/tmp/
ssh server 'gunzip -c /tmp/api-1.4.2.tar.gz | docker load'

# Stream directly over SSH with no temporary file
docker save ghcr.io/your-org/api:1.4.2 | gzip | ssh server 'gunzip | docker load'
Loaded image: ghcr.io/your-org/api:1.4.2
# Export and import (flattens)
docker export web > web-fs.tar
docker import web-fs.tar my-flat-image:1.0 --change 'CMD ["nginx","-g","daemon off;"]'

# Commit (experimental snapshots only)
docker commit -m "debug state" web web-snapshot:debug

Volumes are not part of either: back them up separately (module 5). Prefer a registry and a Dockerfile for anything that is not a one-time transfer.

Sharing a running environment

NeedBest tool
Teammate should run the same multi-service stackCommit compose.yaml plus .env.example; docker compose up
Teammate should develop inside the same toolchainDev Container (module 9)
Deploy to a remote host over SSHdocker context
Demo a local service to someoneA tunnel (cloudflared, ngrok) to a published port; avoid exposing Docker itself
Hand over the exact built artifactPush to a registry and share the digest

Docker contexts point the CLI at other daemons, including over SSH, with no extra agents:

docker context create prod --docker "host=ssh://deploy@203.0.113.10"
docker context ls
docker --context prod ps
docker context use prod            # make it the default
docker --context prod compose up -d
docker context use default

The remote host needs Docker installed and your SSH key authorised for a user in its docker group (root-equivalent, so protect the key). Everything runs on the remote daemon: builds, volumes and mounts refer to the remote machine.

Sharing files between containers

  • Shared named volume mounted into two services (one writer, others :ro).
  • volumes_from is a legacy pattern (--volumes-from other_container in docker run; supported in Compose file format 2 but removed from the modern spec for services). Use named volumes instead.
  • Networked sharing: HTTP between services, or an object store (MinIO) for uploads.
  • Build-time sharing between stages: COPY --from=stage.
services:
  app:
    image: your-org/app
    volumes:
      - assets:/app/public/build
  web:
    image: nginx:1.27-alpine
    volumes:
      - assets:/usr/share/nginx/html/build:ro
volumes:
  assets:

CI: build and push with GitHub Actions

name: docker
on:
  push:
    branches: [main]
    tags: ["v*.*.*"]

permissions:
  contents: read
  packages: write
  id-token: write
  attestations: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-qemu-action@v3
      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=sha,prefix=sha-
            type=ref,event=branch

      - id: build
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: mode=max
          sbom: true

Notes: the action major versions above (checkout@v4, build-push-action@v6, and so on) change over time, so verify the latest majors in each action's repository. type=gha stores the BuildKit cache in the GitHub Actions cache; for large images consider type=registry cache (cache-to: type=registry,ref=ghcr.io/your-org/api:buildcache,mode=max) or Docker Build Cloud (a managed remote builder with shared cache, configured with docker buildx create --driver cloud ORG/BUILDER; it is a paid Docker subscription feature, verify current plans).

Signing, provenance and SBOM

  • SBOM lists the packages in the image. docker buildx build --sbom=true attaches an SBOM attestation; docker buildx imagetools inspect IMAGE --format '{{ json .SBOM }}' reads it.
  • Provenance (SLSA) records how and where the image was built: --provenance=mode=max.
  • Signing with cosign (Sigstore) can be keyless using the CI's OIDC identity:
cosign sign --yes ghcr.io/your-org/api@sha256:DIGEST
cosign verify ghcr.io/your-org/api@sha256:DIGEST \
  --certificate-identity-regexp 'https://github.com/your-org/.*' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com

Sign the digest, not a tag. Enforce verification at deploy time (admission controller on Kubernetes, or a deploy script that runs cosign verify first).

Sharing a dev environment with a team: a recipe

  1. Repo contains Dockerfile, compose.yaml, compose.override.yaml (dev), .env.example, .devcontainer/devcontainer.json.
  2. New hire runs cp .env.example .env && docker compose up --watch, or "Reopen in Container" in VS Code.
  3. Seed data via a one-off service (profiles: [seed]) or a make seed target.
  4. CI builds the same Dockerfile and pushes to the registry, so dev and prod share a build definition.

Lab 8: Run your own registry and ship an image through it

docker run -d --name registry -p 127.0.0.1:5000:5000 registry:2
docker pull nginx:1.27-alpine
docker tag nginx:1.27-alpine localhost:5000/team/nginx:1.27
docker push localhost:5000/team/nginx:1.27
docker rmi localhost:5000/team/nginx:1.27 nginx:1.27-alpine
docker run --rm -d --name from-reg -p 127.0.0.1:8081:80 localhost:5000/team/nginx:1.27
curl -sI http://127.0.0.1:8081 | head -n 1
docker rm -f from-reg registry
HTTP/1.1 200 OK

Now do the same through a file: docker save localhost:5000/team/nginx:1.27 | gzip > nginx.tgz, remove the image, and gunzip -c nginx.tgz | docker load.

Common mistakes in module 8

  • Deploying latest, then not knowing what is running.
  • Passing tokens on the command line instead of --password-stdin.
  • Confusing export with save, and expecting CMD or ENV to survive an export.
  • Using docker commit as a build process.
  • Building multi-arch only for the CI runner's architecture and getting exec format error on Apple silicon or ARM servers.
  • Pushing images that contain .env or private keys (run a secret scan and use .dockerignore).
  • Running a registry over plain HTTP on an open network.

Recap checklist

  • I tag with semver + git SHA and deploy by digest.
  • I can push to GHCR or another registry from CI with cache.
  • I can build multi-arch and inspect the manifest list.
  • I know when to use save/load, export/import and commit.
  • I can target a remote host with docker context.
  • I attach SBOM/provenance and sign by digest.

Module 9: Dev Containers

Learning objectives

  • Explain the Dev Container specification and where it runs.
  • Write devcontainer.json using an image, a Dockerfile or Compose.
  • Use features, lifecycle commands, ports, mounts and customizations.
  • Solve UID mapping and macOS performance problems.
  • Use dev containers in CI and as sandboxes for AI coding agents.

What is a dev container?

A dev container is a container used as a full development environment: the toolchain, language runtimes, CLIs, extensions and settings are defined in code, in .devcontainer/devcontainer.json. The format is an open specification (containers.dev) implemented by:

ToolNotes
VS Code Dev Containers extension"Reopen in Container"
GitHub CodespacesCloud-hosted dev containers
Dev Container CLI (@devcontainers/cli)Build and run from a terminal or CI
JetBrains IDEs (Gateway / remote dev)Support dev containers; check IDE version docs
DevPod, Coder and othersProvider-agnostic implementations

devcontainer.json essentials

It is JSONC (comments allowed).

{
  "name": "Next.js + Postgres",
  // Option A: use an image
  "image": "mcr.microsoft.com/devcontainers/typescript-node:22-bookworm",
  // Option B: build your own
  // "build": { "dockerfile": "Dockerfile", "context": ".." },
  // Option C: Compose
  // "dockerComposeFile": "compose.yaml", "service": "app", "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",

  "features": {
    "ghcr.io/devcontainers/features/github-cli:1": {},
    "ghcr.io/devcontainers/features/docker-outside-of-docker:1": {}
  },

  "forwardPorts": [3000, 5432],
  "portsAttributes": {
    "3000": { "label": "Next.js", "onAutoForward": "openBrowser" }
  },

  "containerEnv": { "NEXT_TELEMETRY_DISABLED": "1" },
  "remoteUser": "node",

  "mounts": [
    "source=node_modules-${devcontainerId},target=${containerWorkspaceFolder}/node_modules,type=volume"
  ],

  "postCreateCommand": "npm ci",
  "postStartCommand": "npm run db:migrate",

  "customizations": {
    "vscode": {
      "extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "bradlc.vscode-tailwindcss"],
      "settings": { "editor.formatOnSave": true }
    }
  }
}

Lifecycle commands

They run in this order: initializeCommand (on the host), onCreateCommand, updateContentCommand, postCreateCommand, postStartCommand, postAttachCommand. A command can be a string, an array, or an object running several in parallel.

CommandWhenTypical content
initializeCommandHost, before the container is createdCreate .env from example
onCreateCommandOnce, on first createPrebuild-friendly setup
updateContentCommandWhen repo content updates (prebuilds)Install dependencies
postCreateCommandAfter the container is created, oncenpm ci, composer install, uv sync
postStartCommandEvery container startStart background services, migrations
postAttachCommandEvery time a tool attachesPrint a welcome message

Features

Features are reusable install units (language runtimes, CLIs) referenced by OCI ID with options. Examples from ghcr.io/devcontainers/features/: node, python, go, rust, php, github-cli, docker-in-docker, docker-outside-of-docker, common-utils, sshd. Versions are pinned with the suffix (:1). Browse the index at containers.dev/features.

"features": {
  "ghcr.io/devcontainers/features/python:1": { "version": "3.13" },
  "ghcr.io/devcontainers/features/node:1": { "version": "22" }
}

Compose-based dev containers

When your project needs a database, cache and mailer, use Compose. .devcontainer/devcontainer.json:

{
  "name": "Laravel",
  "dockerComposeFile": ["../compose.yaml", "compose.devcontainer.yaml"],
  "service": "app",
  "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
  "shutdownAction": "stopCompose",
  "forwardPorts": [8000, 3306],
  "postCreateCommand": "composer install && cp -n .env.example .env && php artisan key:generate"
}

.devcontainer/compose.devcontainer.yaml overrides the app service to be a long-running dev environment with the repo mounted:

services:
  app:
    build:
      context: ..
      dockerfile: .devcontainer/Dockerfile
    volumes:
      - ..:/workspaces/${COMPOSE_PROJECT_NAME:-app}:cached
    command: sleep infinity

sleep infinity keeps the container alive; the editor runs your processes inside it.

Per-language examples

Node / Next.js (image-based, shown in 9.2). Put node_modules in a volume for speed.

Python:

{
  "name": "Python (uv)",
  "image": "mcr.microsoft.com/devcontainers/python:3.13-bookworm",
  "features": { "ghcr.io/va-h/devcontainers-features/uv:1": {} },
  "postCreateCommand": "uv sync",
  "customizations": {
    "vscode": {
      "extensions": ["ms-python.python", "charliermarsh.ruff"],
      "settings": { "python.defaultInterpreterPath": ".venv/bin/python" }
    }
  }
}

(The uv feature ID above comes from a community feature; verify it on containers.dev/features, or install uv in postCreateCommand with pip install uv.)

Laravel / PHP:

{
  "name": "PHP 8.4",
  "image": "mcr.microsoft.com/devcontainers/php:8.4-bookworm",
  "features": {
    "ghcr.io/devcontainers/features/node:1": { "version": "22" }
  },
  "forwardPorts": [8000],
  "postCreateCommand": "composer install && npm ci",
  "customizations": {
    "vscode": { "extensions": ["bmewburn.vscode-intelephense-client", "xdebug.php-debug"] }
  }
}

Rust:

{
  "name": "Rust",
  "image": "mcr.microsoft.com/devcontainers/rust:1-bookworm",
  "mounts": [
    "source=cargo-target-${devcontainerId},target=${containerWorkspaceFolder}/target,type=volume",
    "source=cargo-registry-${devcontainerId},target=/usr/local/cargo/registry,type=volume"
  ],
  "customizations": { "vscode": { "extensions": ["rust-lang.rust-analyzer", "tamasfe.even-better-toml"] } }
}

User and UID mapping

The Microsoft base images create a non-root user (vscode or node, UID 1000). Set remoteUser to it. On Linux, the spec's updateRemoteUserUID (default true) changes the container user's UID/GID to match your host user so bind-mounted files stay writable. On macOS and Windows with Docker Desktop, ownership is translated by the VM, so it usually just works. If files become root-owned, you are running as root; set remoteUser.

Performance tips on macOS

  • Keep dependency folders (node_modules, vendor, target, .venv) in named volumes via mounts (shown above).
  • Alternatively use "Clone Repository in Container Volume" in VS Code: the repo lives in a Docker volume inside the VM, with native Linux speed.
  • Enable VirtioFS in Docker Desktop settings (default on current versions).
  • Allocate enough CPU and RAM to the VM; avoid watching huge directories (.git, build output).
  • Prefer Linux or cloud (Codespaces) for very large monorepos.

Dev containers in CI and the devcontainer CLI

npm install -g @devcontainers/cli
devcontainer up --workspace-folder .
devcontainer exec --workspace-folder . npm test
devcontainer build --workspace-folder . --image-name ghcr.io/your-org/devenv:latest

The official GitHub Action devcontainers/ci runs your tests inside the same environment developers use, so "works in CI" equals "works locally":

- uses: actions/checkout@v4
- uses: devcontainers/ci@v0.3
  with:
    runCmd: npm ci && npm test
    push: never

(Verify the current action version.) You can also prebuild the dev container image and push it to a registry ("image" pointing at the prebuilt tag, or the cacheFrom build option) to cut start-up from minutes to seconds. Codespaces supports prebuilds natively.

Dev containers as sandboxes for AI coding agents

An agent that runs shell commands, installs packages and edits files should not do so with your whole home directory and credentials in reach. A dev container narrows the blast radius:

  • Mount only the project directory, not ~ and not ~/.ssh or cloud credentials.
  • Run as a non-root user; add "runArgs": ["--cap-drop=ALL", "--security-opt=no-new-privileges"] where the toolchain allows it.
  • Restrict network egress (a Compose network with a proxy allow-list, or firewall rules inside the container) when the agent works with untrusted content.
  • Give the agent a scoped, short-lived token rather than your personal credentials.
  • Do not mount the Docker socket into the agent's container.
  • For the strongest isolation, microVM-based sandboxes exist (module 13).

A reproducible environment also means reproducible agent behaviour: the same Node, Python and tool versions for every run.

Lab 9: Your first dev container

mkdir -p ~/devc-lab/.devcontainer && cd ~/devc-lab
cat > .devcontainer/devcontainer.json <<'JSON'
{
  "name": "lab",
  "image": "mcr.microsoft.com/devcontainers/javascript-node:22-bookworm",
  "postCreateCommand": "node --version && echo ready",
  "forwardPorts": [3000]
}
JSON
npx @devcontainers/cli up --workspace-folder .
npx @devcontainers/cli exec --workspace-folder . node -e "console.log(process.version, require('os').userInfo().username)"
v22.x.x node

Open the folder in VS Code and choose "Reopen in Container" to try the editor integration.

Common mistakes in module 9

  • Running everything as root, then fixing permissions forever.
  • Installing tools by hand inside a running dev container (lost on rebuild). Put them in features or the Dockerfile.
  • Bind-mounting node_modules on macOS.
  • Using the Docker-in-Docker feature when the host socket (docker-outside-of-docker) is enough, or vice versa without understanding the security tradeoff.
  • Committing secrets in containerEnv. Use remoteEnv with ${localEnv:VAR}, or a secrets mechanism.

Recap checklist

  • I can write a devcontainer.json using image, Dockerfile, or Compose.
  • I use features and lifecycle commands instead of manual setup.
  • My dependency folders are volumes; my user is non-root.
  • I can run the same environment in CI, and sandbox an agent with it.

Module 10: Security

Learning objectives

  • Run containers with least privilege: non-root, dropped capabilities, read-only filesystem, seccomp, no-new-privileges.
  • Handle secrets without leaking them into layers.
  • Understand rootless Docker and user namespaces.
  • Scan images and reason about the supply chain.
  • Know why the Docker socket is dangerous.

The threat model

Containers share the host kernel. A container escape needs a kernel or runtime vulnerability, or a misconfiguration you created (privileged mode, Docker socket, host mounts, extra capabilities). Most real incidents come from the misconfiguration and vulnerable application categories, so defaults matter. Layer your defences: minimal image, least-privilege runtime, network isolation, patching, and monitoring.

Non-root users

Root inside a container is root-ish on the host if anything breaks out. Create a user in the image:

RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
USER 10001:10001

On Alpine: addgroup -S -g 10001 app && adduser -S -u 10001 -G app app. Use a numeric UID so Kubernetes runAsNonRoot can verify it. Many official images already ship a user: node (UID 1000), nginxinc/nginx-unprivileged (listens on 8080), distroless nonroot (65532). Binding ports below 1024 as non-root needs net.ipv4.ip_unprivileged_port_start or a higher port; just use a high port.

Runtime hardening flags

docker run -d --name hardened \
  --user 10001:10001 \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --cap-drop=ALL \
  --security-opt=no-new-privileges:true \
  --pids-limit 200 \
  --memory 256m --cpus 0.5 \
  -p 127.0.0.1:8080:8080 \
  your-org/api:1.4.2
ControlWhat it doesNotes
--userNon-root processRequired for defence in depth
--read-onlyRoot filesystem read-onlyAdd --tmpfs or volumes for paths that need writes
--cap-drop=ALLRemove all Linux capabilitiesAdd back only what is needed (--cap-add=NET_BIND_SERVICE)
no-new-privilegesBlocks privilege gain via setuid binariesAlmost always safe
seccompSyscall filter. Docker applies a default profile blocking dozens of syscallsNever use --security-opt seccomp=unconfined; supply a custom profile with --security-opt seccomp=profile.json
AppArmor / SELinuxMandatory access control profiles (docker-default on AppArmor hosts)Keep enabled
--pids-limit, memory, CPULimit DoS impactAlways set in production
--privilegedGives nearly all capabilities and device accessAvoid. Equivalent to root on the host

The same in Compose: user, read_only, tmpfs, cap_drop, security_opt, pids_limit, deploy.resources.limits (see module 7).

Secrets

Where secrets must never be:

  • In the Dockerfile (ENV, ARG, COPY .env, RUN echo): they live in layers and docker history, and survive deletion in later layers.
  • In the image at all. Anyone who can pull the image can extract it.
  • In Git.

Where they can be:

StageMechanism
BuildRUN --mount=type=secret (module 4)
Run, simpleFile mounted via Compose secrets: or Docker secrets; *_FILE convention
Run, betterA secrets manager (Vault, AWS Secrets Manager, Doppler, 1Password) fetched at start or injected by the platform
Env varsConvenient but leak via docker inspect, crash dumps and child processes; acceptable for low-risk values

Prove a leak to yourself:

docker history --no-trunc my-api:1.0.0 | grep -i -E 'token|password|secret'

If that finds something, rotate the credential. Deleting the image is not enough if it was ever pushed.

The Docker socket

/var/run/docker.sock is the daemon's root API. Anything that can talk to it can start a privileged container that mounts the host filesystem. Therefore:

  • -v /var/run/docker.sock:/var/run/docker.sock gives the container root on the host. Only do it for tools you fully trust (and consider read-only socket proxies such as tecnativa/docker-socket-proxy for things like Traefik).
  • Membership in the docker group is root-equivalent.
  • Never expose the daemon on TCP (-H tcp://0.0.0.0:2375) without mutual TLS. Prefer ssh:// contexts.
  • Do not mount the socket into CI jobs that run untrusted code; use rootless build tools (BuildKit rootless, Kaniko, buildah) or ephemeral VMs.

Rootless Docker and user namespaces

Rootless mode runs the Docker daemon and containers as an unprivileged user using user namespaces, so even a container breakout lands as that user, not root.

# Debian/Ubuntu: prerequisites uidmap, then (as your normal user)
sudo apt-get install -y uidmap dbus-user-session
dockerd-rootless-setuptool.sh install
systemctl --user enable --now docker
export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock
docker run --rm hello-world

Limitations (verify against the current rootless docs): no privileged ports below 1024 by default, no overlay networks, some storage drivers and --net=host semantics differ, ping may need a sysctl, and networking uses slirp4netns or pasta, which can be slower. userns-remap is the alternative for a root daemon: set "userns-remap": "default" in /etc/docker/daemon.json so container root maps to an unprivileged host UID range (bind-mount ownership gets more complex). Podman is rootless by default and a reasonable alternative.

Scanning images

ToolNotes
Docker ScoutBuilt into Docker Desktop and the CLI. docker scout quickview IMAGE, docker scout cves IMAGE, docker scout recommendations IMAGE. Compares against base-image updates; free tier is limited (check plans).
TrivyOpen source (Aqua). Scans images, filesystems, IaC, secrets and SBOMs.
Grype / SyftAnchore: Grype scans, Syft generates SBOMs.
Docker Hardened Images / ChainguardReduce findings at the source with minimal, rebuilt bases.
docker scout cves --only-severity critical,high my-api:1.0.0
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 my-api:1.0.0
trivy fs --scanners vuln,secret,misconfig .
# CI step
- name: Scan image
  uses: aquasecurity/trivy-action@master
  with:
    image-ref: ghcr.io/${{ github.repository }}:sha-${{ github.sha }}
    severity: CRITICAL,HIGH
    ignore-unfixed: true
    exit-code: "1"

(Pin third-party actions to a release tag or commit SHA rather than master in real pipelines.) Scanners report vulnerabilities in packages that may not be reachable. Triage with VEX statements and focus on exposed, fixable, high-severity issues. Re-scan running images regularly: new CVEs appear after you ship.

Supply chain checklist

  • Pull base images from trusted sources (Docker Official Images, Verified Publisher, Docker Hardened Images); pin digests; let Renovate or Dependabot open update PRs.
  • Use multi-stage builds so compilers and package managers do not ship.
  • Generate SBOM and provenance attestations; sign with cosign; verify before deploy (module 8).
  • Lock dependency versions; use npm ci, --frozen, composer install from a lock file.
  • Build in clean CI environments; do not push from laptops.
  • Treat curl | sh in a Dockerfile as unpinned code execution; download, verify the checksum, then run.

Resource limits as a security control

Without limits, a single container can starve the host (fork bomb, memory leak, log flood). Set --memory, --cpus, --pids-limit, and log rotation (module 11). Set ulimit values with --ulimit nofile=1024:2048 where relevant.

Lab 10: Prove the hardening works

docker run --rm --user 10001:10001 --read-only --cap-drop=ALL \
  --security-opt=no-new-privileges:true alpine:3 sh -c '
    id
    touch /etc/test 2>&1 || echo "root fs is read-only"
    ping -c1 127.0.0.1 2>&1 | head -n 1
  '
uid=10001 gid=10001
touch: /etc/test: Read-only file system
root fs is read-only
ping: permission denied (are you root?)

ping fails because the raw-socket capability was dropped. Now re-run without --cap-drop=ALL and --read-only and compare.

Common mistakes in module 10

  • --privileged "to make it work".
  • Mounting the Docker socket into app containers.
  • ENV API_KEY=... or ARG secrets.
  • Running as root and writable root filesystem by default.
  • Treating scan results as a pass/fail badge without triage, or never re-scanning.
  • Exposing the Docker TCP port.

Recap checklist

  • Image has a numeric non-root USER; runtime uses --cap-drop=ALL, no-new-privileges, and --read-only where possible.
  • No secrets in layers; build secrets use --mount=type=secret.
  • Socket is not mounted into untrusted containers.
  • Images are scanned in CI and re-scanned in production; images are signed.

Module 11: Production and operations

Learning objectives

  • Configure logging drivers and rotation, monitoring and healthchecks.
  • Make containers stop gracefully (PID 1, signals, init).
  • Choose between Compose, Swarm and Kubernetes.
  • Deploy to a VPS with Compose and a reverse proxy; build a CI/CD pipeline.
  • Optimise image size and build speed.

Logging

Write logs to stdout/stderr; Docker captures them. The default json-file driver has no rotation unless configured, and unbounded logs fill disks.

/etc/docker/daemon.json:

{
  "log-driver": "local",
  "log-opts": {
    "max-size": "10m",
    "max-file": "5"
  }
}

Restart the daemon (sudo systemctl restart docker); the new default applies to newly created containers only. Per service in Compose:

services:
  web:
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "5"
DriverUse
localEfficient, rotated by default; note docker logs works
json-fileDefault, human-readable files, needs max-size
journaldSend to systemd journal
syslog, gelf, fluentd, awslogs, gcplogs, splunkShip to log systems. With some remote drivers docker logs may not work (dual logging is available in newer Engine versions)

Emit structured JSON logs from your app and ship them with a collector (Vector, Fluent Bit, Promtail/Alloy) running as a container.

Monitoring

  • Quick look: docker stats, docker events.
  • cAdvisor exports per-container CPU, memory, network and filesystem metrics for Prometheus.
  • Prometheus + Grafana for dashboards and alerts; node_exporter for the host.
  • Uptime checks externally (the host can be up while the app is down).
services:
  cadvisor:
    image: gcr.io/cadvisor/cadvisor:latest
    privileged: false
    devices: ["/dev/kmsg"]
    volumes:
      - /:/rootfs:ro
      - /var/run:/var/run:ro
      - /sys:/sys:ro
      - /var/lib/docker/:/var/lib/docker:ro
    ports: ["127.0.0.1:8081:8080"]
  prometheus:
    image: prom/prometheus:latest
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - promdata:/prometheus
    ports: ["127.0.0.1:9090:9090"]
volumes:
  promdata:
# prometheus.yml
global:
  scrape_interval: 15s
scrape_configs:
  - job_name: cadvisor
    static_configs:
      - targets: ["cadvisor:8080"]

Pin these images to versions in real deployments (shown with latest for brevity), and verify cAdvisor's recommended run flags in its README for your host.

Healthchecks and restart behaviour

  • Define a liveness-style check that verifies the app can serve (a /health endpoint that checks dependencies lightly).
  • restart: unless-stopped restarts crashed containers; it does not restart unhealthy ones on plain Docker. Tools like autoheal or Swarm/Kubernetes act on health.
  • start_period gives slow-starting apps time before failures count.

Graceful shutdown: PID 1, signals and zombies

docker stop sends SIGTERM to PID 1, waits stop_grace_period (10 s default), then SIGKILL. Problems:

ProblemCauseFix
App ignores SIGTERMShell-form CMD makes /bin/sh PID 1Use exec form, or exec node ... in scripts
Node ignores signals as PID 1Default handlers differ for PID 1Handle SIGTERM in code, or use --init
Zombie processes accumulatePID 1 does not reap childreninit: true / docker run --init (tini), or ENTRYPOINT ["tini", "--"]
In-flight requests droppedApp exits immediatelyStop accepting, finish requests, close pools, then exit
// Node graceful shutdown
import { createServer } from "node:http";

const server = createServer((_req, res) => res.end("ok"));
server.listen(3000);

const shutdown = (signal: string) => {
  console.log(`received ${signal}, draining`);
  server.close(() => process.exit(0));
  setTimeout(() => process.exit(1), 8000).unref(); // hard stop before Docker's SIGKILL
};
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));

Set stop_grace_period in Compose to be longer than your drain time (queue workers often need 30 to 60 s). For nginx use STOPSIGNAL SIGQUIT (already set in the official image).

Zero-downtime strategies

On a single host with Compose there is no built-in rolling update. Options:

ApproachHow
Scale-up, then retiredocker compose up -d --no-deps --scale web=2 --no-recreate web, wait for health, remove the old container. Needs a reverse proxy that load-balances via DNS or labels (Traefik, nginx, Caddy) and no fixed host port on the app.
Blue/greenTwo Compose projects (-p blue, -p green); switch the proxy upstream after health passes.
Third-party helpersTools such as docker-rollout implement the scale-up/retire pattern; evaluate for your needs.
OrchestratorDocker Swarm (update_config, order: start-first) or Kubernetes rolling updates.

Database migrations must be backward compatible across the old and new app versions (expand, migrate, contract), otherwise zero-downtime is impossible regardless of tooling.

Compose vs Swarm vs Kubernetes

Compose on one hostDocker SwarmKubernetes
Nodes1ManyMany
Learning curveLowLow-mediumHigh
Rolling updates, self-healingManual / limitedYesYes, rich
AutoscalingNoNo (manual)Yes (HPA/KEDA)
EcosystemDocker-nativeSmall, maintenance mode in practiceHuge
Managed offeringsNone neededFewEKS, GKE, AKS, many more
Best forSide projects, small SaaS, internal toolsSmall multi-node teams already on DockerMulti-team, multi-node, strict reliability needs

Docker Swarm still ships with Engine, but investment in the ecosystem has moved to Kubernetes; verify current support status before choosing it for new work. When to graduate to Kubernetes: you need more than one node for capacity or availability, autoscaling, many teams deploying independently, advanced traffic management, or a managed platform your company already runs. Until then, one well-configured VPS with Compose, backups and monitoring is faster to operate and cheaper. Compose files translate as a starting point with kompose or Docker's Compose Bridge (verify current status).

Deploy to a VPS with Compose and Caddy

Steps on a fresh Ubuntu or Debian VPS:

# 1. Harden and install Docker (see module 1 for install), create a deploy user
adduser --disabled-password deploy && usermod -aG docker deploy
# 2. Firewall: allow only SSH, 80, 443 (and remember Docker bypasses ufw for published ports!)
ufw allow OpenSSH && ufw allow 80 && ufw allow 443 && ufw enable
# 3. Point DNS A/AAAA records for your domain at the server

Project layout on the server:

/srv/shop/
├── compose.yaml          # from module 7.10 (images referenced by digest or version tag)
├── Caddyfile
└── .env                  # DB_PASSWORD=...  (chmod 600, not in Git)

Deploy from your laptop or CI:

docker --context prod compose pull
docker --context prod compose up -d --remove-orphans
docker --context prod image prune -f

For private images, run docker login ghcr.io once on the server with a read-only token. Traefik is the alternative proxy when you want routing by container labels and automatic discovery:

services:
  traefik:
    image: traefik:v3
    command:
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
      - --entrypoints.websecure.address=:443
      - --certificatesresolvers.le.acme.tlschallenge=true
      - --certificatesresolvers.le.acme.email=you@example.com
      - --certificatesresolvers.le.acme.storage=/letsencrypt/acme.json
    ports: ["80:80", "443:443"]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - letsencrypt:/letsencrypt
  web:
    image: ghcr.io/your-org/web:1.4.2
    labels:
      - traefik.enable=true
      - traefik.http.routers.web.rule=Host(`shop.example.com`)
      - traefik.http.routers.web.entrypoints=websecure
      - traefik.http.routers.web.tls.certresolver=le
      - traefik.http.services.web.loadbalancer.server.port=3000
volumes:
  letsencrypt:

Traefik mounts the Docker socket (read-only still exposes container metadata and is a sensitive trust decision; consider a socket proxy). Caddy needs no socket and is simpler for a handful of services.

CI/CD pipeline example

Flow: test, build and push (multi-arch, cached), scan, sign, deploy by digest.

name: ci-cd
on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: docker build --target test -t app:test .

  build-deploy:
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: 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 }}
      - id: build
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ghcr.io/${{ github.repository }}:sha-${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: mode=max
          sbom: true
      - name: Deploy
        env:
          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          IMAGE: ghcr.io/${{ github.repository }}@${{ steps.build.outputs.digest }}
        run: |
          install -m 600 /dev/null key && printf '%s\n' "$SSH_KEY" > key
          ssh -i key -o StrictHostKeyChecking=accept-new deploy@${{ vars.DEPLOY_HOST }} \
            "cd /srv/shop && IMAGE=$IMAGE docker compose up -d --remove-orphans"

In compose.yaml reference image: ${IMAGE} so the deploy pins the exact digest. Use a protected environment with required reviewers for production, and store the SSH key as an environment secret.

Image size and build speed

TechniqueEffect
Multi-stage + minimal runtime baseLargest size win
.dockerignoreSmaller context, fewer cache misses
Order layers by change frequencyBetter cache hits
BuildKit cache mountsFast dependency installs
Remote cache (gha, registry, Build Cloud)CI parity with local speed
Parallel stages (independent FROMs)BuildKit builds them concurrently
--link on COPY, avoiding chown -R layersCheaper layer reuse
Prune dev dependencies, strip binaries (-ldflags="-s -w")Smaller artifacts
Avoid large COPY . . of assets that change oftenKeeps early layers stable

Measure: docker build --progress=plain ., docker history, dive, and docker buildx build --timestamps (verify availability) or the build summary in Docker Desktop's Builds view.

Lab 11: Graceful shutdown you can see

mkdir -p ~/docker-lab11 && cd ~/docker-lab11
cat > app.js <<'JS'
process.on("SIGTERM", () => { console.log("got SIGTERM, cleaning up"); setTimeout(() => process.exit(0), 500); });
console.log("running");
setInterval(() => {}, 1000);
JS
printf 'FROM node:22-alpine\nWORKDIR /app\nCOPY app.js .\nCMD node app.js\n' > Dockerfile.shell
printf 'FROM node:22-alpine\nWORKDIR /app\nCOPY app.js .\nCMD ["node","app.js"]\n' > Dockerfile.exec
docker build -q -f Dockerfile.shell -t lab11:shell .
docker build -q -f Dockerfile.exec -t lab11:exec .
docker run -d --name s lab11:shell && time docker stop s
docker run -d --name e lab11:exec && time docker stop e
docker logs e
docker rm s e
real    0m10.1s     (shell form: SIGKILL after 10 s)
real    0m0.7s      (exec form: handled SIGTERM)
running
got SIGTERM, cleaning up

Hint: some images run /bin/sh as a thin wrapper that does not forward signals; the shell-form container takes the full 10 s grace period.

Common mistakes in module 11

  • No log rotation, then a full disk at 3 a.m.
  • Shell-form CMD and 10-second stops.
  • Relying on restart: alone for health.
  • Exposing databases and dashboards (Grafana, cAdvisor, Portainer) on public IPs.
  • Deploying by pulling latest on the server by hand.
  • Skipping off-host backups and restore tests.
  • Jumping to Kubernetes for a single-server app.

Recap checklist

  • Log rotation configured; logs go to stdout.
  • Containers handle SIGTERM; init: true where needed.
  • Deploys are scripted, by digest, with a rollback plan.
  • Monitoring and off-host backups exist and are tested.

Module 12: Debugging and troubleshooting playbook

Learning objectives

  • Follow a systematic method for any container failure.
  • Fix the most common failures quickly.

A method

  1. State: docker ps -a, docker inspect, exit code, OOMKilled.
  2. Logs: docker logs --tail 200 NAME, docker compose logs.
  3. Inside: docker exec, or start a debug shell with docker run -it --entrypoint sh IMAGE.
  4. Network: netshoot, curl, nslookup.
  5. Filesystem/permissions: ls -ln, id, mount info.
  6. Resources: docker stats, docker system df, host df -h, free -m.
  7. Build: docker build --progress=plain --no-cache.

Exit codes: 0 success; 1 generic app error; 125 Docker daemon error; 126 command not executable; 127 command not found; 137 SIGKILL (often OOM or docker stop timeout); 139 segfault; 143 SIGTERM.

Failure table

SymptomLikely causeDiagnoseFix
Container exits immediatelyMain process ends (no foreground process), crash, bad CMDdocker logs, docker inspect -f '{{.State.ExitCode}}'Run the app in the foreground (nginx -g 'daemon off;'), fix the error, check CMD
exec ... not found / exit 127Wrong path, missing shell (distroless), CRLF line endings in scriptdocker run --rm -it --entrypoint sh IMAGEInstall shell, fix path, convert scripts to LF, chmod +x
Port not reachable from hostApp bound to 127.0.0.1 in container; port not published; wrong host port; firewalldocker port, ss -tlnp in container, docker exec ... curl localhost:PORTBind 0.0.0.0; add -p; check host firewall
Port reachable, but page errorsApp crashed after listen; upstream DNS failureLogs; docker compose psFix upstream, health-gate startups
permission denied on volume or bind mountUID mismatch, SELinux, read-only mountls -ln, id, docker inspect mountsMatch UIDs, chown, add :z, remove :ro
bind: address already in useHost port taken by another process or containerlsof -i :PORT, docker psChange host port; stop the other process
Cannot resolve other serviceDifferent networks, default bridge, typo, service not updocker network inspect, nslookup in netshootSame user-defined network; use service name
DNS fails inside containerHost resolver on 127.0.0.53 (systemd-resolved), VPN, corporate DNScat /etc/resolv.conf in containerSet "dns": ["1.1.1.1","8.8.8.8"] in daemon.json, or dns: per service; fix VPN
no space left on deviceImages, volumes, build cache, logsdocker system df -v, df -h, du -sh /var/lib/docker/containers/*docker builder prune, image prune -a, rotate logs, move data-root
Build is slowHuge context, cache invalidation, no cache mounts, QEMU emulationdocker build --progress=plain, check context size line.dockerignore, reorder layers, cache mounts, cross-compile, remote cache
Cache never hitsCOPY . . too early; changing ARG; timestamps/labels with build time; CI runners without cacheCompare CACHED lines between runsReorder, remove volatile args from early layers, use cache-from/cache-to
exec format errorArchitecture mismatch (arm64 vs amd64), or script without shebangdocker image inspect --format '{{.Architecture}}' IMAGE, uname -mBuild/pull the right platform (--platform), multi-arch builds, add #!/bin/sh
Alpine: not found for an existing binaryBinary linked against glibc, running on muslldd, fileUse Debian slim or build for musl
Alpine: native module build failsMissing python3 make g++, no musl prebuiltBuild logAdd build deps in build stage, or use slim
Zombie / defunct processesPID 1 does not reapps aux inside containerinit: true or tini
10 s delay on docker stop, exit 137SIGTERM not handled / shell formdocker stop timingExec form, handle signals, --init
OOMKilled, exit 137Memory limit exceeded or host OOMdocker inspect -f '{{.State.OOMKilled}}', dmesgRaise limit, fix leak, tune runtime heap (NODE_OPTIONS=--max-old-space-size)
database not ready race at startupdepends_on without healthLogsHealthchecks + condition: service_healthy; app retries
Changes not showing in containerImage not rebuilt; bind mount vs copied code; cachedocker compose up --build, docker compose watchRebuild or use watch/bind mount in dev
pull access denied / unauthorizedNot logged in; wrong name; rate limitdocker login, check name/tagLogin, fix reference, use mirror
Container clock/time zone wrongNo tzdata in imagedateInstall tzdata, set TZ
Host docker hangs or Cannot connect to the Docker daemonDaemon down, wrong context, socket permssystemctl status docker, docker context ls, echo $DOCKER_HOSTStart daemon, docker context use default, fix group
Low disk after docker rmAnonymous volumes left behinddocker volume ls -f dangling=truedocker rm -v, docker volume prune (carefully)

Useful debugging commands

# Start the same image with a shell instead of the real command
docker run --rm -it --entrypoint sh your-org/api:1.4.2

# Debug a distroless/minimal container by sharing its namespaces
docker run --rm -it --pid=container:api --network=container:api nicolaka/netshoot

# See what Docker actually ran
docker inspect -f '{{.Path}} {{json .Args}}' api

# Full build log with no cache
docker build --no-cache --progress=plain . 2>&1 | tee build.log

# Events and daemon logs
docker events --since 10m
journalctl -u docker --since "10 min ago"

Lab 12: Three planted faults

Run each, then diagnose with the table:

# Fault 1: exits immediately
docker run -d --name f1 ubuntu:24.04
docker ps -a --filter name=f1 --format '{{.Status}}'

# Fault 2: unreachable port
docker run -d --name f2 -p 127.0.0.1:9000:9000 python:3.13-slim python -m http.server 9000 --bind 127.0.0.1
curl -s --max-time 2 http://127.0.0.1:9000 || echo "unreachable"

# Fault 3: permission denied
mkdir -p /tmp/lab12 && sudo chown root:root /tmp/lab12
docker run --rm --user 1000:1000 -v /tmp/lab12:/data alpine sh -c 'echo hi > /data/x'
docker rm -f f1 f2
Exited (0) 2 seconds ago
unreachable
sh: can't create /data/x: Permission denied

Fixes: give fault 1 a long-running command; run fault 2 with --bind 0.0.0.0; chown 1000:1000 /tmp/lab12 for fault 3.

Common mistakes in module 12

  • Restarting repeatedly instead of reading the logs and exit code.
  • Debugging inside a container that has no tools instead of attaching a debug container.
  • Rebuilding with --no-cache as a first move, which hides what invalidated the cache.

Recap checklist

  • I check exit code, logs, and inspect first.
  • I can attach netshoot to any container.
  • I recognise exec format error, port-binding and permission failures on sight.

Module 13: Modern and AI features

This module covers the newest Docker features. They evolve quickly; treat every flag and version as "verify against current docs" and check docker <command> --help on your install.

Learning objectives

  • Run local models with Docker Model Runner and wire them into Compose.
  • Run MCP servers in containers and understand the MCP gateway.
  • Build an AI agent stack with Compose.
  • Choose a sandbox strategy for coding agents.

Docker Model Runner (DMR)

Docker Model Runner runs and manages AI models locally through Docker. Models are OCI artifacts pulled from Docker Hub (the ai/ namespace) or GGUF models from Hugging Face (hf.co/...). It exposes an OpenAI-compatible API.

Enable it:

  • Docker Desktop: Settings, AI, "Enable Docker Model Runner"; optionally enable host-side TCP support and pick a port.
  • Docker Engine on Linux: install the plugin package (sudo apt-get install docker-model-plugin on Debian/Ubuntu, or sudo dnf install docker-model-plugin on RPM-based distros), then check docker model version.
docker model pull ai/smollm2
docker model run ai/smollm2 "Explain Docker layers in one sentence."
docker model run ai/smollm2                 # interactive chat
docker model pull hf.co/bartowski/Llama-3.2-1B-Instruct-GGUF
docker model logs
docker model --help                         # list, ps, rm, package, push, tag, and more

OpenAI-compatible endpoints (per the current docs):

CallerBase URL
Host (TCP enabled)http://localhost:12434/engines/v1
Container on Docker Desktophttp://model-runner.docker.internal/engines/v1
Container on Docker Enginehttp://172.17.0.1:12434/engines/v1 (or add an extra_hosts entry for model-runner.docker.internal and use port 12434)
curl http://localhost:12434/engines/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "ai/smollm2", "messages": [{"role": "user", "content": "Hello!"}]}'

Because the API is OpenAI-compatible, any OpenAI SDK works by changing baseURL:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: process.env.LLM_URL ?? "http://localhost:12434/engines/v1",
  apiKey: "not-needed-locally",
});

const res = await client.chat.completions.create({
  model: process.env.LLM_MODEL ?? "ai/smollm2",
  messages: [{ role: "user", content: "Summarise what a Docker volume is." }],
});
console.log(res.choices[0].message.content);

You can also package your own GGUF weights as an OCI artifact and push them to a registry with docker model package --gguf ... --push your-org/model:tag, which lets teams share models the same way they share images.

Hardware note: performance depends on GPU support for your platform (Apple silicon, NVIDIA on Linux and Windows, and others); consult the DMR docs for the currently supported inference backends.

Models in Compose

Compose (v2.38 or later, per current docs) has a top-level models element. When Model Runner is enabled, Compose pulls and runs the model locally and injects the endpoint and model name into your service as environment variables.

services:
  app:
    build: .
    ports:
      - "127.0.0.1:3000:3000"
    models:
      llm:
        endpoint_var: LLM_URL
        model_var: LLM_MODEL

models:
  llm:
    model: ai/smollm2
    context_size: 4096

Short syntax (models: [llm]) injects variables named from the model key (for example LLM_URL and LLM_MODEL). Embedding models need the runtime flag --embeddings:

models:
  embedder:
    model: ai/all-minilm
    context_size: 2048
    runtime_flags:
      - "--embeddings"

MCP servers in containers

The Model Context Protocol (MCP) connects AI clients to tools. Running MCP servers in containers gives you dependency isolation (no global npx or uvx installs) and a smaller blast radius than running arbitrary code on your host.

  • Docker MCP Catalog and Toolkit (in Docker Desktop): a catalog of containerised MCP servers on Docker Hub plus a gateway that runs them and exposes a single MCP endpoint to clients. A client launches the gateway over stdio with docker mcp gateway run (profiles are supported in recent versions; verify the current flags).
  • A hand-rolled alternative is to run any stdio MCP server in a container and let the client start it:
{
  "mcpServers": {
    "filesystem": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges:true",
        "--mount", "type=bind,src=/Users/me/project,dst=/workspace",
        "my-org/mcp-filesystem:1.0.0", "/workspace"
      ]
    }
  }
}

Security guidance for MCP containers: mount only needed directories (read-only when possible), pass only the secrets that server needs, pin image digests, disable network access (--network none) for servers that do not need it, and never mount the Docker socket.

A Compose stack for an AI agent

An agent stack typically contains the agent service, a model endpoint, a vector database, MCP tool servers and an observability sink.

name: agent-stack

services:
  agent:
    build: ./agent
    environment:
      MCP_TOOLS_URL: http://tools:8000/mcp
      QDRANT_URL: http://qdrant:6333
      OTEL_EXPORTER_OTLP_ENDPOINT: http://otel:4318
    models:
      llm:
        endpoint_var: LLM_URL
        model_var: LLM_MODEL
      embedder:
        endpoint_var: EMBED_URL
        model_var: EMBED_MODEL
    depends_on:
      qdrant:
        condition: service_healthy
      tools:
        condition: service_started
    networks: [internal]
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    ports:
      - "127.0.0.1:8000:8000"

  tools:
    build: ./tools          # your MCP server (HTTP transport)
    networks: [internal]
    read_only: true
    cap_drop: [ALL]

  qdrant:
    image: qdrant/qdrant:v1.15.0
    volumes:
      - qdrant:/qdrant/storage
    healthcheck:
      test: ["CMD-SHELL", "bash -c ':> /dev/tcp/127.0.0.1/6333' || exit 1"]
      interval: 10s
      timeout: 3s
      retries: 10
    networks: [internal]

  otel:
    image: otel/opentelemetry-collector-contrib:latest
    networks: [internal]

models:
  llm:
    model: ai/smollm2
    context_size: 8192
  embedder:
    model: ai/all-minilm
    runtime_flags: ["--embeddings"]

networks:
  internal:

volumes:
  qdrant:

Pin image versions in real use (the Qdrant tag above is an example; check the current release). Keep the agent and tool services on an internal network and publish only what you need to 127.0.0.1.

Sandboxing coding agents

Coding agents execute commands, install packages and read files autonomously, so isolation matters. From weakest to strongest:

OptionIsolationNotes
Run on hostNoneNot recommended for autonomous runs
Dev container with a narrow mount (module 9)Container namespaces, shared kernelGood default; restrict network and credentials
Hardened container (--cap-drop=ALL, read-only, non-root, egress filter)StrongerYou maintain the policy
Docker SandboxesMicroVM per agent session with its own kernel and a private Docker daemonDocker's product for agents; the CLI is sbx (for example sbx run claude). Newer and fast-moving: verify availability, commands and licensing in the current docs
Ephemeral cloud VMStrongest separation from your machineCosts and latency; good for untrusted tasks

Principles that apply to all of them: give the agent the minimum files, the minimum credentials (scoped, short-lived tokens), controlled network egress, no Docker socket, and a way to throw the environment away. Review what the agent changed (git diff) before it leaves the sandbox.

Lab 13: Local model behind Compose

Requires Docker Model Runner enabled and Compose v2.38 or later.

mkdir -p ~/docker-lab13 && cd ~/docker-lab13
cat > compose.yaml <<'YAML'
services:
  probe:
    image: curlimages/curl:latest
    models:
      llm:
        endpoint_var: LLM_URL
        model_var: LLM_MODEL
    entrypoint: ["sh", "-c"]
    command:
      - >
        echo "endpoint=$$LLM_URL model=$$LLM_MODEL";
        curl -s "$$LLM_URL/chat/completions"
        -H "Content-Type: application/json"
        -d "{\"model\":\"$$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Say hi in five words\"}]}"
models:
  llm:
    model: ai/smollm2
YAML
docker compose up --abort-on-container-exit
docker compose down

The output prints the injected endpoint and model name, followed by a JSON completion. (If your endpoint variable already includes the /engines/v1 path, the URL above works as written; if the request fails, print the variable and adjust the path per the docs.)

Common mistakes in module 13

  • Assuming a local small model matches a hosted frontier model's quality; evaluate for your task.
  • Exposing the Model Runner TCP port beyond localhost.
  • Mounting the home directory or Docker socket into an MCP or agent container.
  • Pinning nothing: model tags and MCP images change.

Recap checklist

  • I can pull and run a model with docker model and call the OpenAI-compatible API.
  • I can declare models in Compose and read the injected variables.
  • I run MCP servers and agents with least privilege.
  • I know the isolation ladder for coding agents.

Module 14: Cheat sheets and capstone

CLI cheat sheet

TaskCommand
Run detached with port, name, envdocker run -d --name web -p 127.0.0.1:8080:80 -e KEY=val nginx:1.27-alpine
Interactive shell, auto-removedocker run --rm -it alpine sh
List containers / alldocker ps / docker ps -a
Logs followdocker logs -f --tail 100 NAME
Execdocker exec -it NAME sh
Copy filesdocker cp NAME:/path ./local
Inspect fielddocker inspect -f '{{.State.Status}}' NAME
Statsdocker stats --no-stream
Stop / kill / removedocker stop NAME / docker kill NAME / docker rm -f NAME
Images list / removedocker image ls / docker rmi IMAGE
Pull / pushdocker pull IMG / docker push IMG
Tagdocker tag SRC DEST
Builddocker build -t name:tag .
Buildx multi-arch pushdocker buildx build --platform linux/amd64,linux/arm64 -t REF --push .
Inspect manifestdocker buildx imagetools inspect REF
History / layersdocker history IMAGE
Save / loaddocker save -o f.tar IMG / docker load -i f.tar
Volumesdocker volume create / ls / inspect / rm / prune
Networksdocker network create / ls / inspect / connect / disconnect / rm
Disk usagedocker system df -v
Prunedocker system prune, docker builder prune, docker image prune -a
Contextdocker context create / ls / use / rm
Logindocker login REGISTRY --password-stdin
Scandocker scout cves IMAGE
Modelsdocker model pull / run / logs

Dockerfile cheat sheet

GoalSnippet
Enable modern syntax# syntax=docker/dockerfile:1
Multi-stageFROM node:22-slim AS build ... FROM node:22-slim AS runtime ... COPY --from=build
Cache depsCOPY package*.json ./ then RUN npm ci then COPY . .
Cache mountRUN --mount=type=cache,target=/root/.npm npm ci
Secret mountRUN --mount=type=secret,id=tok ... + docker build --secret id=tok,env=TOK
Non-rootUSER 10001:10001
Exec formCMD ["node","server.js"]
Health`HEALTHCHECK --interval=30s CMD wget -qO- http://127.0.0.1:3000/health
Cross-compileFROM --platform=$BUILDPLATFORM ... + ARG TARGETOS TARGETARCH
Chown on copyCOPY --chown=app:app src/ /app/
LabelsLABEL org.opencontainers.image.source="https://github.com/org/repo"
Stop signalSTOPSIGNAL SIGQUIT
HeredocRUN <<EOF ... EOF

Compose cheat sheet

TaskCommand / key
Start / rebuilddocker compose up -d --build
Dev loopdocker compose up --watch
Logsdocker compose logs -f SERVICE
Shelldocker compose exec SERVICE sh
One-offdocker compose run --rm SERVICE CMD
Stop and removedocker compose down (add -v to delete volumes)
Validatedocker compose config
Profilesdocker compose --profile dev up
Multiple filesdocker compose -f compose.yaml -f compose.prod.yaml up -d
Scaledocker compose up -d --scale worker=3
Gate startdepends_on: {db: {condition: service_healthy}}
Limitsdeploy.resources.limits.{cpus,memory}
Secretssecrets: + /run/secrets/NAME
Envenvironment, env_file, ${VAR:-default}, ${VAR:?msg}
Hardeningread_only, cap_drop: [ALL], security_opt: ["no-new-privileges:true"], init: true

Capstone project: containerize a full-stack app end to end

Goal: take a Next.js app with a Postgres database and a background worker, and deliver (1) a multi-stage production image, (2) a Compose stack for dev and prod, (3) a dev container, and (4) a CI pipeline pushing a signed multi-arch image to GHCR and deploying to a VPS.

Repository layout:

shop/
├── .devcontainer/
│   └── devcontainer.json
├── .github/workflows/ci.yaml
├── .dockerignore
├── Dockerfile
├── compose.yaml                # base, production-shaped
├── compose.override.yaml       # dev: watch, exposed ports, mailpit
├── compose.prod.yaml           # prod: pinned image, no dev ports
├── Caddyfile
├── .env.example
├── src/ ...
└── worker/ ...

Step 1. Dockerfile. Use the Next.js Dockerfile from module 4 and add a dev target (see the Next.js + Postgres example in module 7) and a test target that runs npm test. Verify: docker build --target runtime -t shop:local . produces an image under about 300 MB, runs as UID 1001, and passes docker run --rm shop:local id.

Step 2. Compose base. Use the full stack from module 7 (proxy, web, worker, db, cache) with healthchecks, internal data network, resource limits, and init: true. Verify: docker compose config is valid and docker compose up -d reaches all-healthy in docker compose ps.

Step 3. Dev override. compose.override.yaml swaps target: dev, adds develop.watch, publishes Postgres to 127.0.0.1:5432, and adds a Mailpit service under profiles: [dev]. Verify: edit src/app/page.tsx and the browser updates without a rebuild.

Step 4. Dev container. devcontainer.json uses dockerComposeFile pointing at compose.yaml and compose.override.yaml, service: web, node_modules in a named volume, postCreateCommand: npm ci, and forwards 3000 and 5432. Verify: "Reopen in Container", then npm test passes inside.

Step 5. CI. Use the GitHub Actions workflow from module 8: build linux/amd64,linux/arm64, push to ghcr.io/OWNER/shop with sha- and semver tags, cache-from/to: type=gha, SBOM and provenance on. Add a Trivy step that fails on fixable critical issues and a cosign step that signs the digest. Verify: docker buildx imagetools inspect ghcr.io/OWNER/shop:sha-... lists both platforms; cosign verify succeeds.

Step 6. Deploy. Create docker context create prod --docker "host=ssh://deploy@HOST". On the server, keep compose.yaml, compose.prod.yaml, Caddyfile and .env in /srv/shop. The pipeline runs docker compose pull && docker compose up -d --remove-orphans with IMAGE set to the digest. Verify: HTTPS works, docker compose ps is healthy, and rolling back is IMAGE=previous-digest docker compose up -d.

Step 7. Operate. Configure log rotation in daemon.json, a nightly pg_dump copied off-host, and a restore test. Verify: you can restore the dump into a scratch container and query it.

Acceptance checklist:

  • Final image is non-root, has a healthcheck, and no secrets in docker history.
  • docker compose up --watch gives a working dev loop.
  • A teammate can start from a clean clone with a dev container or one docker compose up.
  • CI pushes a multi-arch, signed, attested image with cache.
  • Production deploys by digest and can roll back in under a minute.
  • Backups restore successfully.

Sources and docs

Questions that come up

Should I use Alpine or Debian slim? Default to Debian slim for compatibility. Use Alpine when your dependencies are pure JavaScript, pure Python or static binaries and you have tested it. Use distroless or scratch for static binaries and strict security needs.

Why does docker stop take 10 seconds? The process did not exit on SIGTERM, usually because shell-form CMD made a shell PID 1 or the app does not handle the signal. Docker then sends SIGKILL. Use exec form, handle SIGTERM, or add init: true.

Why can't my containers talk to each other? Usually they are on different networks or on the default bridge, which has no DNS. Use a user-defined network (Compose does this) and call services by name on their container port.

How do I reach a service on my host from a container? Use host.docker.internal (built in on Docker Desktop; add host-gateway as an extra host on Linux), and make the host service listen on a reachable interface.

How do I keep secrets out of images? Do not use ENV, ARG or COPY for secrets. Use BuildKit secret mounts at build time and mounted files or a secrets manager at runtime. Rotate anything that was ever baked into a pushed image.

Do I need Kubernetes? Not for a single server or a small team. Compose on a VPS with backups and monitoring serves many production workloads. Move to Kubernetes when you need multi-node scheduling, autoscaling or many independent teams.

Where to go next

Work through the capstone, then deepen one area: container and Kubernetes security hardening if you ship to production, or the Dev Containers specification if you onboard teams. Keep this page as a reference: the cheat sheets above cover the commands you'll use daily.

The details most likely to be out of date are Engine and Compose version numbers, Docker Hub rate limits and plan features (Scout, Build Cloud, Hardened Images), Docker Sandboxes commands, Model Runner endpoints and flags, GitHub Action major versions, and base image tags (Alpine, Go, Node, PHP and Python releases). Check those against the current docs before you rely on them.