Docker CLI Cheatsheet - Run, Build & Compose Commands

A Docker command reference for app developers and SREs, covering image build, container lifecycle, networks & volumes, Compose orchestration, and resource cleanup. Unlike OS-level container tools, Docker layered images and isolation are what matter when you must debug startup failures, mapping mistakes, or image bloat. By the end you can bring a service up from an image and troubleshoot the three most frequent problems: startup, networking, and disk usage.

Containers & Orchestration·52 commands·Last updated 2026-09-10
dockercomposeImagesContainers

Typical Use Case

For app developers and SREs: run a local service from an image, build reproducible images, orchestrate multi-container stacks with Compose, and independently diagnose startup failures, port-mapping mistakes, image bloat, and disk-full conditions.

Image 8

docker images
List local images, add -a to include intermediate layers
docker pull nginx:alpine
Pull image with tag, defaults to latest if omitted
docker build -t app:1.0 .
Build and tag from Dockerfile in current dir
docker rmi <image>
Remove image, stop container first or use -f
docker tag app:1.0 reg/app:1.0
Tag image for registry push
docker save -o app.tar app:1.0
Export image as tar for offline transfer
docker load -i app.tar
Load image from tar file, useful in offline environments
docker pull alpine:3.20 --platform=linux/amd64
Pull image for a specific platform, e.g. amd64 on ARM Mac

Container 9

docker ps -a
List all containers including stopped
docker run -d -p 8080:80 --name web nginx
Run detached, map port, name container
docker exec -it web sh
Interactive shell into running container
docker logs -f --tail 100 web
Follow last 100 lines of container logs
docker stop web && docker rm web
Stop and remove container
docker inspect web
Full container config JSON for network/mount debugging
docker start web && docker restart web
Start or restart a stopped container
docker stats
Live CPU/memory/network I/O stats for all containers
docker top web
List running processes inside a container

Network & Volume 8

docker network ls
List networks, check here first for inter-container access
docker network create appnet
Create custom bridge network for name-based discovery
docker network connect appnet web
Connect a running container to a network
docker volume ls
List volumes
docker run -v data:/var/lib/app app
Mount named volume for persistence
docker run -v $(pwd):/app app
Bind mount current dir, common in dev
docker volume create appdata
Create a named volume for shared data
docker volume prune
Remove all unused volumes

Registry 6

docker login
Log in to Docker Hub, required before push
docker login registry.example.com
Log in to a private registry (Harbor/Registry)
docker push app:1.0
Push image to remote registry, must tag first
docker pull ubuntu:22.04
Pull Ubuntu 22.04 image from Docker Hub
docker search nginx
Search Docker Hub for official images
docker logout
Log out from the current registry

Build & Debug 7

docker build -t app:1.0 --no-cache .
Force rebuild without cache layers
docker build -t app:1.0 --target=dev .
Build only up to a specific multi-stage target
docker history app:1.0
View image build history, layer sizes and commands
docker diff <container>
Inspect filesystem changes in a container
docker cp app.conf web:/etc/nginx/conf.d/
Copy local config file into a container
docker cp web:/var/log/nginx/access.log ./
Copy a log file from a container to local
docker events --since 5m
Stream Docker daemon events in real time

Compose & Cleanup 9

docker compose up -d
Start Compose project in background
docker compose logs -f svc
Follow logs for a specific service
docker compose down
Stop and remove containers, networks; add -v for volumes
docker compose ps
List container status for all services in Compose project
docker compose restart
Restart all or specified services
docker system df
Check disk usage by images/containers/volumes
docker system prune -a
Clean all unused images and containers, use -a with caution
docker container prune
Remove all stopped containers
docker image prune -a
Remove all unused images to free disk space

FAQ 5

