Skip to content

Cheat sheet: Docker

Docker and Compose commands explained flag by flag, including pipe combos like docker ps -a | grep.

Index
  • #cheatsheet
  • #docker
Updated

Also:docker cli · compose · containers · docker ps · docker logs

Each entry shows the command, a copy button, and what every part does: sub-command, flag, pipe, redirect and placeholder, in the order they appear. <placeholders> are the bits you replace.

120 items
Click a command to see what each part does.

Basics: images & containers11

  • docker version; docker infoIs Docker installed and running?

    What each part does

    1. docker versionclient and server (daemon) versions; an error on Server means the daemon is not running
    2. docker infosystem-wide details: containers, images, storage driver, cgroup driver
  • docker run --rm hello-worldTest that everything works

    What each part does

    1. docker runcreate and start a container (pulls the image if missing)
    2. --rmremove the container when it exits
    3. hello-worldtiny test image that prints a greeting
  • docker imagesList local images

    What each part does

    1. docker imagesalias of docker image ls: repository, tag, image ID, size
  • docker pull <image>:<tag>Download an image

    What each part does

    1. docker pulldownload from a registry (Docker Hub by default)
    2. <image>:<tag>e.g. nginx:1.27; without a tag it means :latest
  • docker ps; docker ps -aList running / all containers

    What each part does

    1. docker psrunning containers
    2. -ainclude stopped ones
  • docker start <container>; docker stop <container>; docker restart <container>Start, stop, restart a container

    What each part does

    1. startstart a stopped container (keeps its data and settings)
    2. stopgraceful stop: SIGTERM, then SIGKILL after 10s (-t to change)
    3. restartstop then start
  • docker rm <container>Remove a containerCaution

    What each part does

    1. docker rmdelete a stopped container; add -f to stop and delete a running one
  • docker rmi <image>:<tag>Remove an imageCaution

    What each part does

    1. docker rmidelete a local image; -f forces it even if tagged elsewhere
  • docker rename <old-name> <new-name>Rename a container

    What each part does

    1. docker renamechange the container name
  • docker port <container>Which host port maps to the container?

    What each part does

    1. docker portlist port mappings, e.g. 80/tcp -> 0.0.0.0:8080
  • docker login <registry>; docker logout <registry>Log in / out of a registry

    What each part does

    1. docker loginstore credentials (Docker Hub if no registry is given)
    2. docker logoutremove them

Volumes & networks4

  • docker volume ls; docker volume create <name>; docker volume rm <name>List / create / remove volumesCaution

    What each part does

    1. volume lsnamed volumes (persistent data)
    2. volume create <name>create one (docker run -v <name>:/path also creates it)
    3. volume rm <name>delete it and its data
  • docker run -d -v <volume>:<container-path> <image>Mount a named volume into a container

    What each part does

    1. -v <volume>:<container-path>data written to <container-path> survives container removal
  • docker network ls; docker network create <name>List / create networks

    What each part does

    1. network lsbridge, host, none + your own networks
    2. network create <name>user-defined bridge: containers on it reach each other by name
  • docker run -d --name <name> --network <network> <image>Run a container on a network

    What each part does

    1. --network <network>attach to that network; other containers can reach it as http://<name>

