Skip to main content

Docker Cheatsheet — 80+ Commands with Pitfalls, Compose, and Build Techniques

Docker command cheat sheet — 80+ commands with real examples, common mistakes, and Compose section.

  • Runs locally
  • Category Developer & DevOps
  • Best for Formatting, validating, shrinking, or inspecting code-adjacent text.
148 commands
Image (19)
docker pull <image>

Download an image (or a specific tag) from a registry to the local daemon.

Common pitfall: Without a tag docker pulls `:latest`, which is a moving target. Pin the version for reproducible builds.

Examples
docker pull nginx
docker pull node:20-alpine
docker pull ghcr.io/user/app:v1.2.3
docker push <image>

Upload a local image to a registry. The image must already be tagged with the registry path.

Common pitfall: Push fails with "denied" if you have not run `docker login` first, or the tag does not include the registry prefix.

Examples
docker push myorg/app:v1.0
docker push registry.example.com/team/app:latest
docker build -t <name> <path>

Build an image from a Dockerfile in <path> and tag it as <name>.

Common pitfall: The build context is the WHOLE folder — a missing .dockerignore can ship gigabytes of node_modules / .git into the daemon.

Examples
docker build -t myapp .
docker build -t myapp:v1.0 -f Dockerfile.prod .
docker build --no-cache -t myapp .
docker images

List all local images with repository, tag, ID, age, and size.

Examples
docker images
docker images -a
docker images --filter "dangling=true"
docker rmi <image>

Remove a local image. Multiple images can be removed in one call.

Common pitfall: `rmi` is for IMAGES; `rm` is for CONTAINERS. Confusing these two is the #1 docker rookie mistake. If a container still uses the image, add -f to force.

Examples
docker rmi nginx:1.25
docker rmi -f myapp:old
docker rmi $(docker images -q -f "dangling=true")
docker tag <src> <dst>

Add a new tag pointing to an existing image. Both old and new tags share the same image ID.

Common pitfall: Tagging does not copy data — pushing the new tag re-uses existing layers and is fast.

Examples
docker tag myapp:latest myorg/myapp:v1.0
docker tag abc123 registry.example.com/team/app:prod
docker save -o <file.tar> <image>

Export an image (with all layers + metadata) to a tar archive for air-gapped transfer.

Examples
docker save -o myapp.tar myapp:v1.0
docker save myapp:v1.0 | gzip > myapp.tar.gz
docker load -i <file.tar>

Import an image from a tar archive created by `docker save`.

Common pitfall: `load` restores an image; `import` creates a new image from a raw filesystem tar. Different inputs, different commands.

Examples
docker load -i myapp.tar
gunzip -c myapp.tar.gz | docker load
docker history <image>

Show the layer-by-layer construction of an image — every command, size, and timestamp.

Examples
docker history nginx
docker history --no-trunc myapp:v1.0
docker scout cves <image>

Scan an image for known CVE vulnerabilities (replaces the deprecated `docker scan`).

Common pitfall: `docker scan` (Snyk-based) is deprecated since Docker Desktop 4.27. Use `docker scout` for new projects.

Examples
docker scout cves myapp:latest
docker scout quickview myapp:latest
docker image prune

Remove all dangling images (images with no tag, usually leftovers from rebuilds).

Common pitfall: `-a` removes EVERY unused image, not just dangling ones — can blow away images you still want.

Examples
docker image prune
docker image prune -a
docker image prune -a --filter "until=168h"
docker inspect <image>

Print low-level JSON metadata for an image: layers, env vars, entrypoint, exposed ports, labels.

Examples
docker inspect nginx
docker inspect --format "{{.Config.Env}}" myapp
docker import <file.tar> <image>

Create a brand-new image from a raw filesystem tarball (e.g. from `docker export`). No layers, no history.

Common pitfall: `import` takes a filesystem tar and flattens it; `load` takes a `docker save` archive and keeps layers. They are not interchangeable.

Examples
docker import rootfs.tar myrootfs:base
docker export web | docker import - web-snapshot:v1
docker image ls --digests

List images including their content-addressable digest (sha256), not just the human tag.

Common pitfall: A tag can be re-pushed to point at new content; the digest never changes. Pin `image@sha256:…` in prod for true immutability.

Examples
docker image ls --digests
docker pull nginx@sha256:abc123...
docker manifest inspect <image>

Inspect a multi-arch manifest list to see which platforms (amd64, arm64, …) a tag actually provides.

Common pitfall: This is an experimental CLI feature; on older Docker you must set `experimental: enabled` in ~/.docker/config.json first.

Examples
docker manifest inspect nginx:latest
docker buildx imagetools inspect nginx:latest
docker pull -a <repo>

Pull every tag available in a repository at once.

Common pitfall: A busy repo can have hundreds of tags and tens of GB. Rarely what you want; pin a single tag instead.

Examples
docker pull -a alpine
docker tag <img> <img>:<sha>

Tag an image with the git commit SHA so every build is traceable back to source.

Examples
docker tag myapp:latest myapp:$(git rev-parse --short HEAD)
docker tag myapp registry.example.com/team/myapp:$(date +%Y%m%d)
docker scout recommendations <image>

Suggest a more secure / smaller base image and tag upgrades to cut CVE count.

Examples
docker scout recommendations myapp:latest
docker scout compare --to myapp:prod myapp:staging
docker image inspect --format

Pull one specific field out of image metadata using a Go template, instead of reading the whole JSON.

Examples
docker image inspect --format "{{.Architecture}}" nginx
docker image inspect --format "{{.Size}}" myapp
Container (43)
docker run <image>

Create AND start a new container from an image. The most-used docker command.

Common pitfall: Each `docker run` creates a NEW container. Repeated runs accumulate stopped containers — use `--rm` for one-shots or `docker start <name>` to reuse.

