Docker & Compose Cheatsheet
Copy-ready CLI reference for Docker Engine and Docker Compose v2. Verified syntax for container lifecycle, image building, volume persistence, bridge networking, and disk cleanup.
Container Lifecycle & Execution
docker run -d -p 8080:80 --name my-web nginxStarts an Nginx container in detached background mode, mapping host port 8080 to container port 80.
Pro Tip: The -d flag runs in background; -p exposes ports.
docker psLists all currently running containers with their IDs, names, status, and port bindings.
Pro Tip: Add -a to view stopped containers as well.
docker stop <container_id>Sends SIGTERM signal to gracefully stop a running container (defaults to 10s before SIGKILL).
Pro Tip: Use docker kill for immediate forceful termination.
docker start <container_id>Restarts a previously stopped container preserving its internal state and IP.
Pro Tip: Use docker restart to restart in one step.
docker rm -f <container_id>Forcefully removes a container even if it is currently running.
Pro Tip: Use docker container prune to delete all stopped containers.
docker exec -it <container_id> shOpens an interactive pseudo-TTY shell session inside an active running container.
Pro Tip: Use bash instead of sh for Ubuntu/Debian containers.
docker logs -f --tail 100 <container_id>Follows container stdout/stderr log output in real-time, streaming the last 100 lines.
Pro Tip: Press Ctrl+C to disconnect from the log stream.
Image Building & Registry Operations
docker build -t myapp:1.0 .Builds a Docker image from the Dockerfile in the current directory and tags it as myapp:1.0.
Pro Tip: The trailing dot specifies the build context path.
docker build --no-cache -t myapp:latest .Forces a fresh image build without using any cached intermediate filesystem layers.
Pro Tip: Essential when installing system packages that update upstream.
docker imagesLists all locally stored Docker images with their repository, tag, image ID, and disk size.
Pro Tip: Add -q to list only numeric image IDs.
docker rmi <image_id>Deletes a local image from disk storage.
Pro Tip: Fails if a container (even stopped) references the image.
docker pull ubuntu:24.04Downloads a pre-built image from Docker Hub or a configured private registry.
Pro Tip: Always pin explicit version tags in production.
docker tag myapp:1.0 registry.example.com/myapp:1.0Applies an alternate alias or registry domain tag to an existing image.
Pro Tip: Prepares an image for pushing to private registries.
docker push registry.example.com/myapp:1.0Uploads a tagged image to a remote container registry.
Pro Tip: Requires prior docker login authentication.
Volumes & Data Persistence
docker volume create my-dataCreates a named Docker volume managed independently in the Docker storage directory.
Pro Tip: Named volumes survive container deletion.
docker run -d -v my-data:/var/lib/mysql mysql:8Mounts the named volume my-data to the MySQL data directory inside the container.
Pro Tip: Data persists across container upgrades.
docker run -d -v $(pwd):/app node:20Mounts the current host working directory into /app inside the container (Bind Mount).
Pro Tip: Ideal for local development with hot reloading.
docker volume lsLists all active Docker volumes on the workstation.
Pro Tip: Inspect disk usage with docker system df -v.
docker volume prune -fRemoves all unused anonymous and named volumes not mounted by any container.
Pro Tip: Warning: Irreversible data deletion.
Docker Networking
docker network create my-netCreates a custom bridge network allowing containers to communicate using container names as DNS.
Pro Tip: Containers on default bridge cannot resolve by name.
docker run -d --network my-net --name api myappAttaches the container to the custom bridge network upon creation.
Pro Tip: Other containers on my-net can reach this via http://api.
docker network lsLists all available Docker networks (bridge, host, none, overlay).
Pro Tip: Default bridge network is named bridge.
docker network inspect my-netDisplays detailed network configuration including subnet, gateway, and attached container IPs.
Pro Tip: Returns structured JSON.
Docker Compose (Multi-Container Orchestration)
docker compose up -dBuilds, creates, and starts all services defined in docker-compose.yml in background detached mode.
Pro Tip: Docker Compose v2 uses "docker compose" (no hyphen).
docker compose downStops containers and removes containers, networks, and internal links created by up.
Pro Tip: Add -v flag to also delete named volumes.
docker compose logs -f webStreams aggregated stdout/stderr logs for the specific service named web.
Pro Tip: Omit service name to view interleaved logs from all services.
docker compose psLists the status, ports, and state of all containers belonging to the current compose project.
Pro Tip: Only shows services in current directory compose file.
docker compose exec web bashExecutes a command or shell inside the running container of the web service.
Pro Tip: Target by service name rather than random container hash.
docker compose restartRestarts all running service containers without recreating them.
Pro Tip: Fast way to apply configuration file updates.
System Maintenance & Cleanup
docker system dfDisplays comprehensive disk space usage consumed by images, containers, local volumes, and build cache.
Pro Tip: First command to run when disk fills up.
docker system prune -a --volumesReclaims maximum disk space by deleting all stopped containers, unused networks, unreferenced images, and build cache.
Pro Tip: Dramatically frees tens of gigabytes.
docker statsStreams live CPU, Memory, Network I/O, and Block I/O resource consumption for all active containers.
Pro Tip: The top/htop equivalent for Docker.
How Docker Operates: Namespaces, Cgroups, and Union Filesystems
Containers are not Virtual Machines (VMs). A virtual machine bundles a full guest operating system, virtualized hardware drivers, and dedicated hypervisor overhead. In contrast, Docker containers run directly on the host Linux kernel, sharing kernel system calls while isolating user space processes using three core Linux primitives:
- Namespaces: Provide process isolation.
pidnamespace isolates process trees,netisolates IP addresses and routing tables,mntisolates mount points, andipcisolates inter-process communication. - Control Groups (cgroups): Enforce hardware resource limits. Cgroups restrict how much CPU time, RAM memory, and block I/O throughput a container can consume, preventing noisy-neighbor exhaustion.
- OverlayFS / Union Filesystem: Implements copy-on-write (CoW) layering. Docker images are composed of immutable read-only layers. When a container runs, Docker adds a thin read-write container layer on top, saving storage and speeding startup.
Docker vs Virtual Machines (VMs) Comparison
| Feature | Docker Containers | Virtual Machines (VMs) |
|---|---|---|
| Startup Time | Milliseconds to seconds (process launch) | Minutes (full OS boot cycle) |
| Memory Overhead | Extremely low (shares host kernel) | High (each VM allocates dedicated RAM) |
| Storage Footprint | Megabytes (shared base layers) | Gigabytes per virtual disk (VHD/VMDK) |
| Isolation Level | Process-level isolation via kernel namespaces | Hardware-level hypervisor virtualization |
Frequently Asked Questions (FAQs)
What is the difference between Docker Compose v1 (docker-compose) and v2 (docker compose)?
Docker Compose v1 was an independent Python CLI package invoked as 'docker-compose'. Docker Compose v2 is written in Go and integrated directly into the Docker CLI binary as 'docker compose' (with a space). Compose v2 offers superior execution speed, parallel build capabilities via BuildKit, and native Compose specification compatibility.
What is the difference between a Docker Volume and a Bind Mount?
Docker Volumes are managed by the Docker Engine inside /var/lib/docker/volumes/, isolated from the host OS filesystem, and are the recommended persistence mechanism for production databases. Bind Mounts map a specific, arbitrary host file path (e.g. $(pwd)) directly into the container, which is ideal for local development source code synchronization.
Why should I use multi-stage Docker builds?
Multi-stage builds allow you to use heavy SDKs and compilation tools (Node.js, Go compiler, Maven) in early build stages, and then copy only the compiled binary or production static assets into a lean, minimal production base image (like Alpine Linux or Google Distroless). This shrinks image sizes from 1GB+ down to 20MB-50MB and reduces attack surface.
How do containers resolve each other by name on a custom Docker network?
Docker provides an embedded internal DNS server at 127.0.0.11 for user-defined bridge networks. When you create a custom network (docker network create my-net) and attach containers with --name, Docker automatically maps container names to their internal IP addresses, enabling seamless inter-service communication.
Explore Related Tools
Hand-picked utilities and calculators related to this tool.