Find & inspect containers7

  • docker ps -a | grep <container-id>Find a container by ID or name in the full list

    What each part does

    1. docker pslist containers (running only by default)
    2. -a--all: include stopped / exited containers too
    3. |pipe the table into grep
    4. grep <container-id>keep only the row that contains that ID (a prefix like 3f2a is enough) or name

    Tip Built-in alternative without grep: docker ps -a --filter id=<container-id> (or --filter name=<name>).

  • docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"Only running containers, compact table

    What each part does

    1. docker psrunning containers
    2. --format "table …"Go template output; "table" adds column headers
    3. {{.Names}} {{.Status}} {{.Ports}}fields to show; \t separates columns
  • docker ps -a --filter status=exited --filter name=<name>Filter containers by state, name or image

    What each part does

    1. -aall containers
    2. --filter status=exitedonly exited ones (also: running, paused, restarting…)
    3. --filter name=<name>name contains <name>. Repeating --filter combines them
  • docker ps -qJust the IDs (for scripting)

    What each part does

    1. -q--quiet: print only container IDs, one per line
  • docker inspect --format '{{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}' <container>Why did it stop? Exit code and OOM

    What each part does

    1. docker inspect <container>full JSON details of the container
    2. --format '…'Go template: print only the fields you ask for
    3. {{.State.ExitCode}}0 = clean exit, 137 = killed (often out of memory), 143 = SIGTERM
    4. {{.State.OOMKilled}}true if the kernel killed it for exceeding its memory limit
  • docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' <container>Container IP address

    What each part does

    1. range .NetworkSettings.Networksloop over every network the container is attached to
    2. {{.IPAddress}}print its IP on that network
  • docker stats --no-streamLive CPU / memory per container

    What each part does

    1. docker statsresource usage of running containers
    2. --no-streamprint one snapshot and exit instead of refreshing

Environment variables & container config12

  • docker exec <container> envPrint all environment variables of a running container

    What each part does

    1. docker exec <container>run a command inside the running container
    2. envprint every environment variable the container's processes see, KEY=value per line

    Tip Needs a running container that has env (most images do; distroless ones don't). For a stopped container use the inspect version below.

  • docker exec <container> printenv <VAR>Print one environment variable

    What each part does

    1. docker exec <container>run inside the container
    2. printenv <VAR>print only that variable's value; exit code 1 if it isn't set
  • docker inspect <container> --format '{{range .Config.Env}}{{println .}}{{end}}'Show env vars from the container config (works when stopped)

    What each part does

    1. docker inspect <container>read the container's stored configuration; no exec needed
    2. --format '...'Go template to pick fields
    3. {{range .Config.Env}}loop over the Env list (from the image ENV, -e and --env-file)
    4. {{println .}}print each KEY=value on its own line

    Tip Shows the configured env, not variables a process exported at runtime. Secrets passed with -e are visible here: anyone with docker access can read them.

  • docker image inspect <image>:<tag> --format '{{json .Config.Env}}'Show env vars baked into an image

    What each part does

    1. docker image inspect <image>:<tag>metadata of a local image
    2. {{json .Config.Env}}the ENV values from the Dockerfile (PATH, versions...) as a JSON list
  • docker run --rm <image>:<tag> envPrint the env a fresh container would get

    What each part does

    1. docker run --rmstart a throwaway container, removed when it exits
    2. <image>:<tag>the image to test
    3. envoverride the command: just print the environment
  • docker compose exec <service> envPrint the env of a Compose service

    What each part does

    1. docker compose exec <service>run inside the running service container
    2. envprint its environment, after .env and environment: substitution

    Tip To check the values before starting anything, use docker compose config.

  • docker inspect <container> --format 'Entrypoint={{json .Config.Entrypoint}} Cmd={{json .Config.Cmd}}'Show the entrypoint and command a container runs

    What each part does

    1. docker inspect <container>container config
    2. {{json .Config.Entrypoint}}the ENTRYPOINT (the program that always runs)
    3. {{json .Config.Cmd}}the CMD (default arguments, replaced by what you type after the image name)
  • docker inspect <container> --format '{{json .Mounts}}' | jqShow mounts (volumes and bind mounts)

    What each part does

    1. {{json .Mounts}}every mount: type, source on the host, destination in the container, read-only flag
    2. | jqpretty-print the JSON
  • docker inspect <container> --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}'Show the container's IP address(es)

    What each part does

    1. {{range .NetworkSettings.Networks}}loop over every network the container is attached to
    2. {{.IPAddress}}its IP on that network
  • docker inspect <container> --format 'restart={{.HostConfig.RestartPolicy.Name}} memory={{.HostConfig.Memory}} cpus={{.HostConfig.NanoCpus}}'Show restart policy and resource limits

    What each part does

    1. {{.HostConfig.RestartPolicy.Name}}no, always, on-failure or unless-stopped
    2. {{.HostConfig.Memory}}memory limit in bytes (0 = unlimited)
    3. {{.HostConfig.NanoCpus}}CPU limit in billionths of a CPU (1000000000 = 1 CPU, 0 = unlimited)
  • docker inspect <container> --format '{{json .State.Health}}' | jqShow the health check status and last results

    What each part does

    1. {{json .State.Health}}status (starting / healthy / unhealthy), failing streak, and the output of the last checks
    2. | jqpretty-print
  • docker inspect <container> --format '{{json .Config.Labels}}' | jqShow labels (Compose project, versions, maintainers)

    What each part does

    1. {{json .Config.Labels}}all labels as JSON, e.g. com.docker.compose.service and org.opencontainers.image.version
    2. | jqpretty-print