Examples
docker run nginx
docker run -d -p 8080:80 nginx
docker run --rm -it ubuntu bash
docker run -it <image> <cmd>

Run interactively with a TTY. -i keeps STDIN open, -t allocates a pseudo-TTY. Together you get a real shell.

Common pitfall: Just `-i` gives no prompt; just `-t` cannot receive input. Use `-it` together. Drop `-t` when piping (e.g. `echo x | docker run -i …`).

Examples
docker run -it ubuntu bash
docker run -it --rm alpine sh
docker run -it node:20 node
docker run -d <image>

Run a container detached (in the background) and print only the container ID.

Examples
docker run -d nginx
docker run -d --name web -p 80:80 nginx
docker run --rm <image>

Auto-remove the container on exit. Perfect for one-shot commands so the host does not pile up dead containers.

Common pitfall: `--rm` runs at container EXIT — it does not remove the image. And data in non-mounted dirs is gone on exit.

Examples
docker run --rm alpine echo hello
docker run --rm -v $(pwd):/work -w /work node:20 npm test
docker run -p <host>:<container> <image>

Publish a container port to the host. Format: HOST:CONTAINER.

Common pitfall: The host port comes FIRST, the container port second. Swapping them gives a confusing "no app listening" error.

Examples
docker run -p 8080:80 nginx
docker run -p 127.0.0.1:5432:5432 postgres
docker run -P nginx
docker run -v <host>:<container> <image>

Mount a host path or named volume into the container at the given path.

Common pitfall: Bind-mounts on macOS/Windows are SLOW (file syncing through VM). Use named volumes for hot paths like node_modules.

Examples
docker run -v $(pwd):/app node:20
docker run -v mydata:/var/lib/mysql mysql
docker run -v $(pwd):/app:ro alpine
docker run --name <name> <image>

Give the container a human-readable name instead of the auto-generated funny-adjective-funny-noun.

Common pitfall: Names must be unique. Re-running with the same name fails until you `docker rm` the old one.

Examples
docker run --name web -d nginx
docker run --name pg -e POSTGRES_PASSWORD=secret -d postgres
docker run -e KEY=value <image>

Pass an environment variable into the container.

Common pitfall: Long secret strings on the CLI leak into shell history. Use `--env-file .env` or a secret manager.

Examples
docker run -e NODE_ENV=production node:20
docker run --env-file .env myapp
docker run -e DEBUG=1 -e LOG_LEVEL=info myapp
docker run --restart unless-stopped <image>

Restart policy: container restarts on crash and on daemon restart, but stays stopped if you `docker stop` it.

Common pitfall: `--restart=always` will resurrect a container even after `docker stop` once the daemon restarts. `unless-stopped` is almost always what you want.

Examples
docker run -d --restart unless-stopped --name web nginx
docker run -d --restart on-failure:5 myapp
docker ps

List running containers. Add -a to include stopped ones.

Examples
docker ps
docker ps -a
docker ps --filter "status=exited"
docker ps --format "table {{.Names}}\t{{.Status}}"
docker start <container>

Start one or more stopped containers (preserves all data + config from when you ran them).

Examples
docker start web
docker start -a web
docker start $(docker ps -aq -f "status=exited")
docker stop <container>

Gracefully stop a running container (SIGTERM, then SIGKILL after 10s).

Common pitfall: Apps that ignore SIGTERM (e.g. shell-wrapped node, sh -c "node app.js") get killed instead of stopped cleanly. Use `exec` form in Dockerfile CMD.

Examples
docker stop web
docker stop -t 30 web
docker stop $(docker ps -q)
docker restart <container>

Stop then start a container — sometimes the fastest fix for a wedged process.

Examples
docker restart web
docker restart -t 5 web
docker rm <container>

Remove one or more stopped containers. Use -f to force-remove running ones.

Common pitfall: Same as image: `rm` is for CONTAINERS, `rmi` is for IMAGES. Volumes mounted into the container are NOT removed; add -v for that.

Examples
docker rm web
docker rm -f web
docker rm -v old-db
docker rm $(docker ps -aq)
docker exec -it <container> <cmd>

Run a one-off command inside a running container — typically a shell to poke around.

Common pitfall: The container must already be RUNNING. To run a command in a stopped container, use `docker start` first or `docker run` a fresh one.

Examples
docker exec -it web bash
docker exec -it web sh
docker exec web ls /etc
docker exec -u 0 -it web bash
docker logs <container>

Print the container's STDOUT + STDERR (whatever your app wrote, not files on disk).

Common pitfall: If your app writes to /var/log/app.log instead of stdout, `docker logs` is empty. Make 12-factor apps log to stdout.

Examples
docker logs web
docker logs -f web
docker logs --tail 100 web
docker logs --since 10m web
docker attach <container>

Attach your terminal to the main process of a running container. Ctrl-C will kill the container.

Common pitfall: `attach` is NOT a shell — it joins the existing process. Use `docker exec -it … bash` instead unless you really need the main TTY.

Examples
docker attach web
docker attach --detach-keys="ctrl-p,ctrl-q" web
docker cp <src> <dst>

Copy files between the host and a container. Either side can be the container.

Examples
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
docker cp ./fix.patch web:/tmp/
docker cp web:/var/log/. ./logs/
docker inspect <container>

Print all low-level config + state JSON for the container: IP, mounts, env, network, exit code.

Examples
docker inspect web
docker inspect --format "{{.State.Status}}" web
docker inspect --format "{{.NetworkSettings.IPAddress}}" web
docker stats

Live stream of CPU, memory, network and disk IO for running containers.

Examples
docker stats
docker stats --no-stream
docker stats web db
docker top <container>

Show the processes running INSIDE a container (similar to host `ps`).

Examples
docker top web
docker top web aux
docker kill <container>

Send SIGKILL (or any signal with -s) immediately to the container's main process.

