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

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

    Read-only templates used to create containers. Images include the application code, runtime, libraries, and dependencies.

  3. Docker Containers

    Lightweight, standalone, and executable units of software that run from Docker images. Each container is isolated but shares the OS kernel.

  4. Dockerfile

    A text file containing instructions for building a Docker image. It defines the environment for the application.

  5. Docker Hub

    A cloud-based registry service for sharing Docker images. You can pull public images or push your own.

  6. Docker Compose

    A tool to define and manage multi-container applications using a YAML file (docker-compose.yml).

  7. Docker Volumes

    Used to persist data outside of containers, enabling data to remain even after a container is removed.

  8. Docker Networks

    Enables communication between containers and with the outside world.

Docker vs VirtualBox (or any Virtual Machine)

FeatureDocker (Container)VirtualBox (VM - Virtual Machine)
ArchitectureContainers share the host OS kernelVMs run full OS on top of a hypervisor
PerformanceLightweight, faster start-up and executionHeavier, slower boot and higher resource consumption
Resource UsageLow (shares host resources)High (each VM has its own OS)
IsolationProcess-level isolationFull OS-level isolation
Startup TimeSecondsMinutes
Image SizeSmall (\~MBs)Large (\~GBs)
PortabilityHighly portable across environmentsLess portable due to OS dependencies
Use CaseMicroservices, CI/CD, testing environmentsFull OS testing, running apps with GUI
ExamplesNginx container, Python app containerWindows 10 VM, Ubuntu Desktop VM

DOCKER IMAGES — Explanation & Commands

A Docker image is a read-only template that contains:

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 .

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:

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:

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:

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:

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:

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

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

TaskCommand Example
List all containersdocker ps -a
List running containersdocker ps
Create and run containerdocker run ubuntu
Run in background (detached)docker run -d nginx
Name containerdocker run --name myweb nginx
Bind portdocker run -p 8080:80 nginx
Set environment variabledocker run -e VAR=value myapp
Start/stop containerdocker start / stop myweb
Inspect container infodocker inspect myweb
Remove a containerdocker rm myweb
Run with terminaldocker run -it ubuntu
Auto remove on exitdocker run --rm ubuntu
Auto restart policydocker 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:

🔹 Extra Options for docker logs:

OptionDescription
--follow or -fFollow 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:

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

docker cp <container_name>:/path/in/container /path/on/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

TaskCommand Example
View container logsdocker logs myapp
Follow live logsdocker logs -f myapp
Open bash shelldocker exec -it myapp /bin/bash
Open sh shelldocker exec -it myapp sh
View resource usagedocker stats
Copy file from containerdocker cp myapp:/app/file.txt ./file.txt
Copy file to containerdocker cp ./file.txt myapp:/app/file.txt
Check exit code after crashdocker inspect --format='{{.State.ExitCode}}' myapp
Restart containerdocker restart myapp
Force remove containerdocker rm -f myapp

DOCKER HUB — Explained with Commands & Examples

What is Docker Hub?

Docker Hub is Docker's cloud-based registry where:

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:

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

Summary Table

TaskCommand Example
Pull imagedocker pull ubuntu
Search imagedocker search nginx
Logindocker login or docker login -u myusername
Logoutdocker logout
Tag imagedocker tag myapp myusername/myapp:1.0
Push imagedocker 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:

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:

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:

Summary Table

TaskCommand Example
List volumesdocker volume ls
Create named volumedocker volume create mydata
Delete named volumedocker volume rm mydata
Mount named volumedocker run -v mydata:/app ubuntu
Mount anonymous volumedocker run -v /app ubuntu
Mount with --mountdocker run --mount type=volume,src=mydata,dst=/app ubuntu
Create bind mount (host ↔️ container)docker run -v $(pwd):/app ubuntu
Bind mount using --mountdocker run --mount type=bind,src="$(pwd)",dst=/app ubuntu
Remove all unused volumesdocker volume prune
Inspect a volumedocker volume inspect mydata

When to Use Which?

TypeUse Case
Named VolumeBest for persistent data (e.g. database, uploads)
Anonymous VolumeTemporary, auto-managed by Docker
Bind MountReal-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:

Docker uses network drivers to implement different types of networking.

Types of Docker Networks

Network TypeDescription
bridgeDefault for standalone containers on a single host
hostContainer shares the host’s network directly
noneNo networking; fully isolated container
overlayFor multi-host communication (used with Docker Swarm)
macvlanAssigns 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:

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:

Summary Table

TaskCommand Example
List all networksdocker network ls
Create a new networkdocker network create mynet
Remove a networkdocker network rm mynet
Remove unused networksdocker network prune
Inspect network detailsdocker network inspect mynet
Run container in custom networkdocker run --network=mynet myapp
Connect container to networkdocker network connect mynet container1
Disconnect container from netdocker network disconnect mynet container1

When to Use Custom Networks?

Docker — All-in-One Reference

BASIC COMMANDS

TaskCommand / ExampleExplanation
Pull an imagedocker pull <image>Downloads an image from DockerHub
Pull specific versiondocker pull <image>:<version>Example: docker pull ubuntu:22.04
List local imagesdocker imagesShows all downloaded images
Run a containerdocker run <image>Creates and runs a container
Run interactivelydocker run -it <image>Opens terminal inside container
Run in backgrounddocker run -d <image>Detached mode
Run with custom namedocker run --name <name> -d <image>Name your container
Expose container portdocker run -p8080:3306 <image>Map host\:container port
List running containersdocker psShows active containers
List all containersdocker ps -aShows active + stopped containers
Stop containerdocker stop <container>Gracefully stops a container
Start containerdocker start <container>Starts a stopped container
Remove containerdocker rm <container>Deletes container
Remove imagedocker rmi <image>Deletes image

TROUBLESHOOTING

TaskCommand / ExampleExplanation
View logsdocker logs <container>Shows STDOUT/STDERR output
Enter container (bash)docker exec -it <container> /bin/bashOpens shell inside container (bash)
Enter container (sh)docker exec -it <container> shFor Alpine-based or minimal containers

DOCKER NETWORKING

TaskCommand / ExampleExplanation
List networksdocker network lsShows all Docker networks
Create networkdocker network create <name>Creates a custom network
Remove networkdocker network rm <name>Deletes unused network
Prune unused networksdocker network pruneRemoves 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

TaskCommand / ExampleExplanation
List volumesdocker volume lsLists all volumes
Create volumedocker volume create <name>Creates named volume
Remove volumedocker volume rm <name>Deletes named volume
Prune unused volumesdocker volume pruneCleans up unused (anonymous) volumes

Mount Types:

TypeExampleDescription
Named volumedocker run -v vol_name:/data ubuntuPersistent, reusable across containers
Anonymousdocker run -v /data ubuntuDocker manages the volume name
Bind mountdocker run -v /host/path:/container/path ubuntuLink 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

TaskCommand
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

KeywordUsage
FROMBase image (e.g., node, python, etc.)
WORKDIRSets working directory inside container
COPYCopies files from host into image
RUNExecutes commands during image build
CMDDefault command to run when container starts
EXPOSEDocuments which ports are exposed (informational)
ENVSets environment variables