Q: How to clean up all unused Docker resources?
A: docker system prune -a removes all unused images, containers, networks, and build cache. Add --volumes to also remove volumes.
Q: How to view container logs?
A: docker logs <container> shows full logs, add -f to follow, --tail 50 for last 50 lines, --since 5m for last 5 minutes.
Q: How to enter a running container?
A: docker exec -it <container> /bin/bash (or /bin/sh). Exit with exit or Ctrl+D.
Q: How to copy files between host and container?
A: docker cp <src> <container>:<dest> to copy in, docker cp <container>:<src> <dest> to copy out.
Q: What restart policies are available?
A: --restart=no (default)/on-failure/always/unless-stopped. unless-stopped is common for production.

Parameter matrix

参数EffectExample
-d后台(detached)运行容器docker run -d -p 8080:80 nginx
-p端口映射,格式 主机端口:容器端口docker run -d -p 8080:80 nginx
--name为容器指定可读名字,便于后续操作docker run -d --name web nginx
-v挂载数据卷或绑定目录,持久化数据docker run -v /data:/app/data nginx
--rm容器退出后自动删除,避免残留docker run --rm alpine echo hi
-e向容器内注入环境变量docker run -e NODE_ENV=prod app
--network加入指定网络,容器间可用名字互访docker run --network appnet web
-it分配交互式终端,用于进入容器 shelldocker exec -it web sh
--restart退出后的重启策略(no/on-failure/always)docker run -d --restart unless-stopped web
--platform指定目标架构(ARM Mac 拉 amd64)docker pull --platform=linux/amd64 nginx
--no-cache构建时忽略层缓存,强制重跑所有层docker build --no-cache -t app .
-f指定 Dockerfile 路径docker build -f Dockerfile.prod -t app .

Common pitfalls

Symptom端口映射后仍无法从宿主机其他进程或外网访问容器服务。

Cause把 主机:容器 写反,或容器内进程只监听 127.0.0.1 而非 0.0.0.0。

Fix确认 -p 8080:80 是「宿主机端口:容器端口」;容器应用需监听 0.0.0.0 才能被外部访问。

Symptomdocker exec 进入容器报 OCI runtime exec failed: exec: "bash": not found。

Cause镜像基于 alpine/scratch 等精简镜像,没有内置 bash。

Fix改用 sh:docker exec -it web sh;或在 Dockerfile 中 apk add bash 后再用 bash。

Symptomdocker build 每次都重新拉取基础镜像、层缓存不命中。

Cause基础镜像用 latest 标签,或把易变的文件(源码)COPY 在不变的文件之前。

Fix固定基础镜像版本(如 node:20-alpine);把不常变的依赖安装层放在前面,源码 COPY 放最后。

Symptom构建或运行报 No space left on device,宿主机磁盘被占满。

Cause大量已停止容器、悬空镜像(<none>)、未清理的数据卷长期累积。

Fix先 docker system df 看占用,再 docker system prune -a --volumes 清理;生产机设定期清理任务。

Symptom容器被强制退出,docker inspect 看到 ExitCode 137。

Cause内存超限被 OOM Killer 杀掉(137 = SIGKILL)。

Fix用 docker stats 看实时内存;为容器设合理 --memory 上限,或优化应用内存占用。

Symptom在 ARM Mac 上拉取的镜像放到 x86 服务器上跑报错 exec format error。

Cause镜像架构与运行环境不一致(arm64 vs amd64)。

Fix构建/拉取时显式指定目标平台:docker build --platform=linux/amd64 -t app . 并推送对应架构镜像。

Symptom在容器内修改了配置文件,重建镜像后改动全部丢失。

Cause容器文件系统是临时的,未挂载持久卷。

Fix用 -v 挂载命名卷或绑定目录(-v /host/path:/container/path)保存需要保留的状态。