Common pitfall: SIGKILL gives the app no chance to clean up — half-written files, unflushed DB writes. Prefer `docker stop` unless the process is wedged.

Examples
docker kill web
docker kill -s SIGHUP web
docker rename <old> <new>

Rename an existing container.

Examples
docker rename web web-old
docker rename happy_elephant payment-service
docker pause <container>

Freeze all processes in the container using cgroup freezer (they are still in memory).

Common pitfall: Paused containers still hold their ports + memory. For testing only — not a real "low-resource standby" mode.

Examples
docker pause web
docker unpause web
docker unpause <container>

Resume a paused container.

Examples
docker unpause web
docker commit <container> <image>

Snapshot a running container's filesystem into a new image. Useful for debugging, NOT for prod builds.

Common pitfall: `commit` images are opaque — no Dockerfile, no reproducibility. Always prefer a Dockerfile for anything you ship.

Examples
docker commit web debug-snapshot:v1
docker commit -m "added trace" -a "lei" web debug:v2
docker diff <container>

Show every file added (A), changed (C), or deleted (D) in the container vs its base image.

Examples
docker diff web
docker wait <container>

Block until the container exits, then print its exit code.

Examples
docker wait batch-job
EXIT=$(docker wait batch-job) && echo "Job finished: $EXIT"
docker port <container>

List the public-facing port mappings for the container.

Examples
docker port web
docker port web 80
docker run -w <dir> <image>

Set the working directory inside the container for the command and any later `exec`.

Examples
docker run -w /app -v $(pwd):/app node:20 npm test
docker run -w /src --rm gcc:13 gcc main.c
docker run -u <uid>:<gid> <image>

Run the container process as a specific user/group instead of root.

Common pitfall: Files written to a bind-mount land on the host owned by this UID. Use `$(id -u):$(id -g)` so they match your host user.

Examples
docker run -u 1000:1000 -v $(pwd):/app node:20
docker run -u $(id -u):$(id -g) --rm -v $(pwd):/work alpine touch /work/x
docker run --memory <limit> <image>

Cap the container’s memory. The kernel OOM-kills the container if it exceeds the limit.

Common pitfall: Without `--memory-swap` set equal to `--memory`, the container can still use host swap. Set both to truly cap RAM.

Examples
docker run -m 512m myapp
docker run --memory 1g --memory-swap 1g myapp
docker run --cpus <n> <image>

Limit how many CPU cores the container may use (fractional values allowed).

Examples
docker run --cpus 1.5 myapp
docker run --cpus 0.5 --cpu-shares 512 myapp
docker run --read-only <image>

Mount the container’s root filesystem read-only. A strong hardening default for stateless services.

Common pitfall: Apps that write temp files break. Add `--tmpfs /tmp` (and any other writable path) so they have somewhere to scribble.

Examples
docker run --read-only --tmpfs /tmp nginx
docker run --read-only -v logs:/var/log myapp
docker run --cap-drop ALL <image>

Drop all Linux capabilities, then add back only the ones the app truly needs with --cap-add.

Common pitfall: Containers run with a default cap set that includes more than most apps need. Drop-all-then-add is least-privilege done right.

Examples
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE nginx
docker run --cap-drop ALL alpine id
docker run --security-opt no-new-privileges <image>

Prevent the container process from gaining new privileges via setuid binaries.

Examples
docker run --security-opt no-new-privileges:true myapp
docker run --health-cmd <cmd> <image>

Attach a healthcheck so `docker ps` shows healthy/unhealthy and orchestrators can act on it.

Common pitfall: A healthcheck that just pings localhost can report "healthy" while the app is broken upstream. Probe a real endpoint.

Examples
docker run --health-cmd "curl -f http://localhost/ || exit 1" --health-interval 30s nginx
docker run --gpus all <image>

Expose host NVIDIA GPUs to the container (needs the NVIDIA Container Toolkit installed).

Common pitfall: `--gpus` needs the nvidia-container-toolkit on the host; without it you get "could not select device driver".

Examples
docker run --gpus all nvidia/cuda:12.4.1-base nvidia-smi
docker run --gpus "device=0,1" myapp
docker run --add-host <host>:<ip> <image>

Add a custom /etc/hosts entry inside the container.

Examples
docker run --add-host db.local:10.0.0.5 myapp
docker run --add-host host.docker.internal:host-gateway myapp
docker update <container>

Change resource limits (CPU, memory, restart policy) on a running container without recreating it.

Common pitfall: Most settings update live, but some (like `--restart`) only take effect on the next start. Port and volume mounts cannot be changed at all.

Examples
docker update --memory 1g web
docker update --restart unless-stopped web
docker update --cpus 2 web
docker exec -e <KEY=val> <container> <cmd>

Run a command inside a running container with extra environment variables for that command only.

Examples
docker exec -e DEBUG=1 -it web node debug.js
docker exec -e PGPASSWORD=secret db psql -U app
docker logs --timestamps <container>

Prefix each log line with an RFC3339 timestamp from the daemon.

Examples
docker logs -t web
docker logs -t --since 2026-01-01T00:00:00 web
docker run --init <image>

Run a tiny init (tini) as PID 1 to reap zombie processes and forward signals correctly.

Common pitfall: If your app spawns children and does not reap them, zombies pile up. `--init` fixes this without changing your image.

Examples
docker run --init myapp
docker run --init -d --name worker myapp
Network (12)
docker network ls

List all docker networks. You always get bridge, host, and none by default.

Examples
docker network ls
docker network ls --filter "driver=bridge"
docker network create <name>

Create a user-defined bridge network. Containers on the same user network can resolve each other by name.

Common pitfall: Default `bridge` network does NOT have DNS-based service discovery — containers cannot ping each other by name. Always create a user network.

Examples
docker network create app-net
docker network create --driver bridge app-net
docker network create --subnet 172.20.0.0/16 app-net
docker network inspect <network>