Software versions inside containers & images9

  • docker exec <container> cat /etc/os-releaseWhich OS and version is the container based on?

    What each part does

    1. docker exec <container>run inside the container
    2. cat /etc/os-releasedistro name and version, e.g. Debian 12, Alpine 3.20, UBI 9
  • docker exec <container> sh -c 'dpkg -l 2>/dev/null || rpm -qa 2>/dev/null || apk info -v'List installed OS packages with versions (any distro)

    What each part does

    1. sh -c '...'run a small shell script inside the container
    2. dpkg -lDebian / Ubuntu packages and versions
    3. 2>/dev/null ||hide the error and try the next tool if this one doesn't exist
    4. rpm -qaRHEL / UBI / Amazon Linux packages
    5. apk info -vAlpine packages with versions
  • docker exec <container> sh -c 'dpkg-query -W <package> 2>/dev/null || rpm -q <package> 2>/dev/null || apk info -v <package>'Version of one package in a container

    What each part does

    1. dpkg-query -W <package>Debian / Ubuntu: name and installed version
    2. rpm -q <package>RHEL family: name-version-release
    3. apk info -v <package>Alpine: name-version
  • docker run --rm <image>:<tag> <program> --versionVersion of the app runtime in an image

    What each part does

    1. docker run --rm <image>:<tag>throwaway container from the image
    2. <program> --versione.g. node --version, python3 --version, java -version, nginx -v
  • docker image inspect <image>:<tag> --format '{{index .Config.Labels "org.opencontainers.image.version"}}'Image version labels (OCI annotations)

    What each part does

    1. docker image inspect <image>:<tag>image metadata
    2. {{index .Config.Labels "..."}}read one label; the OCI version label is set by many official images and good pipelines
  • docker image inspect <image>:<tag> --format '{{.Id}} {{index .RepoDigests 0}} {{.Created}} {{.Os}}/{{.Architecture}}'Image ID, digest, created date and architecture

    What each part does

    1. {{.Id}}local image ID
    2. {{index .RepoDigests 0}}registry digest (repo@sha256:...) to pin exactly this image
    3. {{.Created}}build date
    4. {{.Os}}/{{.Architecture}}platform, e.g. linux/amd64 or linux/arm64
  • docker inspect <container> --format '{{.Config.Image}} {{.Image}}'Which image (and digest) is a container running?

    What each part does

    1. {{.Config.Image}}the name:tag it was started from
    2. {{.Image}}the exact image ID, so you can tell if :latest has moved since
  • docker manifest inspect <image>:<tag> | jq '.manifests[].platform'Check which platforms an image supports, without pulling

    What each part does

    1. docker manifest inspectread the image manifest from the registry
    2. | jq '.manifests[].platform'list os/architecture of every variant (multi-arch images)
  • docker scout quickview <image>:<tag>Quick vulnerability overview of an image

    What each part does

    1. docker scout quickviewsummary of known CVEs by severity and base image update advice (Docker Scout plugin)
    2. <image>:<tag>local or registry image

    Tip docker scout cves <image> lists every CVE. Trivy does the same without Docker's plugin.

