Docker Commands
Here is a tiered guide to Docker CLI commands, from daily essentials to advanced troubleshooting.
Docker Daily Workflow
The 5 Commands You Will Use 90% of the Time
Think as: Managing a busy restaurant.
docker run: This is like opening the restaurant for the day. You unlock the doors and get everything running.docker ps: This is like the Manager checking the floor. “Are all tables served? Is the kitchen running?”docker exec: This is like going into the kitchen yourself. You enter the working area to fix a specific stove or check the ingredients manually.docker logs: This is like checking the CCTV cameras or security journal. If something broke last night, you check the logs to see exactly what happened and when.docker stop: This is closing time. You gently shut down operations and lock the doors.
–
| Command | Purpose (Simple English) | Key Flags to Remember |
docker run | Creates & starts a new container. | -d (Run in background/detached)-p (Map ports: HostPort:ContainerPort)--name (Give it a custom name) |
docker ps | Lists containers currently running. | -a (Show all, including stopped/crashed)-q (Show only IDs, useful for automation scripts) |
docker stop | Gently stops a container. | None usually, but accepts a timeout. |
docker exec | Enters inside a running container. | -it (Interactive TTY – Mandatory if you want to type commands like bash) |
docker logs | Shows what the app is printing. | -f (Follow/Tail: Watch the logs live as they happen) |
–
Key Characteristics to Remember
- Interactiveness: Most commands are “outside looking in,” but
execis “inside looking around.” - Lifecycle:
runcreates it,stophalts it, but it still exists until yourm(remove) it. - Visibility: If you don’t see it with
docker ps, checkdocker ps -a(it might be dead/stopped).
- A common confusion is
docker stopvsdocker kill.- Stop: Sends a
SIGTERMsignal. It politely asks the app, “Please save your work and close.” The app has 10 seconds to do this. - Kill: Sends
SIGKILL. It is like pulling the power plug immediately. No saving. Usestopfirst; usekillonly if it’s stuck.
- Stop: Sends a
Cleanup: docker stop does not remove the container. It stays on your disk (consuming space) until you run docker rm.
–
The docker run Command: The Creator
This command actually does three things in one go: it pulls the image (if missing), creates the container, and starts it.
docker run -d -p 8080:80 --name my-web-server nginx(Runs Nginx in background, accessible at port 8080).- If you forget
-d, the container “steals” your terminal. If you pressCtrl+C, the container dies. Always use-dfor servers. Official Docker Run Reference
The docker exec Command: The Troubleshooter
This is your “teleportation” tool. It lets you open a terminal inside the container environment.
docker exec -it my-web-server bash#(Opens a bash shell inside the container).- If the container uses Alpine Linux (which is very small),
bashmight not exist. In that case, usesh:docker exec -it my-web-server shOfficial Docker Exec Reference
The docker logs Command: The Investigator
When a container starts but immediately crashes (“Exited (1)”), this command tells you why.
docker logs my-web-serverdocker logs --tail 100 -f my-web-server#(Shows only the last 100 lines and keeps the connection open to show new logs instantly). Official Docker Logs Reference
Key Characteristics
- Ephemeral: Containers are meant to be temporary. Don’t treat them like permanent servers.
- Stateless: By default, if you
stopandrma container, the data inside is lost (unless you use Volumes).
Use Case
- Debugging:
docker logsis used instantly when an API call fails. - Maintenance:
docker execis used to check configuration files inside a running database without stopping it.
Benefits
- Speed: These commands execute in milliseconds.
- Consistency:
docker runworks the exact same way on Windows, Mac, and Linux.
–
Limitations
- Shell Availability:
docker execfails if the container image doesn’t have a shell installed (common in “Distroless” security images). - Log Size: If
docker logsis huge, running it without--tailcan freeze your terminal.
Common Issues & Solutions
| Issue | Problem | Solution |
| Container keeps exiting | The main process finished. | Containers only run as long as the main command is running. Ensure your app runs in the foreground. |
| “Exec: executable file not found” | You tried bash but it’s not installed. | Try sh instead: docker exec -it <id> sh. |
| Port Conflict | “Bind for 0.0.0.0:80 failed” | Another service (or container) is already using port 80. Change the host port: -p 8081:80. |
Lab Docker Daily Workflow
Quiz Docker Daily Workflow
Image Management: Building & Shipping
These commands are for when you move from consuming software to creating it.
docker build -t <name>:<tag> .Builds an image from aDockerfilein the current directory (.). The-tflag tags it (e.g.,myapp:v1).docker imagesLists all images stored locally on your machine.docker pull <image>Downloads an image from Docker Hub (e.g.,docker pull postgres:alpine).docker push <image>Uploads your image to a registry (requiresdocker loginfirst).docker history <image>Shows the layers that make up an image. Great for optimizing size.
–
Building Your First Image
- Command:
docker build -t my-app:v1 . - Breakdown:
build: Tells Docker to create an image.-t my-app:v1: Names itmy-appwith versionv1. Always use version numbers!.(Dot): Crucial! It tells Docker, “Look for theDockerfilein the current folder.”
- Tip: If your file is named
Dockerfile.dev, use-f Dockerfile.dev.
Downloading & Uploading (The Supply Chain)
- Pulling (Downloading):
docker pull python:3.9-slim(Always preferslimoralpineversions. They are small and secure). - Pushing (Uploading):
- First, you must log in:
docker login - Tag it for your account:
docker tag my-app:v1 amit/my-app:v1 - Push it:
docker push amit/my-app:v1
- First, you must log in:
Inspecting What’s Inside
- Command:
docker history my-app:v1 - Why use it? If your image is huge (e.g., 2GB), run this command. It shows which line in your Dockerfile added the most size. You might find you accidentally copied a 1GB video file into your code!
–
Layer Caching: The Speed Secret
Docker caches layers. If a layer hasn’t changed, Docker skips building it.
- Architect Strategy: Order your Dockerfile instructions from “Least Changed” to “Most Changed”.
- Bad Order: Copy Code -> Install Dependencies (Slow, because code changes often).
- Good Order: Install Dependencies -> Copy Code (Fast, because dependencies rarely change).
Multi-Architecture Builds docker buildx
In 2026, many servers use ARM processors (like AWS Graviton or Apple M3/M4).
- Command:
docker buildx build --platform linux/amd64,linux/arm64 -t my-app:v1 --push . - Result: This creates a single image that works on both Intel and Apple/ARM chips.
Reducing Attack Surface (Distroless)
Stop using full OS images like ubuntu. Use Google’s “Distroless” images for production. They contain only your app and its dependencies no shell, no package manager.
FROM gcr.io/distroless/nodejs:18- Benefit: Hackers cannot run commands because there is no shell!
The Dangling Images (<none>):
- When you rebuild an image with the same name, the old one loses its name and becomes
<none>. These are “dangling” images. - Fix: Run
docker image pruneto delete them and free up space.
The .dockerignore File:
- Just like
.gitignore. Create this file and addnode_modules,.git,.env, andpasswords.txt. - Benefit: Prevents secrets from being baked into the image and keeps the build fast.
–
Key Characteristics
- Registry: The central storage (Docker Hub, AWS ECR, Azure ACR).
- Base Image: The starting point (e.g.,
FROM python:3.9).
Use Case
- Golden Images: Security teams build a secure base image (hardened Linux), and all developers must use
FROM secure-company-base:v1.
Benefits
- Version Control: You can easily roll back. If
v2breaks production, just deployv1again in seconds.
–
Technical Challenges
- Build Context Size: When you run
docker build ., Docker sends everything in the folder to the daemon. If you have a 5GB dataset in that folder, the build will hang. (Solution: Use.dockerignore).
Common Issues & Solutions
| Issue | Problem | Solution |
| “Manifest not found” | You tried to pull an image that doesn’t exist or you made a typo. | Check Docker Hub. Did you misspell the tag? (e.g., nignx instead of nginx) |
| “Denied: requested access to the resource is denied” | You are not logged in or don’t have permission. | Run docker login. Check if you are pushing to your username (e.g., amit/app), not just app. |
| “No space left on device” | Too many old images. | docker system prune -a (Be careful, this deletes all stopped stuff!). |
- Docker Build: https://docs.docker.com/build/
- Dockerfile Reference: https://docs.docker.com/engine/reference/builder/
Lab Docker Image Management
Quiz Docker Image Management
Storage & Networking
Containers are ephemeral (data disappears when they stop) and isolated. These commands bridge gaps.
Volumes (Persisting Data)
Key Characteristics to Remember
- Life Cycle: Volumes live outside the container. They don’t die when the container dies.
- Sharing: Two containers can read the same volume at the same time (like two people reading the same book).
- Location: Named volumes are hidden deep in Docker’s internal folders (
/var/lib/docker/volumes). Bind mounts are visible folders on your Desktop.
| Command | Action | Explanation (Simple English) |
docker volume create <name> | Create | “Make a new empty storage box.” |
docker volume ls | List | “Show me all storage boxes on this machine.” |
docker volume inspect <name> | Details | “Tell me exactly where this box is on my hard drive.” |
docker run -v <vol>:<path> | Attach | “Connect this storage box to a specific folder inside the container.” |
docker volume rm <name> | Delete | “Destroy this storage box and everything inside it forever.” |
docker volume prune | Clean | “Delete all storage boxes that are not currently being used.” |
The Two Main Types of Storage
- Named Volumes (Production Standard):
- Command:
docker run -v my-db-data:/var/lib/mysql ... - Details: Docker manages these. They are stored in a hidden area (usually
/var/lib/docker/volumes/). You don’t need to worry about the path. - Use for: Databases (Postgres, MySQL, MongoDB), backups, and persistent application data.
- Command:
- Bind Mounts (Developer Standard):
- Command:
docker run -v /home/user/project:/app ... - Details: You link a specific folder on your Host (laptop) to the Container.
- Use for: Live Code Reloading. If you change a code file on your laptop, the container sees it immediately without rebuilding the image.
- Command:
How to Inspect Data
- If you want to know where your data actually lives on your Linux machine, run:
docker volume inspect my-db-data - Look for
"Mountpoint": "/var/lib/docker/volumes/my-db-data/_data". That is the real folder on your hard drive!
Volume Backups (The “Tarball” Technique)
You cannot easily copy a Docker volume file-by-file while the database is running. The architect’s way to backup is using a temporary container.
- The Logic:
- Spin up a temporary Alpine container.
- Mount the Volume you want to save (e.g.,
db-data). - Mount a local folder to store the backup.
- Zip (tar) the contents.
- The Command:Bash
docker run --rm \ -v db-data:/volume-data \ -v $(pwd):/backup \ alpine tar cvf /backup/backup.tar /volume-data
Read-Only Volumes (Security)
Sometimes you want a container to access data (like configuration files) but not change them.
- Command: Add
:roat the end.docker run -v my-config:/etc/app/config:ro my-app - Benefit: Even if a hacker compromises the app, they cannot delete or modify your configuration files.
External Storage Drivers (Cloud Integration)
In Enterprise environments (Kubernetes/AWS), you don’t store data on the node’s disk (because nodes die). You use plugins.
- RexRay / AWS EBS: You can create a Docker volume that actually maps to an Amazon EBS Drive.
docker volume create --driver rexray/ebs --name production-data - This ensures that even if the entire server melts down, your data is safe in the AWS cloud.
–
Lab Docker Volume Cli
Quiz Docker Volume Cli
Networks (Talking to other containers)
| Command | Action | Explanation (Simple English) |
docker network create <name> | Build Road | “Create a private road for specific containers.” |
docker network ls | Map | “Show me all the networks available.” |
docker run --network <name> | Join | “Start this container attached to that specific road.” |
docker network connect <net> <id> | Link | “Connect an already running container to a network.” |
docker network inspect <name> | Audit | “Show me every container currently on this network and their IPs.” |
docker network prune | Clean | “Remove all unused networks to clear clutter.” |
Common Issues & Solutions
| Issue | Problem | Solution |
| “Name does not resolve” | You are using the default bridge network. | Create a custom network (docker network create foo) and use that. Default bridge has no DNS! |
| “Connection Refused” | The target container isn’t listening on that port. | Check docker ps. Is the port exposed? Check docker logs for crashes. |
| “Destination Host Unreachable” | Containers are on different networks. | Use docker network connect to attach them to the same network. |
Lab Docker Network Cli
Quiz Docker Network Cli
Cleaning Up
Docker objects can eat up disk space rapidly.
| Command | Action | Explanation (Simple English) |
docker system prune | Nuke Junk | “Delete all stopped containers, unused networks, and dangling images.” |
docker system prune -a | Nuke ALL | “Delete EVERYTHING not currently running (even valid images like nginx).” |
docker rm <id> | Remove Cup | “Throw away this specific old container.” |
docker rmi <image> | Remove Book | “Delete this specific image from my library.” |
docker image prune | Clean Ghosts | “Delete only the dangling <none> images.” |
docker volume prune | Clean Data | “Delete all storage volumes that are not attached to any container.” |
The “Nuclear” Option: System Prune
- Command:
docker system prune - What it does: It is safe-ish. It removes:
- Stopped containers (dead cups).
- Networks not used by any container.
- Dangling images (old layers).
- Build cache (temporary files).
- The Dangerous Flag (
-a):docker system prune -a- Warning: This deletes all images not currently used by a running container. If you have
postgres:14downloaded but stopped the database for 5 minutes, this command deletes the image. You will have to download 400MB again next time.
- Warning: This deletes all images not currently used by a running container. If you have
Surgical Removal: Targeted Cleanup
- Remove one container:
docker rm my-old-app- Error: “You cannot remove a running container.”
- Fix:
docker rm -f my-old-app(Force kill and delete).
- Remove one image:
docker rmi nginx:latest- Error: “image is being used by running container…”
- Fix: You must stop and remove the container first, then remove the image.
Automated Cleanup: Cron Jobs
Servers fill up at 3 AM when you are sleeping. Architects automate cleanup.
- Strategy: Run a nightly script.
0 3 * * * docker system prune -f --filter "until=24h"- Explanation: “Every day at 3 AM, delete junk that has been created more than 24 hours ago.”
- Why filter? So you don’t accidentally delete a container that just crashed 1 minute ago and needs debugging.
Identifying Space Hogs
Before deleting, know what is eating space.
- Command:
docker system df - Output:Plaintext
TYPE TOTAL ACTIVE SIZE RECLAIMABLE Images 5 1 2.4GB 1.8GB (75%) Containers 2 1 100MB 50MB (50%) Local Volumes 1 0 500MB 500MB (100%)- Analysis: Here, Volumes and Images are wasting the most space.
The “Dangling Volume” Trap
When you run docker rm -f my-db, the container is gone, but the Volume remains (to save data).
- Problem: If you do this 100 times (creating and deleting test databases), you might have 100GB of orphaned volumes.
- Solution:
docker volume prune - Critical Warning: NEVER run this on production without checking backups. If you accidentally deleted the database container, your data is safe in the volume—until you run this command. Then it is gone forever.