Docker is a containerization platform that packages applications with their dependencies into lightweight, portable containers. It revolutionized software deployment by solving the "works on my machine" problem through consistent, isolated environments that run identically across development, testing, and production. Docker containers share the host OS kernel, making them far more efficient than traditional virtual machines while maintaining strong isolation. Docker Engine 29 (2026) ships BuildKit v0.30 as its default builder and Docker Compose V5 as the standard for multi-container orchestration; the legacy docker-compose v1 binary was fully removed in April 2025 β only docker compose (no hyphen) works now. The 2025β2026 release cycle significantly expanded Docker's scope: Docker Model Runner enables local AI inference with an OpenAI-compatible API; Docker Scout provides integrated vulnerability scanning and SBOM analysis; Docker Hardened Images (DHI) offer free, distroless-based images with CVE patches within 24 hours; Docker Build Cloud offloads builds to remote infrastructure for faster CI; Gordon (docker ai) is an AI-powered assistant that manages containers, debugs failures, and rewrites Dockerfiles from the CLI; and the Docker MCP Toolkit (docker mcp) makes it trivial to run and connect 120+ containerized Model Context Protocol servers to any AI client. The key mental model: a container is a running instance of an image, where images are immutable blueprints built in layers, and layers are cached for speed β understanding this layer caching mechanism is critical for optimizing build times and image sizes.
36 tables, 265 concepts. Select a concept node to jump to its table row.
Table 1: Container Lifecycle Management
These commands move a container through every phase of its life β from initial creation, through running and pausing, to graceful or forced termination. Knowing which command uses which signal (and which preserves the writable layer) is what separates clean production shutdowns from corrupted state.
| Command | Example | Description |
|---|---|---|
docker run -d -p 8080:80 --name web nginx | β’ Creates and starts a new container from an image β’ -d runs detached, -p maps ports, --name assigns a custom name. Most commonly used command. | |
docker start web | β’ Starts an existing stopped container β’ preserves all container state and configuration. | |
docker stop web | Gracefully stops a running container by sending SIGTERM then SIGKILL after grace period (default 10s). | |
docker restart web | β’ Stops then starts the same container instance β’ equivalent to stop + start; preserves the writable layer. | |
docker pause web | β’ Freezes all processes in a container using the cgroups freezer β’ no CPU usage, but memory stays allocated; instant resume with unpause. | |
docker unpause web | β’ Resumes a paused container β’ restores execution exactly where it stopped. | |
docker rm -f web | β’ Removes a stopped container β’ -f forces removal of running containers by SIGKILL-ing them first (no grace period). | |
docker kill web | β’ Immediately stops a container by sending SIGKILL β’ no graceful shutdown, use for unresponsive containers. | |
docker create --name web nginx | β’ Creates a container without starting it β’ useful for preparing containers before start. | |
docker wait web | β’ Blocks until a container stops, then prints its exit code β’ useful in scripts. | |
docker rename web web-old | β’ Renames an existing container β’ works on running and stopped containers; log driver tags keep the original name. | |
docker update --cpus 2 --memory 1g web | β’ Dynamically updates resource limits and restart policy on running containers β’ cannot change image, env vars, ports, or volumes. |
Table 2: Container Inspection and Interaction
Once a container is running, day-to-day work is about seeing what it is doing and reaching inside it. These commands cover listing containers, reading their logs and metrics, running ad-hoc commands inside them, and pulling out the metadata Docker keeps about each one.
| Command | Example | Description |
|---|---|---|
docker ps -a | β’ Lists containers β’ default shows running only, -a includes stopped; --filter health=unhealthy filters by health state; --format '{{.HealthStatus}}' prints health as a dedicated field (Engine 29.5+). | |
docker logs -f --tail 100 web | β’ Shows container stdout/stderr of the main process β’ -f follows live output, --tail limits lines. | |
docker exec -it web bash | β’ Runs a new process inside a running container β’ -it allocates interactive TTY for shell access. | |
docker attach web | β’ Connects to container's main process (PID 1) stdin/stdout/stderr β’ Ctrl+C sends SIGINT and usually stops the container; detach with Ctrl+P, Ctrl+Q. | |
docker inspect --format '{{.NetworkSettings.IPAddress}}' web | β’ Returns detailed JSON with all container metadata (config, state, network, mounts) β’ --format Go templates extract single fields. | |
docker stats --no-stream web | β’ Live stream of CPU, memory, network, disk I/O metrics β’ --no-stream prints one snapshot then exits (use in scripts). | |
docker top web | β’ Shows running processes inside a container, using the host's psβ’ PID column reports host PIDs, not the container's PID 1. | |
docker port web | β’ Lists all published port mappings for a container β’ shows host port β container port bindings (only ports published with -p/-P). | |
docker diff web | Shows filesystem changes vs the starting image (A=added, C=changed, D=deleted). |
Table 3: Image Management
Commands for getting images onto and off your machine: building from a Dockerfile, pulling and pushing through registries, tagging, inspecting layers, and moving images between hosts as tar archives. The two biggest gotchas live here too β save vs export (image vs container, layered vs flat) and docker commit as a production anti-pattern.
| Command | Example | Description |
|---|---|---|
docker build -t myapp:1.0 . | β’ Builds an image from a Dockerfile β’ -t tags it; . is the build context directory sent to the daemon. | |
docker images | Lists local images with repository, tag, image ID, creation date, and size. | |
docker pull nginx:alpine | β’ Downloads an image from a registry (default Docker Hub) β’ only missing layers are fetched thanks to content-addressable storage. | |
docker push myuser/myapp:1.0 | β’ Uploads an image to a registry β’ requires docker login first. | |
docker tag myapp:1.0 myapp:latest | β’ Adds a new name pointing to the same image ID β’ does not copy or duplicate layers. | |
docker rmi nginx:alpine | β’ Removes an image β’ fails if any container (running or stopped) references it unless -f forces removal. | |
docker history nginx | β’ Shows each layer in an image with its size and creating command β’ the go-to tool for diagnosing image bloat. | |
docker save -o app.tar myapp:1.0 | Exports an image to a tar archive, preserving all layers and metadata. | |
docker load -i app.tar | β’ Imports an image from a docker save tarballβ’ restores all layers and original tags. | |
docker import rootfs.tar myapp:1.0 | β’ Creates an image from a raw filesystem tarball β’ result is a single layer with no build history. | |
docker export web -o web.tar | β’ Exports a container's filesystem as a flat tar β’ layers collapsed, image metadata lost. | |
docker commit web myapp:snapshot | β’ Creates a new image from a container's filesystem changes β’ fine for ad-hoc debugging, an anti-pattern for production (no Dockerfile, not reproducible). | |
docker search --limit 5 nginx | β’ Searches Docker Hub only (not arbitrary registries) β’ --filter narrows by stars or official status. |
Table 4: Dockerfile Instructions
A Dockerfile is a recipe of instructions that BuildKit executes top-to-bottom to assemble an image, with most instructions producing a new layer. The instructions below are the building blocks every Dockerfile uses, and the trickiest part is knowing which ones run at build time versus runtime, and which ones only attach metadata.
| Instruction | Example | Description |
|---|---|---|
FROM node:18-alpine | β’ Sets the base image and starts a build stage β’ every Dockerfile begins with FROM (after optional ARG/parser directives) β’ pin a specific tag or digest, never latest in production. | |
RUN apt-get update && \ apt-get install -y curl |β’ Executes commands during image build and commits the result as a new layer β’ always chain apt-get update and apt-get install in the same RUN to avoid stale-cache bugs. | | ||
CMD ["npm", "start"] | β’ Provides the default command (or default args for ENTRYPOINT) when a container starts β’ replaced by any command passed to docker runβ’ prefer the exec form (JSON array) for correct signal handling. | |
ENTRYPOINT ["python", "app.py"] | β’ Configures the container to run as a fixed executable β’ args to docker run are appended to it; override only with --entrypointβ’ when both ENTRYPOINT and CMD are exec form, CMD becomes default arguments. | |
COPY package*.json ./ | β’ Copies files and directories from the build context into the image β’ preferred default for local files β predictable, no hidden behavior. | |
ADD app.tar.gz /app/ | β’ Like COPY, but also auto-extracts local tar archives and can fetch remote URLs β’ use COPY unless you specifically need extraction or URL/Git fetching. | |
WORKDIR /app | β’ Sets the working directory for the RUN, CMD, ENTRYPOINT, COPY, and ADD that follow β’ creates the directory if missing β prefer absolute paths. | |
ENV NODE_ENV=production | β’ Sets environment variables that persist in subsequent build steps and in running containers β’ never use for secrets β values leak into image layers and docker history. | |
ARG VERSION=1.0 | β’ Defines a build-time variable settable with --build-argβ’ not present in the running container's environment, and re-scoped per stage in multi-stage builds. | |
EXPOSE 8080 | β’ Documents which ports the container listens on (image metadata only) β’ does NOT publish ports β docker run -p or -P is still required for host access. | |
VOLUME /data | β’ Declares a path as a mount point for an external/anonymous volume β’ with the legacy builder, writes to that path in later RUN steps are discarded (kept under BuildKit). | |
USER node | β’ Sets the UID/GID used by subsequent RUN, CMD, and ENTRYPOINT and at runtime β’ place it after any RUN that needs root (package install, chown) β running as non-root is a security baseline. | |
LABEL version="1.0" | β’ Attaches metadata to the image as key=value pairs β’ visible via docker inspect and filterable with docker image ls --filter, no runtime behavior. | |
HEALTHCHECK CMD curl -f || exit 1 | β’ Defines a command Docker runs periodically to test if the container is healthy (exit 0=healthy, 1=unhealthy, 2 reserved) β’ only flips the container's health status; Compose/Swarm/K8s decide whether to restart. | |
STOPSIGNAL SIGQUIT | β’ Sets the signal sent to PID 1 when stopping the container β’ defaults to SIGTERM; signals only reach the process directly when CMD/ENTRYPOINT use exec form. | |
SHELL ["/bin/bash", "-c"] | β’ Overrides the shell used for shell-form RUN/CMD/ENTRYPOINT β’ default is ["/bin/sh", "-c"] on Linux and ["cmd", "/S", "/C"] on Windows β essential for picking PowerShell on Windows. | |
ONBUILD COPY . /app | β’ Registers a trigger instruction that runs only when this image is used as a FROM base in a downstream buildβ’ useful for framework base images; triggers do not cascade to grandchildren. |
Table 5: Build Optimization Techniques
These techniques shrink final images, speed up rebuilds, and keep secrets out of layer history. Most are built on BuildKit, the modern Dockerfile frontend (# syntax=docker/dockerfile:1) β multi-stage stages, cache mounts, and secret mounts only behave as described when BuildKit is the active builder.
| Technique | Example | Description |
|---|---|---|
FROM golang AS builderFROM alpineCOPY --from=builder /app . | β’ Uses multiple FROM statements to create separate build stages; only artifacts copied into the final stage end up in the published imageβ’ intermediate stages (compilers, dev tools) are discarded entirely, drastically reducing size and attack surface. | |
COPY package*.json ./RUN npm installCOPY . . | β’ Docker caches each instruction's output as a layer; if a layer's inputs change, that layer and every layer after it must rebuild β’ order instructions least- to most-frequently changed (manifests + install before COPY . .) to maximize hits. | |
COPY --link requirements.txt . | β’ Creates an independent layer that doesn't depend on earlier ones β changes to instructions above it don't invalidate it β’ enables remote cache reuse ( --cache-from) and image rebasing across multi-stage and large builds. | |
node_modules*.log.git | β’ Excludes files from the build context (the bundle sent to the BuildKit daemon), not from the image directly β’ shrinks context upload, blocks accidental COPY of node_modules / .git / secrets, and keeps the cache stable across machines. | |
RUN --mount=type=cache,target=/root/.npm npm install | β’ Mounts a persistent build-time cache at the target path for one RUN only β contents survive between builds but are never stored in image layersβ’ target the package manager's download dir ( /root/.npm, /var/cache/apt, /root/.cache/pip), not the install dir. | |
RUN --mount=type=secret,id=token curl -H "Auth: $(cat /run/secrets/token)" | β’ Mounts a secret as a tmpfs file (e.g. /run/secrets/token) for a single RUN; never written to layers, docker history, or build cacheβ’ replaces the leaky --build-arg / ENV SECRET=... pattern. | |
FROM alpine:3.21FROM gcr.io/distroless/staticFROM scratch | β’ Smaller base = smaller image and smaller attack surface (alpine ~5 MB musl-libc vs ubuntu ~80 MB) β’ distroless drops the shell and package manager; scratch is empty β best for statically-compiled Go/Rust binaries. | |
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/* | β’ Chain commands with && so the install and the cleanup happen in the same layer β files deleted in a later RUN still live in earlier layers' historyβ’ also prevents the stale- apt-get update caching trap. | |
docker buildx build --platform linux/amd64,linux/arm64 -t app . | β’ buildx (the BuildKit-backed CLI) builds for multiple architectures in one invocation, producing a single multi-arch manifestβ’ cross-arch builds need either QEMU emulation or native builder nodes per platform. |
Table 6: Port Publishing and Networking
Container ports stay isolated from the host until you explicitly publish them. The -p family of flags wires a host address and port to a container port; getting the syntax β especially the host-then-container order, the default 0.0.0.0 bind, and the implicit TCP protocol β right is the difference between a reachable service and a silent failure.
| Option | Example | Description |
|---|---|---|
docker run -p 8080:80 nginx | β’ Maps a host port to a container port using HOST_PORT:CONTAINER_PORTβ’ with no host IP, binds to 0.0.0.0 on every interface. | |
docker run -P nginx | β’ Publishes every EXPOSEd port to a random ephemeral host portβ’ query the chosen ports with docker port <container>. | |
docker run -p 127.0.0.1:8080:80 nginx | β’ Binds the published port to a specific host interface β’ use 127.0.0.1 to restrict access to the host (e.g. behind a reverse proxy). | |
docker run -p 8000-8010:8000-8010 app | β’ Maps a range of ports one-to-one β’ a range-to-single form like 8000-9000:5000 picks one free host port from the range. | |
docker run -p 53:53/udp dns | β’ -p publishes TCP by default; append /udp for UDP services like DNS, QUIC, or SIPβ’ to publish both, repeat the flag: -p 53:53/tcp -p 53:53/udp. |
Table 7: Network Modes
Docker networking is driven by a pluggable set of built-in drivers β each one shapes how a container's network namespace is wired up, what it can reach, and how it appears to the rest of the world. Picking the right one is the difference between a quick local test and a setup that survives a multi-host production deployment.
| Mode | Example | Description |
|---|---|---|
docker run --network bridge nginx | β’ Containers get private IPs on a virtual L2 bridge with NAT for outbound traffic β’ the default bridge has no name-based DNS between containers β only user-defined bridge networks do. | |
docker run --network host nginx | β’ Container shares the host's network namespace β no isolation, no NAT, binds host ports directly β’ fastest but largest security blast radius. Linux only (Desktop 4.34+ via VM bridge). | |
docker run --network none app | β’ Isolated network namespace with only lo (loopback)β’ no other interfaces, no external connectivity β useful for batch jobs that must not touch the network. | |
docker network create -d overlay --attachable my-net | β’ Multi-host networking over VXLAN for Docker Swarm β’ requires docker swarm init even for single-node use; containers on different swarm nodes see each other as if on one LAN. | |
docker network create -d macvlan --subnet=192.168.1.0/24 -o parent=eth0 my-net | β’ Each container gets its own MAC and appears as a physical device on the parent NIC's LAN β’ Linux-only; most cloud providers block it (hypervisor MAC-spoof protection). | |
docker network create -d ipvlan --subnet=192.168.1.0/24 -o parent=eth0 my-net | β’ Like macvlan but containers share the parent's MAC (L2 mode) β’ works where macvlan is blocked, and avoids upstream-switch MAC-table exhaustion at scale. |
Table 8: Network Management
Docker networking glues containers to each other and to the outside world. The commands here create and manage user-defined networks (almost always what you want β they enable automatic container-name DNS, unlike the default bridge), connect and disconnect running containers, and reach back to the host machine from inside a container.
| Command | Example | Description |
|---|---|---|
docker network create mynet | β’ Creates a user-defined network β default driver is bridge; use -d overlay for Swarm or -d macvlan for L2β’ user-defined bridges enable automatic DNS resolution between containers by name (the default bridge network does not). | |
docker network ls | β’ Lists all networks with NETWORK ID, NAME, DRIVER, and SCOPEβ’ always includes the three predefined networks bridge, host, and none that ship with the daemon. | |
docker network connect mynet web | β’ Attaches a running container to an additional network β containers can be on multiple networks at once β’ on the primary network they resolve each other by name; on secondary networks they must use IP. | |
docker network disconnect mynet web | β’ Removes a container from a network while it is still running β no need to stop it first β’ commonly used before docker network rm to free a network that's blocking removal. | |
docker network inspect mynet | β’ Returns the full JSON config for a network: driver, IPAM Subnet/Gateway, every connected container, IP and MAC addresses, driver optionsβ’ the first stop when containers can see each other by IP but not by name. | |
docker network rm mynet | β’ Removes a user-defined network β fails with "has active endpoints" if any container is still attached β’ disconnect or stop+remove the container first, then retry. -f only ignores "no such network", it does not force-detach. | |
docker network prune | β’ Removes every unused user-defined network (no container attached) and prompts for confirmation; -f skips the prompt, --filter "until=24h" narrows by ageβ’ the predefined bridge, host, and none networks are never touched. | |
curl http://host.docker.internal:3000 | β’ Special DNS name that resolves to the host machine from inside a container β built in on Docker Desktop (Mac/Windows/WSL) β’ on Linux Docker Engine it does not exist by default; add --add-host=host.docker.internal:host-gateway to docker run (or extra_hosts in Compose). |
Table 9: Volume Management
Containers are ephemeral, but most real applications need data that outlives any single container. Docker offers three storage primitives β named volumes, bind mounts, and tmpfs β each with very different durability, portability, and host-coupling trade-offs, plus two CLI shapes (-v and --mount) whose subtle differences trip people up.
| Type | Example | Description |
|---|---|---|
docker run -v data:/app/data nginx | β’ Docker-managed storage under /var/lib/docker/volumes/, lifecycle independent of the containerβ’ preferred for production; easy to back up, share between containers, and reference by name. | |
docker run --mount type=volume,source=mydata,target=/data nginx | β’ Explicit, key-value alternative to -v that supports type=volume, type=bind, and type=tmpfsβ’ recommended for scripting because it errors on a missing bind source instead of silently creating a directory. | |
docker run -v /host/path:/container/path nginx | β’ Maps an absolute host path straight into the container β’ changes sync in real time, ideal for development; portability and permission ownership are your problem, not Docker's. | |
docker run --tmpfs /tmp nginx | β’ Stores data only in host RAM, never written to disk; removed when the container stops β’ good for caches and short-lived secrets, not for anything that must survive a restart. | |
docker run -v /app/data nginx | β’ Created automatically with a random hash name when no source is given β’ persist after the container exits unless you used --rm; accumulate quickly and are hard to identify. | |
docker run -v data:/app:ro nginx | β’ :ro (or readonly with --mount) makes the mount read-only inside the containerβ’ the host can still modify the underlying files; it is a container-side guard, not a host-side lock. | |
docker run --volumes-from web nginx | β’ Mounts all volumes from another container at their original paths β’ classic backup/restore trick; modern setups usually share a single named volume by name instead. |
Table 10: Volume Commands
Volumes are Docker's managed mechanism for persisting data outside a container's writable layer, so data survives container restarts and deletions. The docker volume subcommands let you create, inspect, and clean up that storage β and most of the gotchas live in what they don't do (auto-show usage, expose host paths on Docker Desktop, or prune named volumes by default).
| Command | Example | Description |
|---|---|---|
docker volume create mydata | β’ Creates a named volume with a chosen driver and options β’ rarely required for plain use β docker run -v mydata:/path auto-creates it. | |
docker volume ls | β’ Lists all volumes with driver and name β’ does not show which container uses each β pair with docker ps --filter volume=<name>. | |
docker volume inspect mydata | β’ Shows volume metadata including the Mountpoint β’ on Docker Desktop, that path lives inside the utility VM, not on the host filesystem. | |
docker volume rm mydata | β’ Removes a volume β’ fails if any container references it β including stopped ones (check with docker ps -a). | |
docker volume prune | β’ By default removes only unused anonymous volumes β’ use -a / --all to also delete unused named volumes (API 1.42+). |
Table 11: Resource Constraints
By default a Docker container can use as much memory and CPU as the host kernel will give it, which makes "noisy neighbor" problems and OOM cascades easy to trigger. These flags map directly onto Linux cgroup controllers (memory, CPU CFS, cpuset, pids, blkio) and let you pick between hard caps, soft reservations, relative weights, and device pinning β distinctions that decide whether a container crashes with exit 137 or simply slows down.
| Flag | Example | Description |
|---|---|---|
docker run -m 512m nginx | β’ Hard memory limit (cgroup) β’ OOM killer sends SIGKILL on breach (exit 137), suffixes: b k m g. | |
docker run --memory-reservation 256m nginx | β’ Soft limit only enforced under host memory pressure β’ must be lower than --memory to take effect; container may exceed it. | |
docker run --cpus 1.5 nginx | β’ Hard cap on total CPU time via CFS quota/period β’ 1.5 = --cpu-period=100000 + --cpu-quota=150000; kernel picks which cores. | |
docker run --cpu-shares 512 nginx | β’ Relative weight (default 1024) for CFS β not a cap β’ only honored under CPU contention; idle host = no effect. | |
docker run --cpuset-cpus 0,1 nginx | β’ Pins the container to specific physical CPUs (cores 0 and 1) β’ used for NUMA locality and cache-sensitive workloads. | |
docker run --pids-limit 100 nginx | β’ Caps total PIDs (processes + threads) via the pids cgroup β’ mitigates fork bombs; thread-heavy JVM/Python apps can hit it. | |
docker run --blkio-weight 500 nginx | β’ Relative block-I/O weight (default 500, range 10-1000) β’ effective only on schedulers that honor it (e.g., BFQ/CFQ) and under disk contention. | |
docker run --gpus all nvidia/cuda:12.0-base nvidia-smi | β’ Exposes host GPUs to the container β’ requires the NVIDIA Container Toolkit on the host; use "device=0,1" to target specific GPUs. |
Table 12: Restart Policies
Restart policies tell the Docker daemon when to bring a container back up on its own β after a crash, a host reboot, or a daemon restart. Pick the right one and a single-host stack stays available through reboots; pick the wrong one and a "stopped" container quietly comes back during maintenance.
| Policy | Example | Description |
|---|---|---|
docker run --restart no nginx | β’ Never restart container automatically β’ manual docker start still works. | |
docker run --restart on-failure:3 nginx | β’ Restarts only on non-zero exit code β’ optional :N cap; not triggered by daemon restart. | |
docker run --restart always nginx | β’ Always restarts, including after daemon restart β’ brings back even manually-stopped containers on reboot. | |
docker run --restart unless-stopped nginx | β’ Like always but respects manual stops across daemon restartsβ’ preferred for single-host production stacks. |
Table 13: Health Checks
Docker can probe a running container with a periodic command and surface a healthy / unhealthy / starting state on top of the normal running state. Set the probe in the image via the HEALTHCHECK Dockerfile instruction, or attach/override it at runtime with docker run --health-* flags. The health state shows up in docker ps and docker inspect, but Docker itself does not restart unhealthy containers β that's the orchestrator's (Swarm/Compose with condition: service_healthy/Kubernetes) job.
| Option | Example | Description |
|---|---|---|
HEALTHCHECK --interval=30s CMD curl -f http://localhost/|| exit 1 | β’ Dockerfile instruction defining the probe baked into the image β’ exit 0 = healthy, 1 = unhealthy, 2 is reservedβ’ only the last HEALTHCHECK in a Dockerfile takes effect; HEALTHCHECK NONE disables one inherited from the base image. | |
docker run --health-cmd "curl -f http://localhost/" nginx | β’ Runtime override that attaches (or replaces) the probe command without rebuilding the image β’ useful for ad-hoc testing or images shipped without a HEALTHCHECK. | |
docker run --health-interval=10s nginx | β’ Wait time between checks (after the previous one completes), default 30sβ’ the first check also runs one interval after container start. | |
docker run --health-timeout=5s nginx | β’ Max time for a single check to complete, default 30sβ’ if exceeded, the probe is SIGKILL-ed and that run counts as a failure. | |
docker run --health-retries=3 nginx | β’ Number of consecutive failures needed to flip the state to unhealthy, default 3β’ one successful check resets the failing streak to zero. | |
docker run --health-start-period=60s nginx | β’ Initialization grace window, default 0s β checks still run during it, but failures do not count toward --health-retriesβ’ any single success ends the start period early. |
Table 14: Docker Compose Services
How each services: entry is configured β the attributes that decide what runs, how it reaches the network, what it depends on, and how the platform treats it. Most startup-order, port, and resource bugs in Compose stacks trace back to misreading one of these keys.
| Attribute | Example | Description |
|---|---|---|
image: nginx:alpine | β’ Names the image to run β’ pulled from the registry if not present locally. | |
build: context: . dockerfile: Dockerfile.prod | β’ Builds an image from a Dockerfile β’ context is resolved relative to the Compose file's directory, not the shell's cwd. | |
ports: - "8080:80" | β’ Publishes ports as "HOST:CONTAINER"β’ always quote short syntax β YAML parses unquoted xx:yy as a base-60 number. | |
volumes: - ./data:/data:ro | β’ Mounts volumes or bind mounts β’ trailing :ro mounts the path read-only inside the container. | |
environment: NODE_ENV: production | β’ Sets runtime environment variables β’ only Compose's ${VAR} interpolation expands β a literal $BAR is passed through, not shell-expanded. | |
depends_on: db: condition: service_healthy restart: true required: false | β’ Controls startup order; default service_started only waits for the container to startβ’ service_healthy waits for the dependency's healthcheck to passβ’ restart: true restarts the dependent if the dependency restarts; required: false allows startup even if the dependency is unavailable. | |
networks: - frontend | β’ Attaches the service to named networks β’ inside a shared network, services reach each other by service name on the container port. | |
restart: unless-stopped | β’ Sets the container restart policy β’ options: no (default), always, on-failure[:N], unless-stopped. | |
command: npm run dev | β’ Overrides the image's CMD onlyβ’ the image's ENTRYPOINT still runs and receives this as its arguments. | |
entrypoint: /app/entrypoint.sh | β’ Replaces the image's ENTRYPOINT entirelyβ’ setting it does not clear the image's CMD, which is still passed as arguments. | |
healthcheck: test: ["CMD", "curl", "-f", "http://localhost/"] interval: 30s start_interval: 2s | β’ Defines a container health probe β’ CMD execs the args directly; CMD-SHELL wraps in /bin/sh -c so operators like || workβ’ start_interval sets a faster check rate during start_period so dependent services start sooner. | |
deploy: resources: limits: memory: 512M | β’ Most keys ( replicas, placement, update_config) are Swarm-only and ignored by docker compose upβ’ deploy.resources for limits and GPU reservations does apply to plain Compose. |
Table 15: Docker Compose Commands
The Compose CLI manages multi-container apps defined in a compose.yaml file as a single Compose project β a scope Compose tracks by project name. Note: the legacy docker-compose (v1, hyphenated) was permanently removed in April 2025; only docker compose (space, no hyphen) works. Knowing what each command actually mutates (containers, networks, volumes, images) is the difference between a clean restart and accidentally deleting your database.
| Command | Example | Description |
|---|---|---|
docker compose up -d | β’ Builds, (re)creates, starts all services and their networks β’ -d detaches; recreates containers whose config changed since last up. | |
docker compose down -v | β’ Stops and removes containers and the project's networks β’ Keeps named volumes by default; -v also removes named volumes (data loss). | |
docker compose ps | β’ Lists running containers for the current Compose project β’ add -a for stopped ones. | |
docker compose logs -f web | β’ Shows aggregated logs from services β’ -f follows; pass a service name to filter to one. | |
docker compose exec web sh | β’ Runs a command inside a running service container β’ allocates a TTY by default; --index picks a replica. | |
docker compose build --no-cache | β’ Builds or rebuilds service images from each service's build:β’ --no-cache discards the build cache; pair with --pull to refresh base images. | |
docker compose pull | β’ Pulls images for services from their registries β’ does not start containers. | |
docker compose restart web | Restarts the existing containers without re-reading the Compose file β config edits do not apply (use up -d instead). | |
docker compose stop | β’ Stops services without removing containers, networks, or volumes β’ faster than down; resume with start. | |
docker compose start | β’ Starts previously stopped containers for the project β’ never creates new containers β use up for that. | |
docker compose run --rm web npm test | β’ Runs a one-off command in a new container based on the service β’ --rm removes it after exit; starts linked services unless --no-deps. | |
docker compose watch | β’ Reacts to file changes declared under develop.watchβ’ actions: sync, rebuild, sync+restart (modern replacement for bind-mount-and-restart). |
Table 16: Docker Compose Advanced Features
Compose's advanced primitives go beyond a basic compose.yaml: profiles toggle optional services per environment, extends/include/override files compose larger stacks out of smaller pieces, secrets and configs mount files instead of leaking env vars, develop.watch keeps containers in sync with source changes, and the models top-level element declares AI/ML model dependencies alongside services.
| Feature | Example | Description |
|---|---|---|
profiles: [debug] | β’ Groups services for selective activation β’ docker compose --profile debug up only starts debug services. | |
extends: file: common.yml service: base | β’ Inherits configuration from another service β’ enables reusable base definitions. | |
docker-compose.override.yml | β’ Automatically merged with docker-compose.ymlβ’ environment-specific overrides without modifying base file. | |
include: - monitoring.yml - oci://docker.io/org/stack:latest | β’ Includes separate Compose files or OCI artifacts to combine projects β’ β οΈ update to v2.40.2+ if using OCI includes β CVE-2025-62725 path-traversal fix. | |
env_file: - .env.prod | β’ Loads environment variables from files β’ keeps secrets out of Compose file. | |
secrets: - db_password | β’ Injects secrets as files in container β’ mounted at /run/secrets/. | |
configs: - nginx.conf | β’ Like secrets but for non-sensitive config files β’ also mounted as files. | |
develop: watch: - action: sync path: ./src target: /app/src - action: rebuild path: package.json | β’ Configures hot-reload for development (formerly x-develop β drop the x- prefix)β’ actions: sync (copy files), rebuild (rebuild image), sync+restart (copy and restart)β’ initial_sync syncs all matching files immediately on docker compose watch start. | |
models: llm: model: ai/smollm2 context_size: 4096 | β’ Top-level element declaring AI/ML model dependencies as OCI artifacts alongside services β’ platform (e.g. Docker Model Runner) injects <NAME>_URL and <NAME>_MODEL env vars into consuming services; portable across cloud platforms. | |
x-common: &common restart: alwaysservices: web: <<: *common | β’ Reuses config blocks with anchors and aliases β’ x- prefix defines extension fields that Compose ignores. | |
deploy: resources: reservations: devices: - driver: nvidia count: 1 capabilities: [gpu] | β’ Requests GPU access for a service (NVIDIA and AMD supported) β’ requires NVIDIA Container Toolkit or AMD ROCm driver on host. |
Table 17: Registry and Authentication
Authenticating to a Docker registry sets up the credentials that later push and pull commands silently reuse, so the way you log in directly shapes how exposed those secrets are. This table covers the day-to-day commands and the two safer non-interactive patterns to prefer over -p.
| Command | Example | Description |
|---|---|---|
docker login registry.example.com | β’ Authenticates to a registry and caches credentials for later push/pullβ’ stores them via the configured credential helper, or base64-encoded in ~/.docker/config.json as a fallback. | |
docker logout registry.example.com | β’ Removes the locally stored credential for the given server (or the default registry) β’ does not revoke the token on the registry β rotate it there if it may have leaked. | |
docker login -u user -p pass | β’ Non-interactive login with the password as an argument β’ avoid β leaks into shell history and ps; Docker prints WARNING! Using --password via the CLI is insecure. | |
echo $TOKEN | docker login -u user --password-stdin | β’ Reads the password or PAT from stdin so it never appears in history or process listings β’ the recommended pattern for CI and short-lived cloud tokens (ECR, GCR, ACR). |
Table 18: Image Tagging Strategies
A Docker tag is just a mutable, human-readable pointer β docker tag a b creates an alias to the same image ID, and any tag (including latest) can be reassigned later. Choosing a tagging convention is really choosing how much version, source, and environment information you bake into that pointer so future-you can answer "what is actually running?" without guessing.
| Strategy | Example | Description |
|---|---|---|
myapp:1.2.3 | β’ Uses major.minor.patch format β’ best practice for release tracking and rollbacks. | |
myapp:a3f2c1b | β’ Tags with Git commit hash β’ enables exact source code traceability. | |
myapp:prod-1.2.3 | β’ Includes environment prefix β’ clearly indicates deployment target. | |
myapp:2026-03-01 | β’ Timestamps with YYYY-MM-DD β’ useful for nightly builds or time-based releases. | |
myapp:feature-auth | β’ Tags with branch name β’ tracks feature development images. |
Table 19: Cleanup and Maintenance
Cleanup commands reclaim disk space, but each one targets a different scope and several carry real data-loss risk if used carelessly. Knowing what each prune does and does not touch β especially --volumes, -a, and the until= filter β is the difference between a tidy host and an outage.
| Command | Example | Description |
|---|---|---|
docker system prune -a | β’ Removes stopped containers, unused networks, dangling images, and unused build cache β’ -a also removes any image not used by a container; volumes are NOT included unless --volumes is passed. | |
docker image prune -a --filter "until=168h" | β’ Without -a removes only dangling images (untagged, <none>)β’ -a removes all unused images; --filter "until=168h" keeps images created in the last 7 days. | |
docker container prune | β’ Removes all stopped containers and their writable layers β’ running containers are untouched; prompts before deletion unless -f. | |
docker volume prune | β’ Deletes unused volumes (any volume not attached to a container) β’ Data-loss risk β back up first, and remember docker system prune does NOT touch volumes by default. | |
docker network prune | β’ Removes unused custom networks β’ built-in networks ( bridge, host, none) are never pruned. | |
docker builder prune | β’ Clears the BuildKit build cache for the active builder β’ does not touch images or containers; next build rebuilds layers from scratch. |
Table 20: Logging Drivers
Docker streams every container's stdout/stderr through a logging driver, and the choice between the default json-file driver and alternatives like local, journald, or remote forwarders shapes disk usage, queryability, and how logs reach a central pipeline.
| Driver | Example | Description |
|---|---|---|
--log-driver json-file | β’ Stores logs as JSON on disk β’ queryable with docker logs, no rotation by default β set max-size/max-file to avoid filling /var/lib/docker. | |
--log-driver local | β’ Optimized local file driver with automatic log rotation and compression by default β’ Docker's recommended local driver; now supports label, env, and tag log options (Engine 29.5+). | |
--log-driver syslog --log-opt syslog-address=udp://host:514 | β’ Forwards logs to a syslog daemon over UDP/TCP/TLS β’ integrates with centralized logging. | |
--log-driver journald | β’ Sends logs to the systemd journal (Linux only) β’ query with journalctl CONTAINER_NAME=foo. | |
--log-driver fluentd --log-opt fluentd-address=host:24224 | β’ Forwards to a Fluentd collector β’ popular for Kubernetes and centralized logging. | |
--log-driver awslogs --log-opt awslogs-group=myapp | β’ Sends logs to AWS CloudWatch Logs β’ credentials come from the daemon/host (EC2 instance profile or ECS task role), not container env vars. | |
--log-driver gcplogs | β’ Forwards to Google Cloud Logging β’ auto-detects project, zone, and instance from the GCE metadata server. | |
--log-driver splunk --log-opt splunk-token=XXX --log-opt splunk-url=https://host:8088 | β’ Sends logs to the Splunk HTTP Event Collector β’ enterprise logging solution. |
Table 21: Security Practices
Container security is layered defense: drop privileges, shrink the attack surface, and constrain what the kernel will let the container do. These practices stack β running as non-root, dropping capabilities, applying a seccomp profile, and starting from a minimal base image each close a different escape path, and together they're what stands between a single application bug and host compromise.
| Practice | Example | Description |
|---|---|---|
USER node | β’ Creates and switches to non-root user β’ prevents privilege escalation attacks. | |
docker run --read-only nginx | β’ Makes container filesystem immutable β’ prevents tampering; use tmpfs for writable dirs. | |
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE nginx | β’ Removes Linux capabilities β’ principle of least privilege β drop ALL then add only what's needed. | |
RUN --mount=type=secret,id=token | β’ Never hardcode secrets in images β’ use BuildKit secrets or runtime secrets. | |
docker scout cves nginx:latest | β’ Scans for vulnerabilities β’ integrates with Docker Scout, Trivy, Snyk. | |
FROM gcr.io/distroless/static | β’ Use distroless or alpine β’ fewer packages = smaller attack surface. | |
Avoid --privileged | β’ Never use in production β’ gives full host access, defeats containerization. | |
--security-opt seccomp=profile.json | β’ Apply seccomp/AppArmor/SELinux profiles β’ restricts syscalls and actions. | |
docker run --security-opt no-new-privileges nginx | β’ Prevents processes from gaining additional privileges via setuid/setgid β’ critical for defense in depth. | |
dockerd-rootless-setuptool.sh install | β’ Runs Docker daemon without root privileges β’ mitigates potential vulnerabilities in daemon and container runtime; Engine 29.5+ uses gvisor-tap-vsock as the default rootless network driver. | |
FROM dhi.io/python:3.12 | β’ Docker's distroless-based, CVE-free base images β’ free since Dec 2025, auto-patched within 24hrs, include SBOM and provenance attestations; manage via docker dhi CLI. |
Table 22: Signal Handling
How Docker delivers Unix signals to your container's PID 1 β and why a misplaced shell wrapper or a too-short grace period quietly turns "graceful shutdown" into data corruption. These rows cover the signals Docker actually sends, who receives them, and the form choices that decide whether your app ever gets a chance to clean up.
| Signal | Example | Description |
|---|---|---|
Sent by docker stop | β’ Graceful shutdown signal delivered to the container's PID 1 β’ after a grace period (default 10s on Linux, 30s on Windows), Docker follows up with SIGKILL. Tune with -t / --stop-timeout. | |
Sent after grace period, or by docker kill | β’ Force kill signal β kernel-enforced, cannot be caught, blocked, or ignored β’ immediate termination with no cleanup. | |
Ctrl+C in attached mode | β’ Interrupt signal sent to PID 1 β’ most apps treat it like SIGTERM and exit, so Ctrl+C while attached typically stops the container. | |
docker kill -s SIGHUP web | β’ Hangup signal β historically "controlling terminal closed" β’ many daemons (nginx, HAProxy) repurpose it to reload configuration without restarting. | |
CMD ["app"] vs CMD app | β’ Exec form (JSON array): the app IS PID 1 and receives signals directly β’ shell form wraps in /bin/sh -c, sh becomes PID 1 and does not forward signals β the app never sees SIGTERM. |
Table 23: Context and Remote Docker
A Docker context bundles the endpoint URL, TLS material, and name of one daemon so a single docker CLI can manage many daemons β local Docker Desktop, an SSH-reachable production server, an ECS endpoint β and switch between them. SSH-based contexts are the canonical secure pattern for remote control because they reuse your SSH keys and avoid exposing the Docker daemon socket on a public TCP port.
| Command | Example | Description |
|---|---|---|
docker context create prod --docker "host=ssh://user@host" | β’ Registers a named connection to a Docker daemon (local, tcp://, or ssh://)β’ metadata is stored under ~/.docker/contexts/. | |
docker context use prod | β’ Sets the active context in ~/.docker/config.jsonβ’ persists across shells until changed or overridden by DOCKER_HOST / DOCKER_CONTEXT / --context. | |
docker context ls | β’ Lists every context with its DOCKER ENDPOINT URLβ’ the active one is marked with *. | |
docker context rm prod | β’ Removes a context β’ fails on the active context unless you pass -f / --force or docker context use default first. | |
export DOCKER_HOST=ssh://user | β’ Per-shell daemon-socket override β’ beats the active context but is itself overridden by DOCKER_CONTEXT and --host / --context. |
Table 24: Docker Swarm Basics
Swarm mode is the orchestrator built directly into the Docker Engine β no separate install needed. One docker swarm init turns the current engine into a single-node cluster (a manager), and additional engines join as workers or managers via a join token. From there you create services (replicated containers spread across the cluster) and stacks (a whole Compose file deployed as a unit), and the managers schedule tasks, run rolling updates, and keep the desired replica count alive on the routing mesh.
| Command | Example | Description |
|---|---|---|
docker swarm init | β’ Turns the current Docker Engine into a single-node Swarm cluster β’ the current node becomes the leader manager. | |
docker swarm join --token TOKEN host:2377 | β’ Joins a node to an existing Swarm β’ the token used (worker or manager) determines the role of the joining node. | |
docker service create --replicas 3 --name web nginx | β’ Creates a new Swarm service distributed across the cluster β’ --replicas N declares the desired task count the schedulers keep alive. | |
docker service scale web=5 | β’ Scales an already-running replicated service to a new replica count β’ cannot be used on global-mode services. | |
docker service update --image nginx:1.21 web | β’ Applies a rolling update β by default updates 1 task at a time, controlled by --update-parallelism and --update-delayβ’ supports --rollback on failure. | |
docker node ls | β’ Lists every node the Swarm manager knows about, with status, availability, and manager status β’ only runs on a manager node. | |
docker stack deploy -c compose.yml myapp | β’ Deploys a Compose file (v3.0+) as a Swarm stack β creating its services, networks, and volumes β’ build: is ignored β images must already exist in a registry. |
Table 25: Environment Variables
Docker lets you inject configuration into containers through several distinct channels β runtime CLI flags, files, Dockerfile baked-in values, build-time-only arguments, and Compose declarations. Picking the right one matters: some persist into the image (visible in docker history), some live only during the build, and none of them are a safe place for secrets.
| Method | Example | Description |
|---|---|---|
docker run -e NODE_ENV=prod nginx | β’ Sets single runtime variable at container start β’ visible in docker inspect, so unsuitable for secrets. | |
docker run --env-file .env nginx | β’ Loads variables from a file, one VAR=value per lineβ’ # starts a line comment; no shell-style $VAR interpolation. | |
ENV NODE_ENV=production | β’ Bakes a variable into the image for build AND runtime β’ persists in every container; bad for secrets (visible in docker history). | |
ARG VERSION=1.0 | β’ Build-time only, passed with --build-argβ’ not in the final image's runtime env, but still visible in docker history. | |
environment: NODE_ENV: prod | β’ Sets variables on a service via list or map syntax β’ supports ${VAR} interpolation from host shell or project .env file. | |
env_file: webapp.env | β’ Loads container env from one or more external files β’ later files override earlier ones; distinct from the project .env used for ${VAR} interpolation. |
Table 26: Inspect and Debug
Once a container is running you need ways to look inside it, watch what the daemon is doing, see where your disk went, and get a shell into images that don't have one. This table covers the broader Docker inspect family β the --format Go template idiom for scripting, the system-level views (events, df, info, version), and Docker Desktop's debug and init helpers.
| Command | Example | Description |
|---|---|---|
docker inspect --format '{{.State.Status}}' web | β’ Returns low-level JSON config for any Docker object β’ pair with --format Go templates to extract one field (canonical scripting pattern). | |
docker events --since 1h --filter type=container | β’ Continuous stream of daemon lifecycle events (create, start, die, kill, oom, etc.) β’ bound it with --since/--until and --filter or it blocks forever. | |
docker system df -v | β’ Reports Docker-managed disk usage across images, containers, volumes, and build cache β’ -v adds a per-item reclaimable breakdown. | |
docker system info | β’ Shows runtime configuration β storage driver, cgroup driver, kernel version, containerd/runc versions, container counts β’ aliased as docker info. | |
docker version | Prints client and server version numbers, the Engine API version, and component versions (containerd, runc, docker-init). Different from docker info. | |
docker debug web | β’ Attaches a debug shell with its own toolbox (vim, htop, curl, plus Nix packages) to any container or image, even distroless/scratch with no shell β’ Docker Desktop only, paid subscription required. | |
docker init | β’ Scaffolds Dockerfile, compose.yaml, .dockerignore, README.Docker.md for a new project β’ templates for Go, Node, Python, Rust, Java, PHP, ASP.NET Core. |
Table 27: Copy Operations
How to move files in and out of containers with docker cp β a one-shot snapshot copy (not a live sync like a bind mount) that works on both running and stopped containers, making it the right tool for post-mortem retrieval and surgical config injection.
| Command | Example | Description |
|---|---|---|
docker cp web:/app/log.txt ./log.txt | β’ Copies file from container to host β’ works on running and stopped containers. | |
docker cp ./config.yml web:/app/config.yml | β’ Copies file from host to container β’ immediately available in running container. | |
docker cp web:/app/logs ./logs | Recursively copies entire directories (no -r flag β recursion is the default). | |
docker cp -a web:/app ./backup | β’ Preserves UID/GID and permissions β’ equivalent to cp -a. |
Table 28: BuildKit Advanced Features
BuildKit unlocks the modern Docker build pipeline: persistent caches that survive between builds, secret and SSH credentials that never touch image layers, attestations that prove what shipped, and Bake for orchestrating multi-target build matrices.
| Feature | Example | Description |
|---|---|---|
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt | β’ Mounts a persistent package-manager cache for one RUN stepβ’ data lives in the builder, not in image layers, and is reused across builds. | |
RUN --mount=type=ssh git clone git:repo(invoke with docker build --ssh default) | β’ Forwards the host's SSH agent socket into a single RUN stepβ’ lets builds clone private Git repos without a key entering the image. | |
RUN --mount=type=bind,target=. go build -o /app/hello | β’ Mounts build-context files into the step without COPYβ’ files are read-only by default and never enter image layers or the cache. | |
docker buildx build --cache-from type=registry,ref=user/app:buildcache --cache-to type=registry,ref=user/app:buildcache,mode=max . | β’ Pushes/pulls build cache to a remote location (registry, S3, GHA) β’ lets ephemeral CI runners share cache and stay fast. | |
docker buildx build --cache-to type=inline --cache-from <image> -t app . | β’ Embeds cache metadata inside the published image itself β’ simplest registry-backed cache, but only supports mode=min. | |
docker buildx build --sbom=true -t myapp . | β’ Attaches an SPDX Software Bill of Materials as an OCI attestation β’ lists packages found in the image so scanners (Scout, Trivy) can flag CVEs. | |
docker buildx build --provenance=mode=max -t myapp . | β’ Attaches a SLSA-format provenance record proving what source, frontend, and parameters produced the image β’ mode=max adds the Dockerfile and LLB; mode=min is the default. | |
docker buildx bake -f docker-bake.hcl(HCL defines target and group blocks) | β’ Runs multiple build targets concurrently from an HCL/JSON/Compose file β’ supports variables, inheritance, and matrix targets for monorepos and multi-arch fan-out. |
Table 29: Docker Scout Commands
Docker Scout is Docker's built-in supply-chain security tool: it reads an image's SBOM (generating one if missing), looks up known CVEs against it, and suggests safer base images. These CLI commands are the day-to-day surface β triaging vulnerabilities, comparing image versions, and enrolling an organization for policy enforcement.
| Command | Example | Description |
|---|---|---|
docker scout cves nginx:latest | β’ Scans an image for CVEs β’ shows severity, CVSS score, affected package, and fix availability. | |
docker scout quickview nginx:latest | β’ Displays a summary of vulnerabilities and policy compliance β’ fast overview without printing the full CVE list. | |
docker scout recommendations nginx:latest | β’ Suggests base image refresh or update β’ shows benefits like fewer CVEs and smaller image size for each alternative. | |
docker scout sbom nginx:latest | β’ Generates a Software Bill of Materials β’ lists every package and version (SPDX or CycloneDX output adds licenses and relationships). | |
docker scout compare nginx:1.25 --to nginx:latest | β’ Compares vulnerability profiles of two image versions β’ canonical way to verify a base image bump actually reduced CVEs. | |
docker scout enroll myorg | β’ Enrolls an organization in Docker Scout β’ required before policy enforcement, repository integration, and team dashboards work for org images. |
Table 30: Docker Model Runner
Docker Model Runner (DMR) is a Docker Desktop / Docker Engine feature for pulling, running, and serving local AI models with a docker model CLI that mirrors familiar image commands. Models are stored as OCI artifacts separately from container images, run on a host-native inference server (llama.cpp by default), and are reachable over OpenAI-, Anthropic-, and Ollama-compatible HTTP APIs. As of Docker Desktop 4.71, DMR is disabled by default and must be explicitly enabled in Settings.
| Command | Example | Description |
|---|---|---|
docker model pull ai/llama3.2 | β’ Downloads a model from Docker Hub, an OCI registry, or Hugging Face β’ stored locally as OCI artifacts in a separate model store (not in docker images). | |
docker model run ai/llama3.2 | β’ Runs a one-time prompt or starts an interactive chat in the terminal β’ the model is loaded on demand and unloaded after ~5 min idle. | |
docker model run -d ai/llama3.2 | β’ Pre-loads the model into memory without an interactive session β’ the OpenAI-compatible REST API is always served by Model Runner β -d just warms the cache. | |
docker model list | Lists locally pulled models with size, parameters, and quantization (alias: docker model ls). | |
docker model rm ai/llama3.2 | Removes a model from the local model store to reclaim disk space. | |
curl http://model-runner.docker.internal/engines/v1/chat/completions | β’ Reach the running model via OpenAI-, Anthropic-, or Ollama-compatible endpoints (including /responses for the OpenAI Responses API)β’ from containers use model-runner.docker.internal; from the host use http://localhost:12434/engines/v1. |
Table 31: Docker Build Cloud
Docker Build Cloud is a paid Docker subscription add-on that runs buildx builds on a managed BuildKit instance in AWS (US East), with a shared persistent build cache and native linux/amd64 + linux/arm64 nodes. Your CLI sends the build context to the remote builder; the resulting image streams back to your local image store or is pushed to a registry. The workflow is a builder swap β same Dockerfile, same docker buildx build.
| Feature | Example | Description |
|---|---|---|
docker buildx create --driver cloud myorg/mybuilder | β’ Registers a local endpoint for an existing cloud builder (the builder itself is provisioned in the Docker Build Cloud Dashboard) β’ the local endpoint is named cloud-myorg-mybuilder. | |
docker buildx build --builder cloud-myorg-mybuilder -t myapp . | β’ Sends the build context to the remote builder β’ build runs on AWS EC2 with more CPU/RAM than the laptop, then result is loaded back or pushed to a registry. | |
docker buildx use cloud-myorg-mybuilder --global | β’ Sets the cloud builder as the default for docker buildx buildβ’ --global persists the selection across shells; affects docker buildx build only, not the legacy docker build. | |
docker buildx ls | β’ Lists all builder instances with their driver, endpoint, status, BuildKit version, and supported platforms β’ the current default is marked with a *. | |
(automatic; see docker buildx du) | β’ Each cloud builder has a dedicated EBS volume holding a persistent BuildKit cache shared by everyone using that builder β’ the first teammate's build warms the cache; subsequent local and CI builds reuse it, so cold starts on fresh runners stop paying full rebuild cost. | |
docker buildx build --builder cloud-myorg-mybuilder --platform linux/amd64,linux/arm64 -t myapp --push . | β’ The cloud builder has native linux/amd64 and linux/arm64 nodesβ’ each platform runs on its real CPU in parallel with no QEMU emulation overhead β typically much faster than emulated cross-builds on a single-arch laptop or CI runner. |
Table 32: Compose Dependency Conditions
The depends_on long syntax accepts a condition that controls when Compose considers a dependency satisfied before starting the dependent service. Picking the right condition is how you turn a fragile "container is up" hint into a real readiness gate β or a one-shot migration step.
| Condition | Example | Description |
|---|---|---|
depends_on: db: condition: service_started | β’ Default behavior β waits only for the dependency container to be started β’ does not wait for the app inside to be ready, so first connections can still fail. | |
depends_on: db: condition: service_healthy | β’ Waits for the dependency's healthcheck to report healthyβ’ requires a HEALTHCHECK in the image or a healthcheck: block; without one, the dependent never starts. | |
depends_on: migrate: condition: service_completed_successfully | β’ Waits for a one-off dependency to exit with code 0 β’ canonical "run migrations first" pattern; non-zero exit blocks the dependent. |
Table 33: Distroless and Minimal Images
Choosing a smaller base image shrinks the attack surface, the CVE footprint, and the pull/startup time β but each minimal base trades away something. This table compares the common minimal-base options so you can pick by what your app actually needs at runtime (a shell, a libc, a package manager, none of the above).
| Image | Example | Description |
|---|---|---|
FROM alpine:3.21 | β’ Lightweight ~5 MB base β’ uses musl libc (not glibc), so prebuilt Python/Node binary wheels and other glibc-linked binaries may fail or need recompiling. | |
FROM gcr.io/distroless/static-debian12 | β’ No shell, no package manager β only your app and its runtime deps β’ static is ~2 MB, ~50% of alpine's size; reduces attack surface and CVE noise. | |
FROM scratch | β’ Completely empty base β no libc, no shell, no files β’ works only for statically linked binaries (e.g. Go with CGO_ENABLED=0, Rust with a musl target). | |
FROM gcr.io/distroless/base-debian12:debug | β’ Adds a busybox shell on top of distroless so you can docker run --entrypoint=shβ’ intended for local debugging, never production. | |
FROM dhi.io/python:3.13 | β’ Docker's distroless-based, near-zero-CVE images on alpine or debian foundations β’ free under Apache 2.0 since Dec 17 2025, ship with SBOM + SLSA provenance attestations, patched on a tight SLA. |
Table 34: Docker AI (Gordon)
Gordon is Docker's AI-powered assistant available from Docker Desktop 4.74+ and the docker ai CLI. It reads your live Docker environment β running containers, logs, images, Compose files β proposes actions, and executes them only after your approval. Gordon on Docker Hub and docs.docker.com is free with no Docker account required; CLI and Docker Desktop usage counts against a usage plan.
| Command | Example | Description |
|---|---|---|
docker ai | β’ Opens an interactive terminal UI for Gordon β’ type questions or tasks; Gordon proposes actions and waits for y approval before executing. | |
docker ai "show me logs from my nginx container" | β’ Runs a one-off prompt without the full TUI β’ Gordon reads the environment, proposes relevant commands (e.g. docker logs), and runs them on approval. | |
docker ai "review my Dockerfile for best practices" | β’ Analyzes the Dockerfile in the current directory and suggests optimizations: smaller base, layer order, cache hits, secret handling β’ Gordon can apply the edits in-place. | |
docker ai "why did my db container crash" | β’ Reads container logs and inspect output, diagnoses the root cause, and suggests a fix β’ any proposed docker commands shown before execution. | |
(Docker Desktop sidebar β Gordon) | β’ Same capabilities as CLI Gordon but with a graphical session sidebar β’ lets you link a project directory and run queries with richer visual output. |
Table 35: Docker MCP Toolkit
The Docker MCP Toolkit (docker mcp) makes it trivial to install, run, and connect 120+ containerized Model Context Protocol (MCP) servers β GitHub, Playwright, Slack, Grafana, and more β to AI clients such as Claude Desktop, Cursor, VS Code, and Gordon. Each server runs in an isolated container with Docker's security model. Requires Docker Desktop 4.62+.
| Command | Example | Description |
|---|---|---|
docker mcp profile create --name web-dev | β’ Creates a named profile β a workspace that organizes a set of MCP servers β’ profiles are the unit of sharing; push/pull via docker mcp profile push/pull <oci-ref>. | |
docker mcp profile server add web-dev --server catalog://mcp/docker-mcp-catalog/github-official | β’ Adds a server to a profile using a catalog URI ( catalog://), Docker image URI (docker://), local YAML (file://), or HTTPS registry URLβ’ servers requiring OAuth show "Configuration Required" in Docker Desktop. | |
docker mcp gateway run --profile web-dev | β’ Starts the MCP Gateway over stdio with the given profile's serversβ’ used to connect any AI client manually via its MCP JSON config ( "command": "docker", "args": ["mcp", "gateway", "run", "--profile", "web-dev"]). | |
docker mcp client connect vscode --profile my-project | β’ Connects a named supported client (claude, cursor, vscode, etc.) to a profile β’ writes the appropriate client-specific config file (e.g. .vscode/mcp.json). | |
docker mcp catalog server ls mcp/docker-mcp-catalog | β’ Lists all servers in the Docker MCP Catalog (or a custom catalog) by name and ID β’ the Server ID is used in catalog://mcp/docker-mcp-catalog/<server-id> URIs. | |
docker mcp profile list | β’ Lists all local profiles β’ use docker mcp profile show <id> for servers and config in one profile | |
docker mcp profile export web-dev .docker/mcp-profile.json | β’ Exports a profile to a JSON file for version-control sharing with teammates β’ credentials are excluded; recipients configure secrets separately after docker mcp profile import. |
Table 36: Docker DHI CLI
The docker dhi CLI plugin (Docker Desktop 4.65+) manages Docker Hardened Images: browse the catalog, view SBOM/provenance attestations, mirror images into your organization's registry, and create customized variants that add your own packages on top of a DHI base. A standalone dhictl binary is also available for headless CI environments.
| Command | Example | Description |
|---|---|---|
docker dhi catalog list --filter golang | β’ Lists available DHI images; filter by name, --fips, or --stigβ’ docker dhi catalog get golang shows available tags and CVE counts for a specific image. | |
docker dhi attestation sbom dhi/nginx:1.27 | β’ Displays the SPDX SBOM attached to a DHI image as an OCI attestation β’ docker dhi attestation list dhi/nginx:1.27 shows all attestation types including provenance. | |
docker dhi mirror start --org my-org dhi/golang,my-org/dhi-golang | β’ Begins automatically mirroring a DHI image into your Docker Hub organization registry β’ --dependencies also mirrors base layers; Docker patches the mirror on its SLA. | |
docker dhi mirror list --org my-org | Lists all DHI images currently mirrored to your organization with their status. | |
docker dhi customization prepare golang 1.25 --org my-org --destination my-org/dhi-golang> my-customization.yaml | β’ Generates a YAML scaffold for creating a custom variant of a DHI image β’ edit the YAML to add packages or configuration, then docker dhi customization create. | |
docker dhi customization create my-customization.yaml --org my-org | β’ Submits the customization YAML to Docker to build a custom DHI variant and push it to your org registry β’ docker dhi customization build logs <id> <build-id> streams the build output. | |
docker dhi auth apk | β’ Generates enterprise package repository credentials for installing Docker-patched packages in your own images β’ apk for Alpine-based images, deb for Debian-based images. |