Logs & shells5

  • docker logs -f --tail 200 -t <container>Follow the last 200 log lines with timestamps

    What each part does

    1. docker logs <container>the container's stdout/stderr
    2. -f--follow: keep streaming new lines
    3. --tail 200start from the last 200 lines (alias -n)
    4. -t--timestamps: prefix each line with its time
  • docker logs --since 15m <container> 2>&1 | grep -i errorLogs from the last 15 minutes, errors only

    What each part does

    1. --since 15monly lines from the last 15 minutes (also 1h30m or an RFC3339 time)
    2. 2>&1merge stderr into stdout, so grep also sees error output
    3. | grep -i errorkeep lines containing "error", any case
  • docker exec -it <container> shOpen a shell inside a running container

    What each part does

    1. docker exec <container>run a command in a running container
    2. -i--interactive: keep stdin open
    3. -t--tty: allocate a terminal
    4. shthe command to run (use bash if the image has it)
  • docker exec -e <KEY>=<value> -w <dir> <container> <cmd>Run a one-off command with env and workdir

    What each part does

    1. -e <KEY>=<value>set an environment variable for this command only
    2. -w <dir>working directory inside the container
    3. <cmd>command to run; wrap chains as sh -c "a && b"
  • docker cp <container>:<path> ./ ; docker cp ./<file> <container>:<path>Copy a file out of / into a container

    What each part does

    1. docker cp <container>:<path> ./container → current host directory
    2. ;then
    3. docker cp ./<file> <container>:<path>host → container

Run containers3

  • docker run -d --name <name> -p <host-port>:<container-port> <image>:<tag>Run a service in the background with a port and a name

    What each part does

    1. docker runcreate and start a container
    2. -d--detach: run in the background and print the ID
    3. --name <name>give it a fixed name instead of a random one
    4. -p <host-port>:<container-port>publish a container port on the host (binds all interfaces; use 127.0.0.1:<host-port>:… for local only)
    5. <image>:<tag>image to run (pin a tag, avoid latest)
  • docker run -it --rm <image> shThrow-away interactive container

    What each part does

    1. -itinteractive + terminal
    2. --rmdelete the container (and anonymous volumes) when it exits
    3. shcommand to run instead of the image default
  • docker run -d -e <KEY>=<value> --env-file .env -v <host-path>:<container-path>:ro -m 512m --cpus 1 --restart unless-stopped <image>Env vars, volume and limits

    What each part does

    1. -e <KEY>=<value>set one environment variable
    2. --env-file .envload KEY=value lines from a file
    3. -v <host-path>:<container-path>:robind-mount a host folder, read-only
    4. -m 512mmemory limit (exceeding it → OOM kill, exit 137)
    5. --cpus 1at most one CPU worth of time
    6. --restart unless-stoppedrestart automatically unless you stopped it yourself

Images4

  • docker build -t <registry>/<image>:<tag> -f <Dockerfile> .Build and tag an image

    What each part does

    1. docker buildbuild an image (BuildKit)
    2. -t <registry>/<image>:<tag>name and tag for the result
    3. -f <Dockerfile>which Dockerfile (default ./Dockerfile)
    4. .build context: the folder sent to the builder (.dockerignore trims it)
  • docker build --no-cache --pull --target <stage> --build-arg <KEY>=<value> -t <image>:<tag> .Clean rebuild of one stage with a build arg

    What each part does

    1. --no-cacheignore cached layers
    2. --pullalways check for a newer base image
    3. --target <stage>stop at a named stage of a multi-stage Dockerfile
    4. --build-arg <KEY>=<value>value for an ARG in the Dockerfile
  • docker tag <image>:<tag> <registry>/<image>:<tag> && docker push <registry>/<image>:<tag>Tag and push to a registry

    What each part does

    1. docker tag <src> <target>add another name to an existing image
    2. &&only if tagging worked
    3. docker push <target>upload it (run docker login <registry> first)
  • docker history --no-trunc <image>Image layers and what created them

    What each part does

    1. docker historyone row per layer with its size
    2. --no-truncshow the full command that created each layer

