π Docker Explained Simply (With Real-Life Examples)
If youβve ever faced the dreaded βIt works on my machine but not on yoursβ problem β Docker is the hero you need.
It allows developers to package applications into isolated environments called containers, ensuring they run the same everywhere.
β
Think of it like this:
You built a school project website that runs fine on your laptop. But when you copy it to your friendβs system, it crashes because they have a different PHP version. With Docker, you can package your code, PHP, and dependencies into a single container. Now it works everywhere π.
βοΈ Docker Architecture
Docker has two main parts:
π₯οΈ 1. Docker Client
- The tool we use to interact with Docker.
-
Runs commands like:
-
docker run
β Start a container -
docker pull
β Download an image
-
Can even talk to a remote Docker Daemon over a network.
β‘ 2. Docker Daemon
- The engine of Docker running in the background.
- Responsible for building, running, and managing containers, images, networks, and volumes.
π Communication
-
Client β Daemon communicate via:
- REST API
- Unix socket
- Network interface
π Analogy: You (client) say βMake tea!β β and the kitchen (daemon) makes it.
π§© Docker Components
π¦ 1. Docker Images
- Read-only templates used to create containers.
- Built in layers, so if one layer changes, only that part rebuilds.
π Example:
- Base:
ubuntu
- Add Python β new layer
- Add Flask β another layer
docker pull ubuntu
π 2. Docker Containers
- A running instance of an image.
- You can start, stop, delete, or move them.
- Each has its own read-write layer and connects to storage + networks.
- Ephemeral by default (data gone when removed) β unless a volume is attached.
π Flow:
- Pull image β 2. Create container β 3. Add read-write layer β 4. Connect to virtual network β 5. Get unique container IP β 6. Interact via terminal.
docker container create --name shan ubuntu /bin/bash
π₯ 3. Docker Engine
- The core runtime that builds and runs containers locally.
βοΈ 4. Docker Hub
- Cloud-based repo where you store and share images.
π 5. Dockerfile
- A script with step-by-step instructions to build an image.
- Executed top to bottom by Docker Daemon.
π Workflow:
Dockerfile β docker build β Docker Image β docker run β Container
β
Example:
FROM ubuntu
RUN apt-get update && apt-get install -y nginx
CMD ["nginx", "-g", "daemon off;"]
π¦ Docker Registry
- A service that stores Docker images.
- Docker Hub is the most popular public registry.
π§ Common Docker Commands
πΉ Image Commands
-
docker image ls
β List images -
docker pull <image>
β Download image -
docker rmi <image>
β Remove image -
docker history <image>
β View layers
πΉ Container Commands
-
docker run <image>
β Run container -
docker ps -a
β List containers -
docker exec -it <id> /bin/bash
β Open terminal inside container -
docker logs <id>
β View logs
π Example: Run Nginx on port 80
docker run -d -p 80:80 nginx
π₯ Docker vs Virtual Machine
Feature | Docker (Container) | Virtual Machine (VM) |
---|---|---|
Startup Time | Seconds β‘ | Minutes π |
Resource Usage | Lightweight πͺΆ | Heavy π» |
OS Requirement | Shares Host OS | Needs Full OS |
Performance | Faster π | Slower π’ |
Isolation | Process-level | Hardware-level |
π Example:
- Want to run 10 microservices? Use containers.
- Want to run Windows on Linux? Use a VM.
π― Final Thoughts
Docker has become a must-have skill for developers and DevOps engineers.
Itβs lightweight, fast, and makes your apps portable across environments.
β¨ Next time you hear βbut it worked on my laptopβ¦β, just smile and say:
π βLetβs put it in Docker.β π³
ποΈ Docker Storage & Networking (with Real-World Examples)
Containers are temporary by nature β once theyβre removed, their data is gone β.
Thatβs where Docker Storage comes in to keep your data safe.
π Docker Storage β Volumes
A volume is storage that lives outside of containers, so your data survives even if the container is deleted.
πΉ Types of Storage
- Bind Mount β Maps a host path to a container path.
-
Docker Volume β Managed by Docker, stored under
/var/lib/docker/volumes
. - tmpfs β Stores data in RAM (super fast, but temporary).
πΉ Volume Commands
docker volume ls # List volumes
docker volume create ak # Create a volume
docker volume inspect ak # Inspect volume
π Example: Mount a volume inside a container
docker run -d -it --name ubuntu \
--mount source=ak,destination=/var/app/data ubuntu /bin/bash
πΉ Volume Drivers
-
local
β Store files on host machine -
NFS
β Remote storage -
type=tmpfs
β Store in RAM -
type=none
β Bind mount
π Example: Create tmpfs volume
docker volume create --driver local \
-o type=tmpfs -o device=tmpfs myvol
π Docker Networking
Containers need networking to talk to each other or the outside world.
πΉ Types of Networks
- None β No network assigned.
- Host β Shares host machineβs IP.
- Bridge (default) β Creates a private network with unique container IPs.
πΉ Network Commands
docker network ls # List networks
docker network create mynet # Create new network
docker network inspect mynet # Inspect network
docker network prune # Delete unused networks
π Example: Create a custom bridge network
docker network create --driver bridge \
--subnet 192.168.50.1/24 \
--ip-range 192.168.50.128/25 \
--gateway 192.168.50.1 mynet
π Assign manual IP to a container
docker run -d --network mynet --ip 192.168.50.50 httpd
π Dockerfile β The Recipe of Docker
A Dockerfile is like a recipe card π°.
Each line is an instruction, read top to bottom, that builds your image step by step.
π Fun fact: Dockerfile is case-sensitive β FROM
β
but from
β.
β Example analogy: Baking a cake π§
- Recipe: Take flour, add sugar, bake
- Dockerfile: FROM Ubuntu, RUN apt-get update, COPY code, CMD run app
π οΈ Dockerfile Instructions (with Examples)
π Essential Instructions
- FROM β Base image
FROM ubuntu:latest
- LABEL β Add metadata
LABEL version="1.0"
- ENV β Environment variable
ENV owner="shan"
- VOLUME β Persistent storage
VOLUME ["/data"]
- WORKDIR β Set working directory
WORKDIR /lak
- COPY β Copy files from host β image
COPY AStc /lak
- ADD β Like COPY, but can unzip/download
ADD dumptar /lak
- RUN β Run commands while building
RUN apt update && useradd -ms /bin/bash shan
- USER β Change user
USER shan
- EXPOSE β Open port
EXPOSE 8080
- CMD β Default command (only one allowed)
CMD ["ping", "8.8.8.8"]
- ENTRYPOINT β Make container behave like an executable
ENTRYPOINT ["ping"]
π Foreground vs Background in Containers
- Foreground process = Main task (must keep running).
- Background process = Helper tasks.
π If no foreground process exists, the container stops immediately.
β Example:
- Apache server running = foreground
- Logging system = background
π·οΈ Docker Tags
Tags = version labels for images.
docker tag <container_id> username/app:v1
π Like: Essay_v1.docx
, Essay_v2.docx
Fact: If no tag β Docker uses latest
.
π€ Building & Pushing Docker Images
πΉ Build Image
docker build -t username/app:1.0 .
πΉ Push to Docker Hub
docker push username/app:1.0
π Just like saving your project locally (build) and then uploading it to Google Drive (push).
β Quick Recap
- Volumes keep your data safe.
- Networking connects your containers.
- Dockerfile = Recipe card π
- Instructions like FROM, RUN, COPY, CMD, ENTRYPOINT are must-know.
- Containers need a foreground process to stay alive.
- Tags = versions, and pushing = sharing your app with the world π.
π³ Docker Swarm β Container Orchestration Made Simple
Running a single container is easy. Running hundreds across multiple servers? Thatβs chaosβ¦ unless you use orchestration.
π Enter Docker Swarm: Dockerβs native orchestration tool that makes managing containers across multiple hosts simple, scalable, and reliable.
β‘ 1. What is Docker Swarm?
- Definition: A clustering and orchestration tool built into Docker.
- Purpose: Ensures high availability, load balancing, and scaling.
- Why: Real-world apps need many containers across many servers β orchestration makes this manageable.
β Fun fact: Kubernetes is the industry leader, but Docker Swarm is simpler to set up and works out of the box with Docker.
π Analogy:
- One pizza shop = One Docker host π
- Many shops across the city = Swarm cluster ποΈ
- Manager decides which shop handles orders = Swarm Manager assigns containers to nodes.
π§© 2. Key Concepts in Docker Swarm
- Swarm Mode β Special mode that enables clustering.
- Swarm Manager β Brain of the cluster (handles scheduling, scaling, service mgmt).
-
Swarm Nodes β Machines in the cluster (Manager or Worker).
- Manager node = controls cluster
- Worker node = runs containers
π Only one leader manager exists at a time (others are backups).
π 3. Setting Up a Swarm
On Manager Node
docker swarm init --advertise-addr <IP>
On Worker Nodes
docker swarm join --token <token> <manager-ip>:2377
Verify Nodes
docker node ls
π οΈ 4. Services in Docker Swarm
A Service is Swarmβs way of managing containers. Instead of βjust run this container,β you say:
π βRun 3 copies of this app across the cluster.β Swarm makes it happen β
.
docker service create --replicas 2 -p 80:80 --name myweb nginx
- Runs 2 replicas of Nginx web server on port 80.
Check services:
docker service ls
docker service ps myweb
π¦ 5. Service Modes
- Replicated Mode β You choose how many replicas.
- Global Mode β Runs one container on every node.
π Example:
- Replicated β Run 5 replicas of Nginx across 3 nodes.
- Global β Run monitoring agents (like Prometheus) everywhere.
π 6. Scaling Services
Scale up/down instantly:
docker service scale myweb=5 # scale up
docker service scale myweb=2 # scale down
Swarm will redistribute replicas automatically.
π 7. Service Updates & Rollbacks
Update app version:
docker service update --image nginx:1.25 myweb
Rollback if things break:
docker service rollback myweb
π Just like deploying v2.5, and rolling back to v2.1 if users complain π¨.
π§βπ» 8. Node Management
- Promote worker β manager
docker node promote worker2
- Demote manager β worker
docker node demote manager2
- Drain node (move workloads away)
docker node update --availability drain worker2
- Pause node (keep current workloads, stop new ones)
docker node update --availability pause worker2
π Example:
- Drain = closing a shop, orders shift to others.
- Pause = shop still runs, but no new orders.
π 9. Networks in Swarm
When Swarm starts, it creates an ingress overlay network by default.
This lets containers across different nodes talk securely.
π Example:
Two replicas of a web app running on Node1 & Node2 β both accessible under the same service name.
π 10. Useful Commands Summary
Command | Purpose |
---|---|
docker swarm init |
Initialize swarm |
docker swarm leave |
Leave swarm |
docker node ls |
List nodes |
docker node promote <node> |
Promote worker β manager |
docker node demote <node> |
Demote manager β worker |
docker node rm <node> |
Remove node |
docker node update --availability drain <node> |
Drain containers from node |
docker service create ... |
Create new service |
docker service ls |
List services |
docker service ps <service> |
Show service tasks |
docker service scale <service>=<n> |
Scale replicas |
docker service update --image <image> |
Update service image |
docker service rollback <service> |
Rollback service |
β Final Recap
- Docker Swarm = Cluster & orchestration tool.
- Manager nodes control, workers run containers.
- Services = higher-level objects (can have replicas).
- Modes: Replicated vs Global.
-
Scaling = instant with
docker service scale
. - Updates & Rollbacks = safe deployments.
- Node Management = promote, demote, drain, pause.
- Networking = ingress overlay ensures secure communication.
π With Docker Swarm, you can manage hundreds of containers like a pro β no manual chaos, just smooth orchestration π³β¨.
π Docker β CPU, Memory & Security
1. Why Set CPU & Memory Limits?
-
Definition:
Docker allows you to reserve and limit CPU & memory per container.- Reservation = soft guarantee (minimum resources).
- Limit = hard cap (maximum usage).
-
Why it matters:
- Prevents one container from hogging all host resources.
- Ensures stable performance in multi-container environments.
- Protects against crashes if an app goes out of control.
β Fact: Without limits, a single buggy container can bring down the whole server.
2. Units & Key Facts
-
CPU units in Docker:
-
--cpus="0.5"
β 50% of 1 CPU core. -
--cpu-shares
β relative weight (default = 1024). -
--cpu-period
&--cpu-quota
β fine-grained control.
-
-
CPU units in Kubernetes:
-
100m
= 0.1 CPU (10% of 1 core). -
1000m
= 1 CPU.
-
-
Memory units:
-
256m
= 256 MB -
1g
= 1 GB
-
β Rule of thumb: Donβt allocate 100% of host resources. Keep ~20β30% for the OS.
3. Examples of CPU & Memory Settings
Memory Reservation + Limit
docker run -d --name web1 \
--memory-reservation=256m --memory=512m httpd
- 256 MB reserved (soft).
- 512 MB hard cap β container killed if exceeded.
CPU Limit (Simple)
docker run -d --name web2 --cpus="0.5" httpd
π Max 50% of one CPU core.
CPU Shares (Relative Priority)
docker run -d --cpu-shares=512 --name web3 httpd
π Gets 50% weight compared to default 1024.
CPU Quota/Period (Advanced)
docker run -d --cpu-period=100000 --cpu-quota=50000 httpd
π 50% of CPU (50,000 Γ· 100,000).
Memory + Swap Control
docker run -d --memory=512m --memory-swap=512m httpd
π No swap allowed (only 512 MB RAM).
4. Practical Planning (Worked Example)
Host: 4 CPUs, 8 GB RAM.
- Reserve ~30% for OS β usable = 2.8 CPUs, 5.6 GB RAM.
-
For 4 containers:
-
--cpus=0.5
each β 2 CPUs total. -
--memory=1g
each β 4 GB total.
-
Leaves headroom for spikes.
β
Use docker stats
to monitor and adjust.
5. Observability Commands
-
docker stats
β Live CPU, memory, I/O per container. -
docker inspect <container>
β Shows configured limits. - Host tools:
top
,htop
,free -m
.
6. Security Considerations
-
Why important: Even with limits, a compromised container could:
- Attack other containers.
- Escalate to host system.
-
Best practices:
- Run as non-root (
--user
). - Use minimal base images (e.g.,
alpine
). - Apply AppArmor/SELinux profiles.
- Keep images updated & signed.
- Restrict network/volume access.
- Run as non-root (
β Example: Running Nginx as non-root prevents attackers from gaining full system privileges if the container is hacked.
β Final Summary
- CPU & Memory limits protect host stability.
- Reservation vs Limit = soft guarantee vs hard cap.
-
Docker units:
--cpus
,--memory
, etc. -
Kubernetes units:
m
(millicores) for CPU. - Always leave buffer for the OS.
- Use security hardening (non-root, minimal images, profiles).
π Docker Security β Best Practices
1. Definition
- Docker security = practices that reduce attack surface and protect containers, hosts, and data.
- Covers image hygiene, runtime restrictions, network control, and host hardening.
2. Key Security Practices (with Examples)
- Use lightweight base images
- Smaller = fewer packages = fewer vulnerabilities.
-
Example:
FROM alpine:3.18
- Run as non-root user
RUN adduser -D appuser
USER appuser
- Keep images updated
- Regularly rebuild and pull patched versions.
- Use multi-stage builds
- Builder stage has compilers/tools.
- Final stage contains only the app binary β smaller & safer.
- Drop privileges at runtime
docker run --security-opt=no-new-privileges --cap-drop=ALL ...
- Limit CPU & memory (DoS protection)
docker run -d --memory=512m --cpus="0.5" nginx
- Use Docker Secrets (Swarm mode)
- Store DB passwords, API keys securely (not in
env
).
- Network hygiene
- Expose only needed ports.
- Use user-defined networks for isolation.
- Host hardening
- Enable SELinux/AppArmor.
- Keep Docker & kernel patched.
- Scan & rebuild images regularly
- Tools:
trivy
,clair
.
- Keep containers minimal
- One process per container.
- Avoid running SSHd inside.
3. Practical Secure Run Example
docker run -d --name safe-app \
--memory=512m --cpus="0.5" \
--security-opt=no-new-privileges \
--cap-drop=ALL \
--read-only \
--tmpfs /tmp:rw,size=64m \
myuser/app:1.0
β Non-root, read-only FS, no extra capabilities, tmpfs for writes.
π Docker Command Reference
πΉ 1. System & Info
docker --version # Show version
docker info # Host + engine info
docker ps # List running containers
docker ps -a # List all containers
docker inspect <ctr> # Detailed info
docker stats # Live CPU, memory usage
docker top <ctr> # Show processes in container
πΉ 2. Running & Managing Containers
docker run -it --name mybox alpine /bin/sh # Interactive
docker run -d --name web -p 8080:80 httpd # Detached mode
docker create --name test httpd # Create only
docker start/stop/restart <ctr> # Manage lifecycle
docker pause/unpause <ctr> # Freeze/unfreeze
πΉ 3. Logs & Monitoring
docker logs <ctr> # Show logs
docker logs -f --tail 100 <ctr> # Follow logs
πΉ 4. Copy & Rename
docker cp <ctr>:/path/in/ctr /path/on/host
docker rename old_name new_name
πΉ 5. Resource Controls
docker run -d --memory=512m httpd
docker run -d --cpus="1.5" --memory=512m httpd
docker update --cpus=1.5 --memory=512m <ctr>
πΉ 6. Remove Containers & Images
docker rm <ctr> # Remove container
docker rmi <image> # Remove image
docker system prune -a # Remove unused
πΉ 7. Import / Export
docker export <ctr> > ctr.tar
docker import ctr.tar myimg:latest
docker save -o img.tar myimg
docker load -i img.tar
πΉ 8. Images
docker images # List
docker image history httpd # Layers
docker image inspect httpd # Metadata
docker pull httpd:latest # Download
docker tag httpd:latest myrepo/httpd # Retag
docker push myrepo/httpd # Push
docker search nginx # Search Hub
πΉ 9. Volumes
docker volume ls
docker volume create myvol
docker volume rm myvol
docker volume prune
docker run -d -v myvol:/data httpd
docker run -d --mount type=bind,source=/host,target=/ctr alpine
docker run -d --mount type=tmpfs,destination=/app,tmpfs-size=70m alpine
πΉ 10. Networks
docker network ls
docker network create mybridge
docker network create --driver overlay myoverlay # Swarm only
docker network connect mybridge <ctr>
docker network disconnect mybridge <ctr>
docker run -d --name web --network mybridge nginx
docker run -d --network none nginx # Isolated
docker network rm mybridge
Top comments (0)