Show network details: subnet, gateway, attached containers, options.

Examples
docker network inspect bridge
docker network inspect app-net
docker network connect <network> <container>

Attach a running container to an additional network (containers can be on multiple networks).

Examples
docker network connect app-net web
docker network connect --alias api app-net web
docker network disconnect <network> <container>

Detach a container from a network without stopping it.

Examples
docker network disconnect app-net web
docker network disconnect -f app-net web
docker network rm <network>

Remove one or more empty user-defined networks.

Common pitfall: Networks with attached containers cannot be removed — disconnect them first or remove the containers.

Examples
docker network rm app-net
docker network prune
docker run --network <name> <image>

Start a container directly on a specific network.

Examples
docker run -d --network app-net --name web nginx
docker run --network host nginx
docker network create --internal <name>

Create a network with no external connectivity; containers can talk to each other but not the internet.

Common pitfall: Great for a DB tier that should never reach out. But the DB also cannot pull updates or call webhooks from here.

Examples
docker network create --internal backend
docker run --network backend --name db postgres
docker run --network host <image>

Share the host’s network stack directly; the container has no isolated network namespace.

Common pitfall: On macOS/Windows `--network host` does NOT reach host ports the way Linux does — Docker runs in a VM. Mostly a Linux-only trick.

Examples
docker run --network host nginx
docker run --network host -d prom/prometheus
docker run --dns <ip> <image>

Override the DNS server the container uses for name resolution.

Examples
docker run --dns 1.1.1.1 alpine nslookup example.com
docker run --dns 8.8.8.8 --dns-search corp.local myapp
docker network create --attachable <name>

Create an overlay/bridge network that standalone containers can also attach to (not just swarm services).

Examples
docker network create --driver overlay --attachable mesh
docker network connect mesh standalone-tool
docker run --network none <image>

Give the container no network at all — only a loopback interface. Maximum isolation for untrusted code.

Examples
docker run --network none --rm untrusted-job
docker run --network none alpine ip addr
Volume (9)
docker volume ls

List all docker-managed volumes.

Examples
docker volume ls
docker volume ls --filter "dangling=true"
docker volume create <name>

Create a named volume. Persists data outside the container lifecycle.

Examples
docker volume create pgdata
docker volume create --driver local --opt type=tmpfs fastdata
docker volume inspect <name>

Show volume metadata: driver, mountpoint on host, labels.

Examples
docker volume inspect pgdata
docker volume rm <name>

Delete one or more volumes. Fails if a container still uses them.

Common pitfall: Deleting a volume is IRREVERSIBLE — your DB data is gone. Always back up before pruning shared volumes.

Examples
docker volume rm pgdata
docker volume rm $(docker volume ls -q -f "dangling=true")
docker volume prune

Remove every volume not currently in use by any container.

Common pitfall: A stopped container counts as "in use". A volume only used by a deleted container counts as "unused" and will be pruned.

Examples
docker volume prune
docker volume prune -a -f
docker run --mount type=volume,...

The explicit, verbose alternative to -v. Each option is a key=value pair, harder to typo silently.

Common pitfall: With `-v`, a typo in the source path silently creates a NEW empty volume. `--mount` errors out instead — safer for prod.

Examples
docker run --mount type=volume,source=pgdata,target=/var/lib/postgresql/data postgres
docker run --mount type=bind,source=$(pwd),target=/app,readonly node:20
docker run --mount type=tmpfs,...

Mount an in-memory tmpfs into the container; data is fast and vanishes on stop. Good for secrets/scratch.

Examples
docker run --mount type=tmpfs,target=/tmp,tmpfs-size=64m myapp
docker run --tmpfs /run:rw,size=16m nginx
docker volume create --opt (nfs)

Create a volume backed by an NFS share via the local driver options.

Examples
docker volume create --driver local --opt type=nfs --opt o=addr=10.0.0.5,rw --opt device=:/exports/data nfsdata
volume backup via tar

Back up a named volume by running a throwaway container that tars its contents to the host.

Common pitfall: There is no `docker volume backup` command. The tar-through-a-container pattern is the standard idiom.

Examples
docker run --rm -v pgdata:/data -v $(pwd):/backup alpine tar czf /backup/pgdata.tar.gz -C /data .
docker run --rm -v pgdata:/data -v $(pwd):/backup alpine tar xzf /backup/pgdata.tar.gz -C /data
System (13)
docker system df

Show disk usage for images, containers, volumes, and build cache (the `du` of docker).

Examples
docker system df
docker system df -v
docker system prune

Remove stopped containers, dangling images, unused networks, and build cache in one shot.

Common pitfall: `-a --volumes` ALSO removes unused images + volumes. People run this and lose database data. Read the prompt before confirming.

Examples
docker system prune
docker system prune -a
docker system prune -a --volumes
docker system info

Print daemon-wide info: total containers/images, storage driver, kernel, OS, registry mirrors.

Examples
docker info
docker info --format "{{.ServerVersion}}"
docker version

Show client + server version, API version, Go version, git commit.

Examples
docker version
docker version --format "{{.Server.Version}}"
docker events

Live stream of daemon events: container start/stop, image pull, network create. Great for debugging.

Examples
docker events
docker events --filter "type=container"
docker events --since 1h --until 5m
docker login

Authenticate to a registry. Credentials get cached in ~/.docker/config.json.

Common pitfall: On shared machines, config.json may store creds in plaintext. Use `docker-credential-helpers` (osxkeychain / pass) for real protection.

Examples
docker login
docker login ghcr.io
echo $TOKEN | docker login -u user --password-stdin ghcr.io
docker logout

Remove cached registry credentials.

Examples
docker logout
docker logout ghcr.io
docker context ls

List docker contexts (local socket, remote SSH host, Desktop). Switch which daemon the CLI talks to.

Common pitfall: Running commands against the wrong context (e.g. prod instead of local) is a classic foot-gun. Check `docker context show` first.