Cleanup6

  • docker system dfHow much space Docker uses

    What each part does

    1. docker system dfspace used by images, containers, volumes and build cache, plus how much is reclaimable
  • docker ps -q | xargs -r docker stopStop all running containersCaution

    What each part does

    1. docker ps -qIDs of running containers
    2. |pipe them to xargs
    3. xargs -rpass them as arguments; -r: don't run if the list is empty
    4. docker stopstop each one gracefully (SIGTERM, then SIGKILL after 10s)
  • docker ps -aq --filter status=exited | xargs -r docker rmRemove all exited containersCaution

    What each part does

    1. -aqall containers, IDs only
    2. --filter status=exitedonly exited ones
    3. xargs -r docker rmremove them

    Tip Same result: docker container prune

  • docker system prune -f --filter "until=24h"Remove unused data older than a dayCaution

    What each part does

    1. docker system pruneremove stopped containers, unused networks, dangling images and build cache
    2. -f--force: no confirmation prompt
    3. --filter "until=24h"only things older than 24 hours
  • docker system prune -a --volumesRemove everything unused, including volumesDestructive

    What each part does

    1. -a--all: also every image not used by a container (not just dangling)
    2. --volumesalso unused volumes: this deletes data
  • docker builder prune -af --filter "until=24h"Remove build cache onlyCaution

    What each part does

    1. docker builder pruneremove BuildKit build cache (image prune does not touch it)
    2. -aall cache, not only dangling
    3. -fno prompt
    4. --filter "until=24h"keep the last day of cache

Docker Compose v27

  • docker compose up -d --buildBuild and start everything in the background

    What each part does

    1. docker composeCompose v2 (plugin; not the old docker-compose binary)
    2. upcreate and start the services
    3. -ddetached
    4. --buildbuild images before starting
  • docker compose up -d --force-recreate --remove-orphans --waitRecreate cleanly and wait until healthy

    What each part does

    1. --force-recreaterecreate containers even if nothing changed
    2. --remove-orphansremove containers for services no longer in the file
    3. --waitwait until services are running/healthy (implies -d)
  • docker compose logs -f --tail 100 <service>Follow logs of one service

    What each part does

    1. logs <service>logs of that service (omit for all)
    2. -ffollow
    3. --tail 100start from the last 100 lines
  • docker compose exec <service> sh; docker compose run --rm <service> <cmd>Shell into a service / run a one-off task

    What each part does

    1. exec <service> shshell in the already-running service container
    2. run --rm <service> <cmd>start a new temporary container for a one-off command, removed afterwards
  • docker compose -f compose.yaml -f compose.prod.yaml -p <project> up -dUse several compose files and a project name

    What each part does

    1. -f compose.yaml -f compose.prod.yamlmerge files in order; later files override earlier ones
    2. -p <project>project name (prefix for container/network names)
  • docker compose configSee the final merged config

    What each part does

    1. configparse, merge and print the effective compose file (great for checking env substitution)
  • docker compose down -vStop and remove the stack (and its volumes)Destructive

    What each part does

    1. downstop and remove containers and networks
    2. -valso remove named volumes declared in the file: deletes data