Troubleshooting

  1. 1容器起不来或闪退,先看日志

    docker logs --tail 50 web

    从日志末尾定位启动失败的报错(配置错误、依赖缺失、端口占用)。

  2. 2确认容器退出状态与原因

    docker inspect -f '{{.State}}' web

    ExitCode 0=正常退出,137=OOM,139=段错误等,结合 Reason 判断。

  3. 3端口冲突或映射异常时列出所有容器端口

    docker ps --format '{{.Names}}\t{{.Ports}}'

    核对 0.0.0.0:8080->80/tcp 是否如预期,避免端口被其他容器占用。

  4. 4磁盘被占满时先看各对象占用

    docker system df

    区分 Images / Containers / Volumes 占用,再针对性清理。

  5. 5进入容器排查网络连通性

    docker exec -it web sh -c "cat /etc/resolv.conf; ping -c1 8.8.8.8"

    分别验证 DNS 解析与出网连通,定位是网络配置还是镜像问题。

Command Examples

Run nginx in the background with a port mapping

docker run -d --name web -p 8080:80 nginx:alpine

-p 8080:80 表示宿主机 8080 转发到容器 80,访问 http://localhost:8080 即可看到 nginx 欢迎页;-d 让容器后台运行,--name 便于后续用名字管理。

Output

b3f2c1a9d8e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b

Bind-mount the current directory and enter an interactive shell

docker run -it --rm -v "$(pwd)":/app -w /app node:18-alpine sh

-v 把当前目录挂载到容器 /app,-w 设为工作目录,--rm 退出时自动删除容器,-it 提供交互终端,适合本地调试 Node 应用而无需本地安装 Node。

Follow the last 100 lines of a container log

docker logs -f --tail 100 web

-f 实时跟踪后续日志,--tail 100 只从最后 100 行开始输出,排查启动崩溃或请求异常时第一命令。

Prune unused images to free disk space

docker system df

先 docker system df 看占用,再决定是否 docker image prune -a 清理所有未被容器引用的镜像;删镜像前务必确认没有需要保留的版本。

Output

TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          12        5         1.4GB     621.5MB (43%)
Containers      8         3         5.6MB     5.6MB (100%)

Common Pitfalls

  • docker run -p is host_port:container_port — reversed means external access never works, and it fails silently, the hardest thing to debug.
  • prune -a removes every image no container is using, including freshly built but not-yet-run versions. Run docker images first on production.
  • An "executable file not found" error usually means the image lacks that shell; Alpine ships only sh, so use docker exec -it <c> sh.
  • Flags like -e env vars and port mappings cannot be changed after the container starts; you must stop, remove, and re-run.
  • A permission denied on bind mounts often comes from a mismatch between the host directory owner and the container user.

Tips

  • In docker run -p, it's host_port:container_port — reversing them blocks external access.
  • If exec says "executable file not found", switch to sh: Alpine images usually lack bash.
  • prune -a removes all images not used by any container — verify with docker images first on production.
  • docker system df quickly shows disk usage — run it periodically to avoid /var/lib/docker filling up.
  • docker compose restart is faster than down/up and does not rebuild networks or volumes — best for nginx config changes.

FAQ

What is the difference between docker run and docker start?

docker run creates and starts a new container from an image (first launch); docker start restarts an existing but stopped container without creating a new instance. Use start to debug existing state, run to deploy new services.

How do I free up disk space used by Docker?

Use docker system prune to remove stopped containers, dangling images, and build cache; add -a to also remove all images not referenced by any container. Use cautiously in production to avoid deleting valuable images.

What is the relationship between a container and an image?

An image is a read-only template containing the code, dependencies, and config needed to run an app; a container is a running instance of that image with a writable layer on top. One image can launch multiple isolated containers.

Why does my container exit immediately with status Exited (0)?

Check the exit code with docker ps -a: Exited (0) usually means the foreground process did not stay alive (the command finished and exited), so use -it or switch to a foreground command in the Dockerfile (e.g. CMD ["nginx","-g","daemon off;"]). For non-zero codes, run docker logs <id> to read the real error, usually a missing dependency, permission, or wrong config path.

Why can I not reach localhost from inside a container?

Inside a container, localhost refers to the container itself, not the host, so host services are unreachable via localhost. To reach a host service, use the default bridge gateway IP (host.docker.internal on macOS/Windows, --network host or the host LAN IP on Linux). To make containers talk to each other, join them to a custom network and address them by container name.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Sep 10, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us