Examples
docker context ls
docker context use my-remote
docker context create remote --docker "host=ssh://user@host"
docker builder prune

Reclaim disk used specifically by the BuildKit build cache, leaving images and containers untouched.

Common pitfall: `docker system df` often shows build cache as the single biggest consumer. Prune it here without nuking images.

Examples
docker builder prune
docker builder prune -af --filter "until=72h"
docker stats --format

Stream container stats as a custom one-line format instead of the full live table.

Examples
docker stats --no-stream --format "{{.Name}}: {{.MemUsage}}"
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemPerc}}"
docker inspect --format (template)

Use Go templates to extract exactly the fields you want from any object’s inspect JSON.

Common pitfall: Inside `--format` use `{{json .Field}}` to dump a sub-object as JSON, and `{{index .Map "key"}}` to read a map by key.

Examples
docker inspect --format "{{json .Mounts}}" web
docker inspect --format "{{index .Config.Labels \"version\"}}" web
docker system events --filter

Subscribe to a filtered live event stream — e.g. only container die events — for alerting or audit.

Examples
docker events --filter "event=die"
docker events --filter "image=nginx" --filter "event=start"
docker info --format (driver)

Quickly check the storage driver, cgroup version, or default runtime without scrolling all of `docker info`.

Examples
docker info --format "{{.Driver}}"
docker info --format "{{.CgroupVersion}}"
Compose (18)
docker compose up

Create + start all services defined in compose.yaml. Add -d for background.

Common pitfall: `docker-compose` (with dash) is V1 and deprecated. Use `docker compose` (space) which is the V2 plugin built into modern Docker.

Examples
docker compose up
docker compose up -d
docker compose up --build
docker compose up web db
docker compose down

Stop AND remove all containers, networks, default network. Add -v to also remove named volumes.

Common pitfall: `down -v` wipes DATA volumes. People do this in dev then run the same command in staging and lose user data. Treat -v as destructive.

Examples
docker compose down
docker compose down -v
docker compose down --rmi all
docker compose ps

List containers managed by this compose project (with health + ports).

Examples
docker compose ps
docker compose ps --status running
docker compose logs

Tail aggregated logs from all services. -f follows, --tail limits per-service.

Examples
docker compose logs
docker compose logs -f web
docker compose logs --tail=50 -f
docker compose build

Build (or rebuild) all services that have a build: block in compose.yaml.

Common pitfall: `docker compose up` does NOT rebuild on Dockerfile changes by default. Pair with `--build` or run `build` first.

Examples
docker compose build
docker compose build --no-cache web
docker compose build --pull
docker compose restart

Restart all (or named) services without recreating containers.

Examples
docker compose restart
docker compose restart web
docker compose exec <svc> <cmd>

Run a command in an already-running compose service (vs `run` which starts a new container).

Examples
docker compose exec web bash
docker compose exec db psql -U postgres
docker compose exec -T db pg_dump mydb > backup.sql
docker compose run <svc> <cmd>

Start a NEW one-off container for a service to run a command. Networks attached, volumes mounted, but no port publishing by default.

Common pitfall: `compose run` does NOT publish ports defined in compose.yaml — pass --service-ports if you need them.

Examples
docker compose run --rm web npm test
docker compose run --rm --service-ports web bash
docker compose pull

Pull the latest images for all services with an image: block.

Examples
docker compose pull
docker compose pull web db
docker compose config

Parse + validate compose.yaml and print the merged, resolved config. Great for debugging env var interpolation.

Examples
docker compose config
docker compose config --services
docker compose -f compose.yaml -f compose.prod.yaml config
docker compose stop

Stop services without removing containers. `start` brings them back later.

Examples
docker compose stop
docker compose stop web
docker compose up -d --wait

Start services detached and block until they all report healthy (or fail). Ideal for CI.

Common pitfall: `--wait` only works if your services define a healthcheck. Without one, compose considers "started" = "ready", which it often is not.

Examples
docker compose up -d --wait
docker compose up -d --wait --wait-timeout 60
docker compose --profile <p> up

Start only services tagged with a given profile. Lets one compose file hold dev-only / debug-only services.

Examples
docker compose --profile debug up
docker compose --profile prod up -d
docker compose pull --policy missing

Control when compose pulls images. `missing` pulls only images you do not have locally.

Examples
docker compose pull --policy missing
docker compose up --pull never
docker compose watch

Watch source files and auto-sync/rebuild services per the `develop.watch` block in compose.yaml.

Common pitfall: `watch` needs a `develop:` section in your service; it is not on by default. It is the compose-native hot-reload, no bind mount needed.

Examples
docker compose watch
docker compose up --watch
docker compose -p <name> ...

Set the compose project name explicitly, isolating container/network/volume names from other stacks.

Common pitfall: Default project name = the folder name. Two clones in same-named folders collide. Set `-p` (or COMPOSE_PROJECT_NAME) per stack.

Examples
docker compose -p staging up -d
COMPOSE_PROJECT_NAME=ci docker compose up
docker compose cp <svc>:<src> <dst>

Copy files between a compose service container and the host (the compose-aware `docker cp`).

Examples
docker compose cp db:/var/lib/postgresql/data/pg_hba.conf ./
docker compose cp ./seed.sql db:/tmp/
docker compose top

Show the running processes inside each service’s containers, grouped by service.

Examples
docker compose top
docker compose top web
Build techniques (17)
DOCKER_BUILDKIT=1 docker build

Enable BuildKit — the modern build engine with parallel layers, cache mounts, secrets, much faster builds.

Common pitfall: BuildKit is default since Docker Engine 23.0. On older daemons you must set DOCKER_BUILDKIT=1 each time or in daemon.json.

Examples
DOCKER_BUILDKIT=1 docker build -t myapp .
docker buildx build -t myapp .
docker build --target <stage>