Container lifecycle & live changes10

  • docker top <container>Processes running inside a container

    What each part does

    1. docker topps output for the container's processes, as seen from the host (PIDs are host PIDs)
    2. <container>name or ID
  • docker diff <container>Files changed inside a container since it started

    What each part does

    1. docker difflist files added (A), changed (C) or deleted (D) in the container's writable layer

    Tip Handy to find where an app writes data that should be in a volume.

  • docker kill -s <signal> <container>Send a signal to a containerCaution

    What each part does

    1. docker killsend a signal to the main process (default SIGKILL)
    2. -s <signal>e.g. HUP to reload nginx config, TERM for a graceful stop
  • docker pause <container>; docker unpause <container>Pause and resume a container

    What each part does

    1. docker pausefreeze all processes (cgroup freezer); memory stays, no CPU used
    2. docker unpauselet them run again
  • docker wait <container>Wait for a container to exit and get its exit code

    What each part does

    1. docker waitblock until the container stops, then print its exit code (useful in scripts)
  • docker update --memory 1g --memory-swap 1g --cpus 1.5 --restart unless-stopped <container>Change memory, CPU or restart policy of a running container

    What each part does

    1. docker updatechange settings live, no restart
    2. --memory 1g --memory-swap 1ghard memory limit; equal swap value means no extra swap
    3. --cpus 1.5at most 1.5 CPUs
    4. --restart unless-stoppednew restart policy
  • docker attach --sig-proxy=false <container>Attach to a container's main process

    What each part does

    1. docker attachconnect your terminal to the main process's stdin/stdout
    2. --sig-proxy=falseso Ctrl+C doesn't kill the container; detach with Ctrl+P Ctrl+Q

    Tip Usually you want docker logs -f or docker exec instead.

  • docker events --filter container=<container> --since 30mWatch Docker events live

    What each part does

    1. docker eventsstream of daemon events: create, start, die, oom, health_status, kill...
    2. --filter container=<container>only this container (also type=, event=, image=)
    3. --since 30minclude events from the last 30 minutes
  • docker commit -m "<message>" <container> <image>:<tag>Save a container's current state as an image

    What each part does

    1. docker commitsnapshot the container's filesystem into a new image
    2. -m "<message>"commit message
    3. <image>:<tag>name for the new image

    Tip Good for debugging or forensics; for real images use a Dockerfile.

  • docker create --name <name> <image>:<tag>Create a container without starting it

    What each part does

    1. docker createcreate the container (pull if needed) but don't run it
    2. --name <name>its name; start later with docker start

