Skip to main content
< All Topics

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.

CommandPurpose (Simple English)Key Flags to Remember
docker runCreates & starts a new container.-d (Run in background/detached)
-p (Map ports: HostPort:ContainerPort)
--name (Give it a custom name)
docker psLists containers currently running.-a (Show all, including stopped/crashed)
-q (Show only IDs, useful for automation scripts)
docker stopGently stops a container.None usually, but accepts a timeout.
docker execEnters inside a running container.-it (Interactive TTY – Mandatory if you want to type commands like bash)
docker logsShows 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 exec is “inside looking around.”
  • Lifecycle: run creates it, stop halts it, but it still exists until you rm (remove) it.
  • Visibility: If you don’t see it with docker ps, check docker ps -a (it might be dead/stopped).
  • A common confusion is docker stop vs docker kill.
    • Stop: Sends a SIGTERM signal. 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. Use stop first; use kill only if it’s stuck.

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 press Ctrl+C, the container dies. Always use -d for 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), bash might not exist. In that case, use shdocker exec -it my-web-server sh Official 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-server
  • docker 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 stop and rm a container, the data inside is lost (unless you use Volumes).

Use Case

  • Debugging: docker logs is used instantly when an API call fails.
  • Maintenance: docker exec is used to check configuration files inside a running database without stopping it.

Benefits

  • Speed: These commands execute in milliseconds.
  • Consistency: docker run works the exact same way on Windows, Mac, and Linux.

Limitations

  • Shell Availability: docker exec fails if the container image doesn’t have a shell installed (common in “Distroless” security images).
  • Log Size: If docker logs is huge, running it without --tail can freeze your terminal.

Common Issues & Solutions

IssueProblemSolution
Container keeps exitingThe 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 a Dockerfile in the current directory (.). The -t flag 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 (requires docker login first).
  • 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 it my-app with version v1. Always use version numbers!
    • . (Dot): Crucial! It tells Docker, “Look for the Dockerfile in 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 prefer slim or alpine versions. They are small and secure).
  • Pushing (Uploading):
    1. First, you must log in: docker login
    2. Tag it for your account: docker tag my-app:v1 amit/my-app:v1
    3. Push it: docker push amit/my-app:v1

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 prune to delete them and free up space.

The .dockerignore File:

  • Just like .gitignore. Create this file and add node_modules, .git, .env, and passwords.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 v2 breaks production, just deploy v1 again 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

IssueProblemSolution
“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!).

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.
CommandActionExplanation (Simple English)
docker volume create <name>Create“Make a new empty storage box.”
docker volume lsList“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 pruneClean“Delete all storage boxes that are not currently being used.”

The Two Main Types of Storage

  1. 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.
  2. 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.

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:
    1. Spin up a temporary Alpine container.
    2. Mount the Volume you want to save (e.g., db-data).
    3. Mount a local folder to store the backup.
    4. Zip (tar) the contents.
  • The Command:Bashdocker 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 :ro at 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 Drivedocker 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)

CommandActionExplanation (Simple English)
docker network create <name>Build Road“Create a private road for specific containers.”
docker network lsMap“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 pruneClean“Remove all unused networks to clear clutter.”

Common Issues & Solutions

IssueProblemSolution
“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.

CommandActionExplanation (Simple English)
docker system pruneNuke Junk“Delete all stopped containers, unused networks, and dangling images.”
docker system prune -aNuke 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 pruneClean Ghosts“Delete only the dangling <none> images.”
docker volume pruneClean 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:
    1. Stopped containers (dead cups).
    2. Networks not used by any container.
    3. Dangling images (old layers).
    4. 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:14 downloaded but stopped the database for 5 minutes, this command deletes the image. You will have to download 400MB again next time.

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:PlaintextTYPE 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.

Lab Docker Cleaning Up Cli

Quiz Docker Cleaning Up Cli


Advanced / Debugging

  • docker stats: Displays a live stream of container resource usage (CPU, Memory, Network I/O), similar to top or Task Manager.
  • docker inspect <id>: Returns a huge JSON object with every low-level detail about a container or image (IP address, mounts, environment variables).
    • Tip: Use grep to find what you need, e.g., docker inspect my-db | grep IPAddress.

Contents
Scroll to Top