In a multi-stage Dockerfile, build only up to the named stage. Useful for dev images that stop at the `builder` stage.

Examples
docker build --target builder -t myapp:dev .
docker build --target prod -t myapp:prod .
docker build --platform <plat>

Build for a specific target platform. Supports cross-arch (linux/arm64 from amd64 host) via emulation.

Common pitfall: Building cross-arch via QEMU emulation is 5-20x slower than native. Use `docker buildx` + remote ARM builder for production multi-arch.

Examples
docker build --platform linux/amd64 -t myapp .
docker buildx build --platform linux/amd64,linux/arm64 -t myorg/myapp --push .
docker build --build-arg <KEY=VALUE>

Pass a build-time variable matching an ARG in the Dockerfile.

Common pitfall: ARG values end up in `docker history` — do NOT pass secrets this way. Use BuildKit `--secret` instead.

Examples
docker build --build-arg NODE_VERSION=20 -t myapp .
docker build --build-arg GIT_SHA=$(git rev-parse HEAD) -t myapp .
docker buildx build --secret

Pass a secret into the build that does NOT end up in the final image or `docker history`.

Examples
docker buildx build --secret id=npmrc,src=$HOME/.npmrc -t myapp .
RUN --mount=type=secret,id=npmrc cp /run/secrets/npmrc ./
docker buildx build --cache-from

Reuse build cache from a remote image (great for CI where the local cache is empty).

Examples
docker buildx build --cache-from type=registry,ref=myorg/myapp:cache --cache-to type=registry,ref=myorg/myapp:cache,mode=max -t myorg/myapp:v1 --push .
.dockerignore

Tell docker which paths to EXCLUDE from the build context. Same syntax as .gitignore.

Common pitfall: Without `.dockerignore`, docker uploads node_modules, .git, dist, .env to the daemon — slow builds and accidental secret leaks in layers.

Examples
echo "node_modules\n.git\ndist\n.env*" > .dockerignore
multi-stage Dockerfile

Use multiple FROM blocks to build in one stage (with toolchain) and copy only artifacts into a tiny runtime image.

Common pitfall: Without multi-stage, your prod image includes gcc, npm, source code, tests — easily 1GB+. With multi-stage, the same app fits in 50MB.

Examples
FROM node:20 AS builder\nWORKDIR /app\nCOPY . .\nRUN npm ci && npm run build\n\nFROM nginx:alpine\nCOPY --from=builder /app/dist /usr/share/nginx/html
docker buildx

Extended build command (BuildKit). Multi-platform, cache backends, output to registry/tar/oci, all in one.

Examples
docker buildx create --use --name multi
docker buildx build --platform linux/amd64,linux/arm64 -t myorg/app --push .
docker buildx ls
RUN --mount=type=cache,...

BuildKit cache mount: persist package-manager caches across builds without baking them into a layer.

Common pitfall: A cache mount survives between builds but never ships in the image — perfect for ~/.npm, /root/.cache/pip, go mod cache.

Examples
RUN --mount=type=cache,target=/root/.npm npm ci
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
docker buildx bake

Build a whole group of targets from a docker-bake.hcl / compose file in one parallel, declarative run.

Examples
docker buildx bake
docker buildx bake --push web api
docker buildx bake -f docker-bake.hcl --set "*.platform=linux/amd64,linux/arm64"
docker build --output type=local

Export build artifacts straight to the host filesystem instead of producing a container image.

Common pitfall: With `--output type=local,dest=./out` the final stage’s filesystem lands on disk — handy for building static binaries or sites.

Examples
docker buildx build --output type=local,dest=./dist .
docker buildx build -o type=tar,dest=out.tar .
docker build --progress=plain

Print full, non-collapsed build logs (every RUN line) instead of the tidy TTY view. Essential for CI debugging.

Examples
docker build --progress=plain --no-cache -t myapp .
BUILDKIT_PROGRESS=plain docker build -t myapp .
HEALTHCHECK in Dockerfile

Bake a healthcheck into the image so every container from it reports health automatically.

Common pitfall: A Dockerfile `HEALTHCHECK` is inherited by all containers; a `docker run --health-cmd` only applies to that one run and overrides it.

Examples
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost/ || exit 1
HEALTHCHECK NONE  # disable an inherited check
ENTRYPOINT vs CMD

ENTRYPOINT sets the fixed executable; CMD sets default args. Together they make a configurable container command.

Common pitfall: Use the exec form `["nginx","-g","daemon off;"]`, not shell form. Shell form wraps in /bin/sh -c and swallows SIGTERM.

Examples
ENTRYPOINT ["python", "app.py"]\nCMD ["--port", "8080"]
docker run myapp --port 9090  # overrides CMD, keeps ENTRYPOINT
COPY --chown / --chmod

Set ownership and permissions of copied files in one step, avoiding an extra RUN chown layer.

Examples
COPY --chown=node:node . /app
COPY --chmod=755 entrypoint.sh /usr/local/bin/
COPY --from=<image>

Copy files from another image (not just an earlier build stage) into the current stage.

Examples
COPY --from=golang:1.22 /usr/local/go/bin/go /usr/local/bin/go
COPY --from=builder /app/dist /usr/share/nginx/html
Common errors (17)
Cannot connect to the Docker daemon

Daemon is not running, or your user is not in the docker group. On Linux: `sudo systemctl start docker` then `sudo usermod -aG docker $USER` and re-login.

Common pitfall: On macOS/Windows the daemon is Docker Desktop — open the app. WSL2 needs Docker Desktop's WSL integration enabled per distro.

Examples
sudo systemctl start docker
sudo systemctl status docker
docker context ls
permission denied while trying to connect (Linux)

Your user is not in the `docker` group. Add yourself and re-login (group membership is loaded at login).

Common pitfall: `sudo docker` works but every command needing sudo defeats the purpose. Group membership only takes effect on a fresh login (or `newgrp docker`).