Builds, multi-platform & moving images11

  • docker build --build-arg <ARG>=<value> --target <stage> --no-cache -t <image>:<tag> .Build with build args, a target stage and no cache

    What each part does

    1. --build-arg <ARG>=<value>set an ARG declared in the Dockerfile (not for secrets: they stay in history)
    2. --target <stage>stop at this stage of a multi-stage build
    3. --no-cacherebuild every layer
    4. -t <image>:<tag>name the result
    5. .build context
  • docker build -f <path>/Dockerfile.prod -t <image>:<tag> .Use a different Dockerfile

    What each part does

    1. -f <path>/Dockerfile.prodDockerfile to use
    2. .build context (can differ from the Dockerfile's folder)
  • docker build --secret id=npmrc,src=$HOME/.npmrc -t <image>:<tag> .Pass a secret to a build without leaving it in the image

    What each part does

    1. --secret id=npmrc,src=...mount a file only during the RUN step that asks for it
    2. Dockerfile sideRUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
  • docker buildx build --platform linux/amd64,linux/arm64 -t <registry>/<image>:<tag> --push .Build for several CPU architectures and push

    What each part does

    1. docker buildx buildBuildKit builder with multi-platform support
    2. --platform linux/amd64,linux/arm64build both (Intel/AMD servers and ARM like Graviton or Apple Silicon)
    3. --pushpush the multi-arch image straight to the registry
  • docker buildx ls; docker buildx create --name <builder> --useList and create buildx builders

    What each part does

    1. docker buildx lsbuilders and the platforms they support
    2. docker buildx create --usenew builder (docker-container driver) and make it the default
  • docker build --progress=plain -t <image>:<tag> .Build with plain progress output (CI logs)

    What each part does

    1. --progress=plainfull, line-by-line output of every step instead of the collapsing TTY view
  • docker save -o <file>.tar <image>:<tag>Save an image to a file (no registry)

    What each part does

    1. docker saveexport one or more images with all layers and tags
    2. -o <file>.tarwrite to a tar file
  • docker load -i <file>.tarLoad an image from a file

    What each part does

    1. docker loadimport images saved with docker save
    2. -i <file>.tarinput file (also reads .tar.gz)
  • docker save <image>:<tag> | gzip | ssh <user>@<host> 'gunzip | docker load'Copy an image to another host over SSH

    What each part does

    1. docker save <image>:<tag>stream the image as tar
    2. | gzipcompress it
    3. | ssh <user>@<host> '...'send it to the other machine
    4. gunzip | docker loadunpack and load it there
  • docker export <container> -o <file>.tarExport a container's filesystem

    What each part does

    1. docker exportflatten the container's filesystem into a tar (no layers, history or metadata)
    2. -o <file>.taroutput file
  • docker initGenerate a Dockerfile, compose file and .dockerignore

    What each part does

    1. docker initasks about your project (Node, Python, Go...) and writes starter Docker files

Volumes, networks & remote hosts in depth12

  • docker volume inspect <volume>; docker ps -a --filter volume=<volume>Where is a volume's data and who uses it?

    What each part does

    1. docker volume inspectdriver, mountpoint on the host, labels
    2. docker ps -a --filter volume=<volume>containers using it
  • docker run --rm -v <volume>:/data:ro -v "$PWD":/backup alpine tar czf /backup/<volume>.tgz -C /data .Back up a volume to a tar file

    What each part does

    1. docker run --rmthrowaway helper container
    2. -v <volume>:/data:romount the volume read-only
    3. -v "$PWD":/backupmount the current host folder
    4. alpine tar czf ... -C /data .archive the volume contents into the host folder

    Tip Stop the app first (or use its own dump tool) for consistent database backups.

  • docker run --rm -v <volume>:/data -v "$PWD":/backup alpine tar xzf /backup/<volume>.tgz -C /dataRestore a volume from a tar fileCaution

    What each part does

    1. -v <volume>:/datamount the target volume read-write
    2. tar xzf ... -C /dataunpack the backup into it
  • docker volume prune -aRemove unused volumesDestructive

    What each part does

    1. docker volume prunedelete volumes no container uses
    2. -ainclude named volumes (without it, only anonymous ones on Docker 23+)
  • docker network inspect <network> --format '{{json .IPAM.Config}} {{range .Containers}}{{.Name}} {{.IPv4Address}}; {{end}}'Inspect a network: subnet and connected containers

    What each part does

    1. docker network inspect <network>network details
    2. {{json .IPAM.Config}}subnet and gateway
    3. {{range .Containers}}...{{end}}each attached container with its IP
  • docker network connect <network> <container>; docker network disconnect <network> <container>Connect / disconnect a running container to a network

    What each part does

    1. docker network connectattach to another network (containers can be on several)
    2. docker network disconnectdetach
  • docker run --rm --network host <image>; docker run --rm --network none <image>Run with host or no networking

    What each part does

    1. --network hostshare the host's network stack: no port mapping, no isolation (Linux only)
    2. --network noneno network at all, only loopback
  • docker network prune -fRemove unused networksCaution

    What each part does

    1. docker network prunedelete networks no container uses
    2. -fno prompt
  • docker context create <name> --docker host=ssh://<user>@<host>; docker context use <name>Run docker commands against a remote host

    What each part does

    1. docker context createsave a named connection to another Docker daemon
    2. --docker host=ssh://<user>@<host>connect over SSH (no exposed TCP port needed)
    3. docker context use <name>make it the default; docker context use default to come back
  • DOCKER_HOST=ssh://<user>@<host> docker psOne-off command on a remote daemon

    What each part does

    1. DOCKER_HOST=ssh://...point this one command at another daemon
    2. docker psany docker command
  • cat /etc/docker/daemon.json; journalctl -u docker -n 100 --no-pagerCheck the daemon config and its logs

    What each part does

    1. /etc/docker/daemon.jsondaemon settings: log driver and rotation, registry mirrors, data-root, address pools
    2. journalctl -u dockerthe daemon's own logs (start errors, pull failures)
  • docker info --format '{{.DockerRootDir}} {{.Driver}} {{.LoggingDriver}} {{.CgroupDriver}}'Where does Docker store its data?

    What each part does

    1. {{.DockerRootDir}}data directory, usually /var/lib/docker
    2. {{.Driver}}storage driver (overlay2)
    3. {{.LoggingDriver}}default log driver (json-file, local, journald)
    4. {{.CgroupDriver}}systemd or cgroupfs

Compose: more commands9

  • docker compose ps -aStatus of the stack's containers

    What each part does

    1. docker compose pscontainers of this project: service, state, health, ports
    2. -ainclude stopped ones
  • docker compose restart <service>; docker compose stop <service>Restart / stop one service

    What each part does

    1. restart <service>restart the container (config changes need up -d instead)
    2. stop <service>stop without removing
  • docker compose build --pull <service> && docker compose up -d <service>Rebuild images and recreate

    What each part does

    1. build --pullrebuild, pulling newer base images
    2. up -d <service>recreate the container with the new image
  • docker compose pullPull newer images for all services

    What each part does

    1. docker compose pulldownload the image of every service; follow with up -d to use them
  • docker compose up -d --scale <service>=3Run several replicas of a service

    What each part does

    1. --scale <service>=3run 3 containers of the service (don't fix a host port or container_name)
  • docker compose --profile <profile> up -dStart optional services with a profile

    What each part does

    1. --profile <profile>also start services marked profiles: [<profile>], e.g. debug or tools
  • docker compose watchRebuild automatically when files change

    What each part does

    1. docker compose watchsync or rebuild services on file changes, per the develop.watch section
  • docker compose top; docker compose imagesProcesses and images of the stack

    What each part does

    1. docker compose topprocesses in each service container
    2. docker compose imagesimage and tag each container uses
  • docker compose cp <service>:<path> ./Copy a file out of a service

    What each part does

    1. docker compose cplike docker cp, by service name

Swarm mode (services & stacks)10

  • docker swarm init --advertise-addr <ip>Turn this host into a swarm manager

    What each part does

    1. docker swarm initcreate a single-node swarm with this host as manager
    2. --advertise-addr <ip>the address other nodes use to reach it
  • docker swarm join-token workerGet the join command for workers

    What each part does

    1. join-token workerprint the docker swarm join command (use manager for extra managers)
  • docker node lsList nodes

    What each part does

    1. docker node lsnodes, status, availability and manager status
  • docker service create --name <service> --replicas 3 -p 80:80 <image>:<tag>Create a replicated service

    What each part does

    1. docker service createa long-running service the swarm keeps alive
    2. --replicas 33 tasks spread over the nodes
    3. -p 80:80publish through the routing mesh on every node
  • docker service ls; docker service ps <service>List services and where their tasks run

    What each part does

    1. docker service lsservices with replicas running/desired
    2. docker service ps <service>each task, its node, state and errors
  • docker service scale <service>=5Scale a service

    What each part does

    1. scale <service>=5set the number of replicas
  • docker service update --image <image>:<new-tag> <service>; docker service rollback <service>Rolling update to a new image, and roll back

    What each part does

    1. service update --imagerolling replace of tasks with the new image
    2. service rollbackgo back to the previous spec
  • docker service logs -f <service>Logs of all tasks of a service

    What each part does

    1. docker service logsaggregated logs from every task
    2. -ffollow
  • docker stack deploy -c compose.yaml <stack>; docker stack rm <stack>Deploy and remove a stack from a compose fileCaution

    What each part does

    1. stack deploy -c compose.yaml <stack>create or update all services in the file
    2. stack rm <stack>remove the stack's services and networks
  • printf '%s' "$VALUE" | docker secret create <name> -Store a secret for services

    What each part does

    1. printf '%s' "$VALUE"the secret value without a trailing newline
    2. docker secret create <name> -store it encrypted in the swarm; services mount it at /run/secrets/<name>

My DevOps Playbook by Angelo John Calleja

New runbook

GitHub not connected

Saving is handled by the site: the GitHub token is stored in Cloudflare, not in your browser. Enter the editor password (the EDITOR_PASSWORD secret) to unlock saving in this browser.

Saving commits to gelogrammer/My_DevOps_Playbook. Create a fine-grained token with access to only this repo andContents: Read and write, then paste it here. It is stored only in this browser.

src/content/docs/…