Docker Commands Cheat Sheet

Common Docker commands: run, ps, build, compose, exec, logs, volume and more, with notes for everyday container work.

How It Works

Docker packages an app with its dependencies as an image, and runs an instance of that image as a container. An image is built from stacked read-only layers (cached and reused); the container adds one writable layer on top, so startup is fast and isolation is strong.

The core lifecycle: build creates an image from a Dockerfile, run starts a container, ps lists running ones, exec runs a command inside, rm/rmi clean up. Mounting a host directory as a volume keeps data alive after the container is removed.

When to Use This Table

This table is for troubleshooting containers or running one-off tasks quickly. Its value is compressing frequent operations into paste-ready commands: reclaiming disk from dangling images, finding why a container exited, getting into a stopped container.

When not to consult it: you are designing container architecture or orchestrating multi-container deployment. Image layering strategy, volume planning and network topology belong to Docker architecture, and this table cannot advise on them — whether a given docker run invocation is any good depends on image trustworthiness and whether data must survive.

Rule of thumb: this table is enough for throwaway verification, CI steps and debugging. Production deployment needs explicit volumes, restart policies, resource limits and log rotation, none of which are covered here, and omitting any of them causes incidents.

Mind --rm together with data volumes: it is convenient for one-off containers, but only if all state lives in a volume. Files written inside a container that is later removed are lost unrecoverably, which is the most common local debugging data loss.

Boundaries and Common Pitfalls

  • Dangling images fill the disk but are invisible in docker images

    Rebuilding tags the previous image as <none>:<none>. docker images filters by repository by default and hides these, yet they still consume disk — the leading cause of disk alerts under frequent builds. Inspect with docker images -f "dangling=true" and remove with docker image prune -f, after confirming no older version is needed for rollback.

  • A "running" container with an unresponsive service may be a host problem

    Up does not mean the app works: the process may be deadlocked while PID 1 survives, may bind the wrong port, or may listen only on 127.0.0.1 so external access fails. Check in order — docker logs for the app output, docker exec plus curl inside the container to confirm it listens, then curl from the host to confirm the port is reachable. That sequence separates application, container networking and firewall causes.

  • Volumes and the container filesystem are separate stores

    The container writable layer disappears with the container; volumes live outside its lifecycle. Files written only inside the container (config, database files, upload directories) vanish when the container is replaced. A bind mount works for development, but production should use named volumes or external storage, and note that bind mounts degrade noticeably in performance on Linux.

How This Relates to Neighbours

Dockerfile instructions and image build practices are not covered here; build context, layer caching and multi-stage builds are their own topic.

To orchestrate multiple containers or schedule across hosts, use Docker Compose or Kubernetes; this table covers single-container operations only.

For connectivity problems, first separate container-to-container traffic (same bridge network) from outbound access (proxy, registry); the latter is unrelated to these commands.

Image security scanning or SBOM generation belongs to supply-chain tooling, not to Docker basics.

Practical Snippet

Key points: (1) dangling images need -f "dangling=true" to be visible and are the top cause of disk alerts, while system prune -a removes every unused resource so inspect scope first; (2) when a container exits, check ExitCode and OOMKilled before the actual entrypoint to separate crashes, OOM and misconfiguration; (3) Up does not mean reachable — curling inside the container and again from the host isolates app, container networking and firewall causes; (4) --rm is only safe when all state lives in a volume.

# ① 磁盘排查:悬空镜像是头号原因(docker images 默认看不见它们)
docker images -f "dangling=true"
docker system df                          # 先看整体占用构成
docker image prune -f                     # 只删悬空镜像,安全
# docker system prune -a 会删所有未使用镜像/网络/卷 —— 先 -f 前三行看清范围再用

# ② 容器为何退出:按 4→1 顺序看
docker ps -a --filter "status=exited" --format '{{.Names}}	{{.Status}}'
docker logs <name> --tail 200            # ① 应用输出
docker inspect <name> --format '{{.State.ExitCode}} {{.State.OOMKilled}} {{.State.Error}}'
docker inspect <name> --format '{{.Path}} {{json .Args}}'   # 实际执行的入口

# ③ Up 但不响应:区分应用 / 容器网络 / 宿主机
docker exec <name> curl -sS -o /dev/null -w '%{http_code}
' http://127.0.0.1:3000  # 容器内
curl -sS -o /dev/null -w '%{http_code}
' http://127.0.0.1:3000                    # 宿主机

# ④ 一次性容器:--rm 前提是数据都在 volume 里
docker run --rm -it --network host node:22-alpine node -e "console.log(1+1)"
docker run --rm -v mydata:/data alpine ls -la /data      # 数据在 volume,删容器不丢

# ⑤ 查端口占用(本机最常踩的坑:Address already in use)
docker ps --format '{{.Names}}	{{.Ports}}' | grep 3000

Practical Notes

  • docker run flags and compose fields are not one-to-onePorts, volumes and environment variables are similar in meaning but different in syntax, and a mechanical conversion easily drops orchestration-only features such as depends_on and healthcheck. Verify field by field rather than only checking that it starts.
  • localhost inside a container is not the hostA container has its own network namespace, so reaching "the database on this machine" requires host.docker.internal (Docker Desktop) or the host private address. This is the first thing to check when something works locally but not in a container.
  • Layer caching plus :latest makes builds irreproducibleWith a :latest base image, the same Dockerfile builds differently at different times. Pin production images to a specific tag or digest, and separate dependency installation from source copying so code edits do not reinstall everything.

Data Sources

  • Docker CLI reference (docs.docker.com)
  • Compose specification (compose-spec.io)

Codes, names and definitions above come from public specifications; we claim no originality over the specification data itself. The arrangement, Chinese annotations and practical notes on this page are written by us.

CommandDescription
docker --versionShow the Docker client version
docker versionShow client and server versions
docker infoDisplay system-wide info
docker loginLog in to a registry
docker pullPull an image from a registry
docker pushPush an image to a registry
docker imagesList local images (-a all)
docker rmiRemove an image (-f force)
docker buildBuild from a Dockerfile (-t tag)
docker runRun a container (-d detach / -p port)
docker psList running containers (-a all)
docker stopStop a running container
docker startStart a stopped container
docker restartRestart a container
docker rmRemove a container (-f force / -v volume)
docker execRun a command in a container (-it)
docker logsFetch container logs (-f follow)
docker cpCopy files between container and host
docker inspectReturn low-level JSON info
docker topShow running processes in a container
docker compose upStart compose services (-d)
docker compose downStop and remove compose resources
docker compose buildBuild images in compose
docker network lsList Docker networks
docker volume lsList volumes
docker system pruneRemove unused data (-a all)
docker statsLive resource usage stats

Frequently Asked Questions

What is the difference between docker run and docker create?

docker create only creates a container without starting it; docker run is create + start, launching the main process immediately (in the foreground, or with -d detached).

How do I enter a running container?

Use docker exec -it <container> /bin/sh (or /bin/bash) for an interactive shell; add --rm to auto-clean the exec process on exit.

How do I see disk space used by containers?

docker system df shows overall image/container/volume usage; docker ps -s shows each container's writable size; clean up with docker system prune -a.

How do I save a container's changes as a new image?

Use docker commit <container> <new-image> to freeze the current state, but writing a Dockerfile is preferred for reproducible, versioned builds.