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.
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 imagesdocker pull nginx:alpinedocker build -t app:1.0 .docker rmi <image>docker tag app:1.0 reg/app:1.0docker save -o app.tar app:1.0docker load -i app.tardocker pull alpine:3.20 --platform=linux/amd64Container 9
docker ps -adocker run -d -p 8080:80 --name web nginxdocker exec -it web shdocker logs -f --tail 100 webdocker stop web && docker rm webdocker inspect webdocker start web && docker restart webdocker statsdocker top webNetwork & Volume 8
docker network lsdocker network create appnetdocker network connect appnet webdocker volume lsdocker run -v data:/var/lib/app appdocker run -v $(pwd):/app appdocker volume create appdatadocker volume pruneRegistry 6
docker logindocker login registry.example.comdocker push app:1.0docker pull ubuntu:22.04docker search nginxdocker logoutBuild & Debug 7
docker build -t app:1.0 --no-cache .docker build -t app:1.0 --target=dev .docker history app:1.0docker diff <container>docker cp app.conf web:/etc/nginx/conf.d/docker cp web:/var/log/nginx/access.log ./docker events --since 5mCompose & Cleanup 9
docker compose up -ddocker compose logs -f svcdocker compose downdocker compose psdocker compose restartdocker system dfdocker system prune -adocker container prunedocker image prune -aFAQ 5
Q: How to clean up all unused Docker resources?Q: How to view container logs?Q: How to enter a running container?Q: How to copy files between host and container?Q: What restart policies are available?Parameter matrix
| Parameter | Effect | Example |
|---|---|---|
-d | Run the container detached in the background | docker run -d -p 8080:80 nginx |
-p | Publish a port, written hostPort:containerPort | docker run -d -p 8080:80 nginx |
--name | Give the container a readable name for later commands | docker run -d --name web nginx |
-v | Mount a volume or bind directory so data outlives the container | docker run -v /data:/app/data nginx |
--rm | Delete the container on exit so nothing is left behind | docker run --rm alpine echo hi |
-e | Inject an environment variable into the container | docker run -e NODE_ENV=prod app |
--network | Attach to a named network so containers resolve each other by name | docker run --network appnet web |
-it | Allocate an interactive TTY, used when entering a container shell | docker exec -it web sh |
--restart | Restart policy applied after exit: no, on-failure or always | docker run -d --restart unless-stopped web |
--platform | Target a specific architecture, such as amd64 images on an ARM Mac | docker pull --platform=linux/amd64 nginx |
--no-cache | Ignore the layer cache at build time and rerun every layer | docker build --no-cache -t app . |
-f | Point at a specific Dockerfile | docker build -f Dockerfile.prod -t app . |
Common pitfalls
SymptomAfter publishing a port, nothing on the host or the network can reach the service.
CauseThe host:container order is reversed, or the process inside listens on 127.0.0.1 instead of 0.0.0.0.
FixRemember -p 8080:80 means host port first; the application inside the container must bind 0.0.0.0 to be reachable.
Symptomdocker exec fails with OCI runtime exec failed: exec: "bash": not found.
CauseThe image is built on alpine or scratch, neither of which ships bash.
FixFall back to sh with docker exec -it web sh, or install bash in the Dockerfile via apk add bash first.
SymptomEvery docker build re-pulls the base image and never hits the layer cache.
CauseThe base image uses the latest tag, or frequently changing files such as source are copied before stable ones.
FixPin the base version (node:20-alpine) and put dependency installation ahead of the source COPY.
SymptomBuild or run reports No space left on device and the host disk is full.
CauseStopped containers, dangling (<none>) images and unused volumes have piled up over time.
FixInspect usage with docker system df, reclaim space with docker system prune -a --volumes, and schedule that cleanup on production hosts.
SymptomA container is killed and docker inspect shows ExitCode 137.
CauseIt exceeded its memory limit and the OOM killer sent SIGKILL, which surfaces as 137.
FixWatch live usage with docker stats, then set a sensible --memory limit or reduce what the application allocates.
SymptomAn image pulled on an ARM Mac fails with exec format error on an x86 server.
CauseThe image architecture does not match the runtime: arm64 versus amd64.
FixState the target platform explicitly at build or pull time, for example docker build --platform=linux/amd64 -t app ., and push a matching image.
SymptomConfig edits made inside the container vanish as soon as the image is rebuilt.
CauseThe container filesystem is ephemeral and no persistent volume was mounted.
FixAttach a named volume or bind mount with -v /host/path:/container/path for anything that has to survive.
Troubleshooting
1Container will not start or exits immediately: read the logs
docker logs --tail 50 webThe tail usually holds the startup failure: bad config, missing dependency or a port already in use.
2Check the exit status and reason
docker inspect -f '{{.State}}' webExitCode 0 is a clean exit, 137 is OOM, 139 a segfault and so on; read the Reason field alongside it.
3List every container port when a mapping looks wrong
docker ps --format '{{.Names}}\t{{.Ports}}'Confirm 0.0.0.0:8080->80/tcp is what you expected and that no other container already holds the port.
4See what is consuming disk when the volume fills up
docker system dfBreak the figure down by Images, Containers and Volumes, then clean up the category that dominates.
5Enter the container to check network connectivity
docker exec -it web sh -c "cat /etc/resolv.conf; ping -c1 8.8.8.8"Testing DNS and outbound reach separately tells you whether the problem is your network config or the image.
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