Examples
sudo usermod -aG docker $USER
newgrp docker
docker ps
image too large

Switch to a slim base (alpine / distroless), use multi-stage, run `npm ci --omit=dev`, and put your COPY of large dirs LAST so cache works.

Common pitfall: Each RUN creates a layer — `RUN apt update && apt install -y x && rm -rf /var/lib/apt/lists/*` in ONE line is much smaller than three separate RUNs.

Examples
FROM node:20-alpine
FROM gcr.io/distroless/nodejs20
docker history --no-trunc myapp:latest
container exited with code 137 (OOMKilled)

137 = 128 + SIGKILL(9). The kernel OOM killer reaped your container. Either bump --memory or fix the leak.

Common pitfall: On Docker Desktop the VM has its own memory cap (default 2GB on older versions, 8GB on newer). Bump it in Settings > Resources.

Examples
docker run -m 1g myapp
docker inspect --format "{{.State.OOMKilled}}" web
docker stats --no-stream web
container exited with code 125 / 126 / 127

125 = docker itself errored; 126 = command found but not executable; 127 = command not found in the container.

Common pitfall: Code 127 hits hard with alpine — many distros have `bash` but alpine ships only `sh`. Use `sh` in exec/run or install bash.

Examples
docker run --rm alpine sh -c "echo hi"
docker run --rm alpine bash  # exit 127
docker run --rm alpine apk add --no-cache bash
no space left on device

Docker fills /var/lib/docker. Run `docker system prune` first, then `docker system df` to see what is left.

Common pitfall: On Docker Desktop the disk is a sparse VM file — pruning frees logical space but the .raw file does not shrink automatically. Reset disk image as last resort.

Examples
docker system df
docker system prune -a --volumes
sudo du -sh /var/lib/docker
address already in use (port conflict)

Another process (often a previous container) holds the host port. Find it: `lsof -i :<port>` or `docker ps -a` then stop/remove.

Examples
docker ps -a --filter "publish=8080"
lsof -i :8080
docker rm -f $(docker ps -aq -f "publish=8080")
manifest unknown / image not found

The tag does not exist in the registry. Check the spelling, verify with `docker buildx imagetools inspect <image>` or browse the registry UI.

Common pitfall: For private registries this can also mean you are not authenticated — `docker login` first. ARM users hitting amd64-only images get this too.

Examples
docker buildx imagetools inspect ghcr.io/user/app:v1
docker login ghcr.io
docker pull --platform linux/amd64 myimg
Docker Desktop vs Podman vs nerdctl

All three speak the same CLI. Desktop is the official GUI bundle (paid for big orgs). Podman is daemonless and rootless by default. nerdctl ships with containerd.

Common pitfall: Podman aliases `docker` to `podman` — handy until something assumes a docker socket at /var/run/docker.sock. Either start `podman system service` or keep real docker.

Examples
alias docker=podman
podman system service --time=0 unix:///tmp/podman.sock &
nerdctl run hello-world
exec format error

You are running an image built for a different CPU architecture (e.g. arm64 image on amd64 host).

Common pitfall: Common on Apple Silicon pulling amd64-only images, or CI on amd64 running an arm64 build. Add `--platform` or build multi-arch.

Examples
docker run --platform linux/amd64 myimg
docker buildx build --platform linux/amd64,linux/arm64 -t myorg/app --push .
COPY failed: file not found in build context

The path in COPY is outside the build context, or excluded by .dockerignore.

Common pitfall: COPY paths are relative to the build context root (the last arg of `docker build`), not to the Dockerfile’s folder. You cannot COPY ../something.

Examples
docker build -f docker/Dockerfile .   # context is "."
cat .dockerignore   # check nothing excludes the file
changes inside container disappear after restart

The container’s writable layer is ephemeral. Without a volume, anything written there is lost on rm/recreate.

Common pitfall: `docker stop`+`docker start` keeps the writable layer; `docker rm`+`docker run` does NOT. For data that must survive, use a volume.

Examples
docker run -v pgdata:/var/lib/postgresql/data postgres
docker inspect --format "{{.Mounts}}" db
localhost inside container is not the host

Inside a container, `localhost` is the container itself, not the host machine or another container.

Common pitfall: To reach the host from a container use `host.docker.internal` (Desktop) or `--add-host host.docker.internal:host-gateway` (Linux). To reach another container, use its service/container name on a shared network.

Examples
docker run --add-host host.docker.internal:host-gateway myapp
curl http://host.docker.internal:5432
failed to solve: failed to read dockerfile

BuildKit cannot find the Dockerfile — wrong -f path, or no Dockerfile in the context.

Common pitfall: The default filename is `Dockerfile` (capital D). On case-sensitive filesystems `dockerfile` will not be found without `-f`.

Examples
docker build -f path/to/Dockerfile .
ls -la Dockerfile
tls: failed to verify certificate / x509

Pulling from a registry with a self-signed or untrusted cert. The daemon refuses the TLS handshake.

Common pitfall: For a private registry, add it under `insecure-registries` in daemon.json (dev only), or install its CA into the host trust store (prod).

Examples
/etc/docker/daemon.json: {"insecure-registries":["registry.local:5000"]}
sudo cp registry-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
context canceled / build hangs at sending build context

A huge build context (gigabytes) is being uploaded to the daemon before the build even starts.

Common pitfall: Almost always a missing or weak .dockerignore. Check the "transferring context" size in build output, then exclude node_modules/.git/dist.

Examples
printf "node_modules\n.git\ndist\n*.log\n" > .dockerignore
du -sh . --exclude=node_modules
health check stuck "health: starting"

The container is still inside its `start-period` window, so an early failing check is not counted yet.

Common pitfall: If it never leaves "starting", your `--health-cmd` is failing every time. Run the command manually with `docker exec` to see why.

