Docker
This Docker cheatsheet
Definition of Docker
Docker is an open-source platform used to automate the deployment, scaling, and management of applications using containerization. It allows you to package an application with all its dependencies into a container, which can then be run on any system that has Docker installed — ensuring consistency across multiple environments (development, testing, production, etc.).
Components of Docker
-
Docker Engine
The core part of Docker that runs and manages containers.
- Docker Daemon (dockerd): Runs in the background and manages Docker containers, images, networks, and volumes.
- Docker CLI (docker): Command-line tool to interact with Docker Daemon.
- REST API: Interface to communicate programmatically with Docker Engine.
-
Docker Images
Read-only templates used to create containers. Images include the application code, runtime, libraries, and dependencies.
-
Docker Containers
Lightweight, standalone, and executable units of software that run from Docker images. Each container is isolated but shares the OS kernel.
-
Dockerfile
A text file containing instructions for building a Docker image. It defines the environment for the application.
-
Docker Hub
A cloud-based registry service for sharing Docker images. You can pull public images or push your own.
-
Docker Compose
A tool to define and manage multi-container applications using a YAML file (docker-compose.yml).
-
Docker Volumes
Used to persist data outside of containers, enabling data to remain even after a container is removed.
-
Docker Networks
Enables communication between containers and with the outside world.
Docker vs VirtualBox (or any Virtual Machine)
| Feature | Docker (Container) | VirtualBox (VM - Virtual Machine) |
|---|---|---|
| Architecture | Containers share the host OS kernel | VMs run full OS on top of a hypervisor |
| Performance | Lightweight, faster start-up and execution | Heavier, slower boot and higher resource consumption |
| Resource Usage | Low (shares host resources) | High (each VM has its own OS) |
| Isolation | Process-level isolation | Full OS-level isolation |
| Startup Time | Seconds | Minutes |
| Image Size | Small (\~MBs) | Large (\~GBs) |
| Portability | Highly portable across environments | Less portable due to OS dependencies |
| Use Case | Microservices, CI/CD, testing environments | Full OS testing, running apps with GUI |
| Examples | Nginx container, Python app container | Windows 10 VM, Ubuntu Desktop VM |
DOCKER IMAGES — Explanation & Commands
A Docker image is a read-only template that contains:
- Source code
- Runtime environment
- Libraries and dependencies
- Configuration files
You use Docker images to create containers.
Docker Image Commands & Examples
1. List All Local Docker Images
Command:
docker images
Output Example:
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest d1a364dc548d 2 weeks ago 133MB
myapp v1.0 3ac8b1f4c3c8 5 days ago 105MB
Lists all images that are stored locally on your machine.
2. Delete a Specific Image
Command:
docker rmi <image_name_or_ID>
Example:
docker rmi myapp:v1.0
This deletes the image. You must stop and remove any container using this image before removing it.
3. Remove Unused (Dangling) Images
Command:
docker image prune
Purpose: Deletes images not associated with any container (dangling images).
Example Prompt:
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N]
To skip confirmation:
docker image prune -f
4. Build an Image from a Dockerfile
Basic Build
Command:
docker build -t <image_name>:<version> .
Example:
docker build -t myapp:1.0 .
- -t = Tag the image
- . = Build context (current directory)
This reads the Dockerfile in the current directory and builds the image.
Build Without Using Cache
Command:
docker build -t <image_name>:<version> . --no-cache
Example:
docker build -t myapp:2.0 . --no-cache
💡 Useful when you want to force rebuild all layers (ignore cache).
More Useful Image Commands
5. List Only Image IDs
docker images -q
Output:
d1a364dc548d
3ac8b1f4c3c8
Use this for scripting or mass-deletion.
6. Remove All Unused Images, Containers, Networks
docker system prune
⚠️ This cleans up:
- Dangling images
- Stopped containers
- Unused networks
To confirm automatically:
docker system prune -f
7. Remove All Images
docker rmi $(docker images -q)
Be careful! This deletes all images.
8. Save Image to a .tar File
docker save -o myapp.tar myapp:1.0
Useful for sharing images offline.
9. Load Image from a .tar File
docker load -i myapp.tar
Example Dockerfile
# Base image FROM python:3.11-slim # Set working directory WORKDIR /app # Copy files COPY . . # Install dependencies RUN pip install -r requirements.txt # Run app CMD ["python", "app.py"]
Build the image:
docker build -t my-python-app:latest .
DOCKER CONTAINERS — Explanation & Commands
A Docker container is a running instance of a Docker image. It is:
- Lightweight
- Isolated
- Portable
- Fast to start/stop
Containers include everything needed to run an application: code, system tools, libraries, and settings.
Container Commands & Examples
1. List All Containers (Running + Stopped)
docker ps -a
Shows all containers including stopped ones.
Example Output:
CONTAINER ID IMAGE STATUS NAMES
db1234567890 nginx Exited (0) 2 hours ago web-nginx
ed2234aaef00 ubuntu Up 5 minutes my-ubuntu
2. List Only Running Containers
docker ps
Shows only currently running containers.
3. Create & Run a New Container
docker run <image_name>
Example:
docker run ubuntu
It will:
- Download the image if not found locally
- Start an interactive Ubuntu shell
- Exit immediately if no interactive session is open
4. Run Container in Background (Detached Mode)
docker run -d <image_name>
Example:
docker run -d nginx
Runs the container in the background — doesn't attach terminal to it.
5. Run Container With Custom Name
docker run --name <container_name> <image_name>
Example:
docker run --name myweb nginx
Makes it easier to refer to containers later by name.
6. Port Binding (Host ↔️ Container)
docker run -p <host_port>:<container_port> <image_name>
Example:
docker run -p 8080:80 nginx
Maps:
- Host port 8080
- To container port 80 (Nginx default)
Now you can access the app at http://localhost:8080.
7. Set Environment Variables
docker run -e <VAR_NAME>=<VAR_VALUE> <image_name>
Example:
docker run -e ENV=production -e VERSION=1.2 myapp
Used to pass configuration into the container at runtime.
8. Start or Stop an Existing Container
docker start <container_name_or_id> docker stop <container_name_or_id>
Example:
docker start myweb docker stop myweb
Start or stop containers that were previously created/stopped.
9. Inspect a Container (View JSON Info)
docker inspect <container_name_or_id>
Example:
docker inspect myweb
Shows detailed JSON about:
- IP Address
- Volume mounts
- Network settings
- Environment variables
- Runtime configs
10. Delete a Container
docker rm <container_name_or_id>
Example:
docker rm myweb
⚠️ Cannot delete running container — stop it first.
BONUS: Extra Useful Container Commands
11. Run Container with Interactive Terminal
docker run -it ubuntu
- -i: interactive
- -t: terminal
Opens terminal inside container (bash).
12. Remove Container After It Stops
docker run --rm ubuntu
Automatically deletes the container after it exits.
13. Restart Policy (Auto-restart Container)
docker run --restart=always nginx
Automatically restarts the container if it crashes or system restarts.
14. Mount Local Volume to Container
docker run -v $(pwd):/app myapp
Mounts your current local directory into /app inside container.
Summary Table
| Task | Command Example |
|---|---|
| List all containers | docker ps -a |
| List running containers | docker ps |
| Create and run container | docker run ubuntu |
| Run in background (detached) | docker run -d nginx |
| Name container | docker run --name myweb nginx |
| Bind port | docker run -p 8080:80 nginx |
| Set environment variable | docker run -e VAR=value myapp |
| Start/stop container | docker start / stop myweb |
| Inspect container info | docker inspect myweb |
| Remove a container | docker rm myweb |
| Run with terminal | docker run -it ubuntu |
| Auto remove on exit | docker run --rm ubuntu |
| Auto restart policy | docker run --restart=always nginx |
DOCKER TROUBLESHOOTING — Commands & Examples
1. Fetch Logs of a Container
Command:
docker logs <container_name_or_id>
Example:
docker logs myapp
Output:
Displays the STDOUT and STDERR output of the container.
💡 Use this to:
- Debug application output
- See errors from your running service (e.g., Node.js, Python, Nginx)
🔹 Extra Options for docker logs:
| Option | Description |
|---|---|
| --follow or -f | Follow live logs like tail -f |
| --tail <n> | Show only last n lines |
💡 Example:
docker logs -f --tail 100 myapp
Shows the last 100 lines and follows the log in real-time.
2. Open a Shell Inside a Running Container
This lets you "SSH-like" into a container to:
- Inspect files
- Manually run commands
- Debug configuration
Command 1: (Most Common for Ubuntu-based)
docker exec -it <container_name_or_id> /bin/bash
Example:
docker exec -it myapp /bin/bash
Command 2: (Use /bin/sh if bash is not available, like in Alpine)
docker exec -it <container_name_or_id> sh
Example:
docker exec -it myapp sh
How to Know Which Shell to Use?
You can check if bash is installed by trying:
docker exec -it myapp which bash
If it returns nothing, try:
docker exec -it myapp which sh
BONUS TROUBLESHOOTING COMMANDS (Very Useful)
3. View Resource Usage of Containers
docker stats
Shows live CPU, memory, network, I/O usage of running containers.
4. Check Container Events (Timeline of Actions)
docker events
Tracks Docker events in real time (start, stop, create, destroy).
5. Copy Files from/to Container
- From container → Host:
docker cp <container_name>:/path/in/container /path/on/host
- To container ← Host:
docker cp /path/on/host <container_name>:/path/in/container
Example:
docker cp myapp:/var/log/app.log ./app.log
6. Run One-off Command Inside Container
docker exec <container_name> ls -l /app
Run arbitrary commands like ls, cat, curl, ping, etc.
7. Check Container Exit Code (After Crash)
docker inspect <container_name> --format='{{.State.ExitCode}}'
Exit code 0 = success, non-zero = failure.
8. Attach to a Running Container's STDOUT
docker attach <container_name>
⚠️ Use only if you're not using -d (detached mode), or it might block.
9. Restart a Crashed Container
docker restart <container_name>
Restarts the container (stop → start).
10. Remove Stuck or Dead Container Forcefully
docker rm -f <container_name_or_id>
Useful if the container refuses to stop normally.
Summary Table
| Task | Command Example |
|---|---|
| View container logs | docker logs myapp |
| Follow live logs | docker logs -f myapp |
| Open bash shell | docker exec -it myapp /bin/bash |
| Open sh shell | docker exec -it myapp sh |
| View resource usage | docker stats |
| Copy file from container | docker cp myapp:/app/file.txt ./file.txt |
| Copy file to container | docker cp ./file.txt myapp:/app/file.txt |
| Check exit code after crash | docker inspect --format='{{.State.ExitCode}}' myapp |
| Restart container | docker restart myapp |
| Force remove container | docker rm -f myapp |
DOCKER HUB — Explained with Commands & Examples
What is Docker Hub?
Docker Hub is Docker's cloud-based registry where:
- You can find public Docker images.
- You can upload (push) your own images.
- You can host private repositories (free & paid plans available).
DOCKER HUB COMMANDS & USAGE
1. Pull an Image from Docker Hub
Command:
docker pull <image_name>
Example:
docker pull ubuntu
This pulls the latest version of the Ubuntu image from Docker Hub.
You can also specify a tag:
docker pull ubuntu:20.04
2. Search for an Image on Docker Hub
Command:
docker search <image_name>
Example:
docker search nginx
Output Sample:
NAME DESCRIPTION STARS OFFICIAL
nginx Official build of nginx 17000 [OK]
bitnami/nginx Bitnami nginx image 500
Useful to find official or community-maintained images.
3. Login to Docker Hub
Command:
docker login
This prompts:
Username: your_username
Password: ******
You can also use:
docker login -u <username>
Stores credentials in ~/.docker/config.json (Linux/macOS) or Windows equivalent.
4. Logout from Docker Hub
Command:
docker logout
This removes stored credentials and logs you out from the Docker Hub session.
5. Tag a Local Image for Docker Hub
Before pushing, you must tag your image with the format:
<your_dockerhub_username>/<image_name>:<tag>
Example:
docker tag myapp:latest myusername/myapp:1.0
6. Push Image to Docker Hub
Command:
docker push <username>/<image_name>
Example:
docker push myusername/myapp:1.0
Make sure:
- You are logged in (docker login)
- You have tagged the image correctly
- You have permission to push (your own repo or organization)
7. List Your DockerHub Repositories (via web)
No CLI command for this — go to:
https://hub.docker.com/repositories
Real World Workflow (Step-by-Step)
👇 Example: Build → Tag → Push to DockerHub
# Step 1: Build your local image docker build -t myapp . # Step 2: Tag it for DockerHub docker tag myapp myusername/myapp:1.0 # Step 3: Login to DockerHub docker login # Step 4: Push it docker push myusername/myapp:1.0
Bonus: Tips & Notes
- Use :latest tag to represent the most current version of your image.
- If you’re using CI/CD pipelines (GitHub Actions, etc.), use access tokens instead of password for docker login.
- You can create private repos on Docker Hub (limited for free users).
- You can also push images to GitHub Container Registry (ghcr.io) or Google Artifact Registry, etc.
Summary Table
| Task | Command Example |
|---|---|
| Pull image | docker pull ubuntu |
| Search image | docker search nginx |
| Login | docker login or docker login -u myusername |
| Logout | docker logout |
| Tag image | docker tag myapp myusername/myapp:1.0 |
| Push image | docker push myusername/myapp:1.0 |
DOCKER VOLUMES — Explained with Commands & Examples
What is a Docker Volume?
A volume in Docker is a mechanism for persisting data generated and used by containers. Volumes:
- Are stored outside the container's filesystem (inside /var/lib/docker/volumes)
- Persist even after container is removed
- Can be named or anonymous
- Are the preferred way to persist data in Docker
VOLUME COMMANDS & EXAMPLES
1. List All Volumes
Command:
docker volume ls
Output:
DRIVER VOLUME NAME
local mydata
local db_backup
2. Create a Named Volume
Command:
docker volume create <volume_name>
Example:
docker volume create mydata
This creates a persistent named volume called mydata.
3. Delete a Named Volume
Command:
docker volume rm <volume_name>
Example:
docker volume rm mydata
⚠️ You can’t remove a volume if it's in use by any container.
4. Mount Named Volume with Running Container
Method 1: Using --volume or -v
docker run -v <volume_name>:<container_path> <image>
Example:
docker run -v mydata:/app/data ubuntu
✔ Mounts named volume mydata to /app/data inside the container.
Method 2: Using --mount
docker run --mount type=volume,src=<volume_name>,dst=<container_path> <image>
Example:
docker run --mount type=volume,src=mydata,dst=/app/data ubuntu
--mount is more explicit and recommended for readability.
5. Mount Anonymous Volume
Command:
docker run -v <container_path> <image>
Example:
docker run -v /data ubuntu
Docker creates an anonymous volume and mounts it at /data. Good for temporary storage.
6. Create a Bind Mount (Host Folder → Container)
Bind mount maps host path to container path.
Method 1: Using --volume
docker run -v /host/path:/container/path <image>
Example:
docker run -v $(pwd):/app ubuntu
Maps the current directory on your host to /app inside the container.
Method 2: Using --mount
docker run --mount type=bind,src=/host/path,dst=/container/path <image>
Example:
docker run --mount type=bind,src="$(pwd)",dst=/app ubuntu
Bind mounts are useful for:
- Sharing config files
- Real-time code development
- Logs, backups, etc.
7. Remove All Unused Local Volumes (Garbage Collection)
Command:
docker volume prune
Prompts:
WARNING! This will remove all local volumes not used by at least one container.
Are you sure you want to continue? [y/N]
This is helpful to clean up unused anonymous volumes.
BONUS: Check Details of a Volume
Command:
docker volume inspect <volume_name>
Example:
docker volume inspect mydata
Shows:
- Mount point on host
- Driver (usually local)
- Labels, options, etc.
Summary Table
| Task | Command Example |
|---|---|
| List volumes | docker volume ls |
| Create named volume | docker volume create mydata |
| Delete named volume | docker volume rm mydata |
| Mount named volume | docker run -v mydata:/app ubuntu |
| Mount anonymous volume | docker run -v /app ubuntu |
| Mount with --mount | docker run --mount type=volume,src=mydata,dst=/app ubuntu |
| Create bind mount (host ↔️ container) | docker run -v $(pwd):/app ubuntu |
| Bind mount using --mount | docker run --mount type=bind,src="$(pwd)",dst=/app ubuntu |
| Remove all unused volumes | docker volume prune |
| Inspect a volume | docker volume inspect mydata |
When to Use Which?
| Type | Use Case |
|---|---|
| Named Volume | Best for persistent data (e.g. database, uploads) |
| Anonymous Volume | Temporary, auto-managed by Docker |
| Bind Mount | Real-time file access between host and container (e.g. local dev) |
DOCKER NETWORK — Explanation with Commands & Examples
What is Docker Network?
Docker Networking allows containers to communicate with:
- Other containers
- The host machine
- The internet
Docker uses network drivers to implement different types of networking.
Types of Docker Networks
| Network Type | Description |
|---|---|
| bridge | Default for standalone containers on a single host |
| host | Container shares the host’s network directly |
| none | No networking; fully isolated container |
| overlay | For multi-host communication (used with Docker Swarm) |
| macvlan | Assigns a MAC address, container appears as a physical device on the network |
For most use cases (especially development), bridge and custom bridge networks are enough.
NETWORK COMMANDS & EXAMPLES
1. List All Docker Networks
Command:
docker network ls
Output:
NETWORK ID NAME DRIVER SCOPE
9f1c5a3f62fd bridge bridge local
e2d45b3acb1e host host local
85c6f733fe20 none null local
2. Create a Custom Bridge Network
Command:
docker network create <network_name>
Example:
docker network create mynetwork
This creates a custom bridge network mynetwork.
Benefits of custom networks:
- Containers can talk to each other using container names as DNS.
- Better isolation and security.
3. Remove a Docker Network
Command:
docker network rm <network_name>
Example:
docker network rm mynetwork
⚠️ You cannot delete a network that’s currently in use by a container.
4. Remove All Unused Networks
Command:
docker network prune
Prompts:
WARNING! This will remove all custom networks not used by at least one container.
Are you sure you want to continue? [y/N]
Cleans up dangling networks safely.
BONUS: ADVANCED NETWORK USAGE
5. Run Containers in Same Network
Create a network:
docker network create app-net
Run containers in that network:
docker run -d --name redis --network app-net redis docker run -d --name backend --network app-net mybackendapp
Now backend can access Redis using its name:
redis:6379
DNS-based discovery between containers — no need for IP addresses!
6. Connect a Container to an Existing Network
Command:
docker network connect <network_name> <container_name>
Example:
docker network connect app-net mycontainer
Adds the container mycontainer to app-net.
7. Disconnect a Container from a Network
docker network disconnect <network_name> <container_name>
8. Inspect a Docker Network
Command:
docker network inspect <network_name>
Example:
docker network inspect app-net
Shows:
- Subnet info
- Connected containers
- Driver type
- IP ranges
Summary Table
| Task | Command Example |
|---|---|
| List all networks | docker network ls |
| Create a new network | docker network create mynet |
| Remove a network | docker network rm mynet |
| Remove unused networks | docker network prune |
| Inspect network details | docker network inspect mynet |
| Run container in custom network | docker run --network=mynet myapp |
| Connect container to network | docker network connect mynet container1 |
| Disconnect container from net | docker network disconnect mynet container1 |
When to Use Custom Networks?
- Microservices talking to each other (e.g. backend ↔ database)
- When you want network-level isolation
- For Docker Compose multi-container applications (each Compose file uses its own network by default)
Docker — All-in-One Reference
BASIC COMMANDS
| Task | Command / Example | Explanation |
|---|---|---|
| Pull an image | docker pull <image> | Downloads an image from DockerHub |
| Pull specific version | docker pull <image>:<version> | Example: docker pull ubuntu:22.04 |
| List local images | docker images | Shows all downloaded images |
| Run a container | docker run <image> | Creates and runs a container |
| Run interactively | docker run -it <image> | Opens terminal inside container |
| Run in background | docker run -d <image> | Detached mode |
| Run with custom name | docker run --name <name> -d <image> | Name your container |
| Expose container port | docker run -p8080:3306 <image> | Map host\:container port |
| List running containers | docker ps | Shows active containers |
| List all containers | docker ps -a | Shows active + stopped containers |
| Stop container | docker stop <container> | Gracefully stops a container |
| Start container | docker start <container> | Starts a stopped container |
| Remove container | docker rm <container> | Deletes container |
| Remove image | docker rmi <image> | Deletes image |
TROUBLESHOOTING
| Task | Command / Example | Explanation |
|---|---|---|
| View logs | docker logs <container> | Shows STDOUT/STDERR output |
| Enter container (bash) | docker exec -it <container> /bin/bash | Opens shell inside container (bash) |
| Enter container (sh) | docker exec -it <container> sh | For Alpine-based or minimal containers |
DOCKER NETWORKING
| Task | Command / Example | Explanation |
|---|---|---|
| List networks | docker network ls | Shows all Docker networks |
| Create network | docker network create <name> | Creates a custom network |
| Remove network | docker network rm <name> | Deletes unused network |
| Prune unused networks | docker network prune | Removes dangling networks |
MONGO + MONGO-EXPRESS EXAMPLE
Create custom network
docker network create mongo-network
Mongo container
docker run -d -p 27017:27017 --name mongo \ --network mongo-network \ -e MONGO_INITDB_ROOT_USERNAME=admin \ -e MONGO_INITDB_ROOT_PASSWORD=qwerty \ mongo
Mongo-Express container
docker run -d -p 8081:8081 --name mongo-express \ --network mongo-network \ -e ME_CONFIG_MONGODB_ADMINUSERNAME=admin \ -e ME_CONFIG_MONGODB_ADMINPASSWORD=qwerty \ -e ME_CONFIG_MONGODB_URL="mongodb://admin:qwerty@mongo:27017" \ mongo-express
DOCKER VOLUMES
| Task | Command / Example | Explanation |
|---|---|---|
| List volumes | docker volume ls | Lists all volumes |
| Create volume | docker volume create <name> | Creates named volume |
| Remove volume | docker volume rm <name> | Deletes named volume |
| Prune unused volumes | docker volume prune | Cleans up unused (anonymous) volumes |
Mount Types:
| Type | Example | Description |
|---|---|---|
| Named volume | docker run -v vol_name:/data ubuntu | Persistent, reusable across containers |
| Anonymous | docker run -v /data ubuntu | Docker manages the volume name |
| Bind mount | docker run -v /host/path:/container/path ubuntu | Link host folder to container path |
DOCKER COMPOSE
YAML File: docker-compose.yaml
version: "3.8" services: mongo: image: mongo ports: - "27017:27017" environment: MONGO_INITDB_ROOT_USERNAME: admin MONGO_INITDB_ROOT_PASSWORD: qwerty volumes: - /Users/kali/Desktop/data:/data/db
Commands
| Task | Command |
|---|---|
| Compose up (start) | docker compose -f docker-compose.yaml up -d |
| Compose down (stop) | docker compose -f docker-compose.yaml down |
DOCKERIZING AN APP
Example Dockerfile
FROM node ENV MONGO_DB_USERNAME=admin \ MONGO_DB_PWD=qwerty RUN mkdir -p /testapp COPY . /testapp CMD ["node", "/testapp/server.js"]
Build the image
docker build -t testapp:1.0 .
Push to DockerHub
docker push <username>/testapp:1.0
💡 Docker File Keywords Summary
| Keyword | Usage |
|---|---|
| FROM | Base image (e.g., node, python, etc.) |
| WORKDIR | Sets working directory inside container |
| COPY | Copies files from host into image |
| RUN | Executes commands during image build |
| CMD | Default command to run when container starts |
| EXPOSE | Documents which ports are exposed (informational) |
| ENV | Sets environment variables |