Examples
docker inspect --format "{{json .State.Health}}" web
docker exec web sh -c "curl -f http://localhost/ || echo FAIL"

What this tool does

Searchable docker cheat sheet covering the 80+ commands you actually type at the terminal — not the toy hello-world list. Eight categories: image (pull, push, build, images, rmi, tag, save, load, history, scout, prune, inspect), container (run, start, stop, restart, rm, ps, exec, logs, attach, cp, inspect, stats, top, kill, rename, pause, unpause, commit, diff, wait, port, plus the -it / -d / --rm / -p / -v / -e / --restart flags broken out so you stop guessing), network (create / ls / inspect / connect / disconnect / rm and the "default bridge has no DNS" trap), volume (create / ls / inspect / rm / prune with the data-loss warnings), system (df / prune / info / version / events / login / logout), Compose V2 (up / down / ps / logs / build / restart / exec / run / pull / config / stop with the `docker-compose` vs `docker compose` deprecation note), build techniques (BuildKit, multi-stage Dockerfile, .dockerignore, --build-arg, --target, --platform, --secret, --cache-from, buildx), and common errors with fixes (cannot connect to daemon, permission denied, image too large, OOMKilled exit 137, exit 125/126/127, no space left on device, port already in use, manifest unknown, Docker Desktop vs Podman vs nerdctl). Every entry shows the full syntax, a Chinese AND English description, the trap people actually hit ("rm vs rmi", "-it pieces apart", "--rm is exit-time, not image-time", "ARG values leak into history, never put secrets there"), and one to four copy-ready examples. Search filters across command + description + pitfall + example text simultaneously, category chips scope the list, one-click copy on every command. Fully client-side, no upload, no tracking. Pair with our Git Cheatsheet and Crontab Helper for the other two things every dev Googles weekly.

Tool details

Input
Text
The page exposes text boxes, numeric controls, file pickers, or structured inputs depending on the tool.
Output
Live result + Copy
The result area focuses on usable output, with copy, download, or preview actions when supported.
Privacy
Browser-side processing
The main tool logic does not call an external API, so inputs normally stay in the current tab.
Save / share
No account required
Open the page and use it; whether results survive refresh depends on the tool.
Performance budget
Initial JS <= 25 KB
No WASM budget is declared, keeping the tool quick to open on mobile.
Best fit
Developer & DevOps · Developer
Category and role tags drive related tools, internal links, and quick fit checks.

How to use

  1. 1. Input

    Paste or drop your content into the tool panel.

  2. 2. Process

    Click the button. All processing is local in your browser.

  3. 3. Copy / Download

    Copy the result or download to disk in one click.

How Docker Cheatsheet fits into your work

Use it in the small gaps between coding, reviewing, debugging, and shipping.

Developer jobs

  • Formatting, validating, shrinking, or inspecting code-adjacent text.
  • Preparing snippets for documentation, tickets, commits, or handoff.
  • Checking a small payload quickly without switching tools.

Developer checks

  • Run irreversible transforms like minify or obfuscate on a copy.
  • Keep secrets out of pasted snippets unless the tool explicitly stays local.
  • Use your normal tests or linter before shipping transformed code.

Good next steps

These links move the current task into a more complete workflow.

  1. 1 JSON Formatter & Validator Format, validate, and minify JSON instantly — right in your browser. Open
  2. 2 Git Cheatsheet Git command cheat sheet — searchable, with explanations, common mistakes, and real examples. Open
  3. 3 Regex Cheatsheet Interactive regex cheat sheet — quick reference for every flavor (JS, Python, PCRE). Open

Real-world use cases

  • Onboarding a junior who keeps deleting the wrong thing

    A new hire ran `docker rm myimage` to free disk, got "no such container", then tried `-f` and removed a running database. Send them the Container category, point at the `rm` vs `rmi` pitfall line, and the search box matches "delete" across both. Five minutes of reading beats a 40-minute incident and a restored volume.

  • Debugging a container that exits with 137 in CI

    Your build job dies with exit 137 and the pipeline log says nothing useful. Type "137" or "OOM" in the search and the exit-code entry surfaces the OOMKilled check command plus the `--memory` and Docker Desktop VM-cap fixes. You raise the runner memory from 2GB to 4GB and the 3-hour green-then-red flake stops.

  • Shrinking a 1.2GB image before a slow registry push

    A deploy to a remote region takes 9 minutes because the image is 1.2GB. Filter to Build techniques, copy the multi-stage Dockerfile and `.dockerignore` patterns, switch the runtime base to distroless, and the image drops to 140MB. The push falls to under a minute and your rollback window shrinks with it.

  • Settling the docker-compose vs docker compose argument

    Half the team scripts `docker-compose` (dash) and CI throws "command not found" on a fresh runner. Search "compose", read the V2 deprecation note, and you do one sed pass swapping the dash for a space across 14 Makefiles. The runner uses the built-in Go plugin and the red CI goes green without installing the old Python binary.

Common pitfalls

  • Running `docker rm image` to delete an image — `rm` removes containers, `rmi` (or `docker image rm`) removes images; mixing them gives "no such container".

  • Putting secrets in `--build-arg` — ARG values are baked into `docker history`, so anyone with the image can read your token; use `--secret` with BuildKit instead.

  • Expecting service discovery on the default `bridge` network — it has no DNS, so `ping web` fails; create a user-defined network (`docker network create app`) and containers resolve each other by name.

Privacy

This cheat sheet is a single static page. Your search text is matched against an in-memory array of commands entirely in your browser, and nothing is uploaded, logged, or written to the URL. Open DevTools and watch the Network tab while you type — you will see zero requests. It works behind corporate proxies, on a plane, or on an air-gapped jump host.

FAQ

Tool combos

Folks in your role tend to reach for these alongside this tool.

Made by Toolora · 100% client-side · Updated 2026-06-13