Docker
A complete guide to Docker and containers: why containers changed software delivery, how Linux namespaces and cgroups work, Docker vs VMs, and core commands.
Before the 1950s, shipping goods around the world was slow and expensive. Dockworkers had to load individual sacks of coffee, barrels of oil, and wooden crates onto cargo ships by hand. Loading one ship could take a full week, and goods were frequently damaged or delayed because every port used different equipment. Then an entrepreneur named Malcolm McLean popularized the standardized shipping container: a sturdy steel box with standard dimensions and corner locks. Suddenly, the cranes, trucks, trains, and ships did not need to care what was inside the container. Whether holding bananas, clothing, or electronics, the container fit smoothly onto any truck or cargo ship in the world. Shipping costs plunged, and global trade expanded. Docker did the exact same thing for software. Before Docker, running an application on a server required matching the developer's exact operating system, library versions, language runtimes, and system settings. When things failed, developers would say: 'It works on my machine!' Docker packages your application code, its libraries, configuration files, and dependencies into a standard digital container that runs identically on a developer laptop, a test server, or an enterprise cloud cluster.
Definition
Docker is an open-source platform that packages and runs applications inside lightweight, portable containers, using Linux kernel features (namespaces and control groups) to provide isolation while sharing the host operating system kernel.
Why It Matters
Docker permanently addressed the common 'works on my machine' headache. If a container runs on your local computer, it will run with the exact same behavior in testing environments and on production cloud servers. Before Docker, teams primarily used Virtual Machines (VMs) for environment isolation. But VMs require an entire guest operating system (consuming gigabytes of memory and storage) and take minutes to boot. Docker containers share the host operating system's kernel, start in seconds, use far less memory, and allow companies to run many more applications on the same physical server, significantly reducing infrastructure costs.
How It Works
Docker is not a hardware hypervisor; it does not simulate a virtual computer or boot a separate guest operating system. Instead, Docker relies on built-in Linux kernel capabilities: 1. Linux Namespaces (Process and Resource Isolation): Namespaces give each container the appearance of having its own private operating system: • PID Namespace: Gives the container an isolated process list (its main process runs as PID 1). • NET Namespace: Gives the container its own virtual network interface, IP address, and port bindings. • MNT Namespace: Isolates the filesystem mount points visible to the container. • IPC Namespace: Keeps inter-process communication (like shared memory) separate between containers. • UTS Namespace: Allows each container to have its own hostname. • USER Namespace: Maps the container's internal root user to an unprivileged user on the host system for added safety. 2. Control Groups (cgroups: Resource Limits): cgroups meter and limit how much physical hardware a container can consume. For example, you can set a limit that a container cannot use more than 512MB of RAM and 1 CPU core. If the application has a memory leak and exceeds that limit, the operating system stops only that container, protecting the rest of the host from crashing. 3. OverlayFS (Layered Storage and Copy-on-Write): Docker images are built as a stack of read-only layers. When a container starts, Docker places a thin, temporary read-write layer on top. If fifty containers run the same Node.js image, they all share the exact same read-only layers on disk, using minimal additional storage. 4. Core Docker Components: • Docker CLI: The command-line tool you use to interact with Docker (`docker run`, `docker build`). • Docker Daemon (`dockerd`): The background service managing containers, images, networks, and volumes. • containerd and runc: The industry-standard runtime tools that talk directly to the Linux kernel to launch container processes.
Docker Container Architecture vs Virtual Machines
Key Points
- Containers are isolated host processes sharing the host operating system kernel; they are not mini Virtual Machines.
- An Image is an immutable blueprint (like a class); a Container is a running instance of that image (like an object).
- Linux Namespaces provide process, network, and filesystem isolation.
- Control Groups (cgroups) keep a single runaway container from consuming all system CPU or RAM.
- OverlayFS uses Copy-on-Write so multiple containers can share the same underlying read-only image layers.
- Docker Volumes are used to store data permanently so information is not lost when a container stops.
Steps
Install Docker Engine
Install Docker Desktop on macOS or Windows, or Docker Engine on Linux to run the background service.
Download a Pre-Built Image
Download an official image from Docker Hub using `docker pull nginx:alpine`.
Start a Container with Port Forwarding
Run your container with `docker run -d -p 8080:80 --name my-webserver nginx:alpine` and view it in your browser at `http://localhost:8080`.
Inspect Logs and Running Processes
View running containers using `docker ps`, check application logs with `docker logs my-webserver`, or open a terminal inside with `docker exec -it my-webserver sh`.
Stop and Remove the Container
Stop the container with `docker stop my-webserver` and delete it when finished using `docker rm my-webserver`.
Examples
The Recipe vs Cake Analogy
A Docker Image is like a recipe in a cookbook: it lists the ingredients and step-by-step instructions, sitting safely on your shelf. A Docker Container is the actual cake baked from that recipe. You can bake fifty identical cakes (containers) from that single recipe (image).
The Apartment Building Analogy
Virtual Machines are like separate single-family houses: each has its own independent roof, furnace, and plumbing (guest OS). Docker containers are like apartments in a modern building: each resident has their own locked private space (isolated processes), but all apartments share the building's central heating, water, and foundation (host OS kernel).
Real-World Examples
Spotify's Move to Containers
Spotify transitioned thousands of internal microservices from heavy virtual machines to lightweight Docker containers. Removing the overhead of separate guest operating systems reduced server costs, lowered application startup times from minutes to seconds, and paved the way for automated container orchestration with Kubernetes.
Technical Examples
# ─── Production Container Launch with Security & Resource Limits ─────
docker run -d \
--name payment-api \
--restart unless-stopped \
-p 8080:8080 \
# Resource limits using Linux cgroups
--memory="512m" \
--memory-reservation="256m" \
--cpus="1.5" \
# Security settings
--read-only \
--cap-drop=ALL \
--cap-add=NET_BIND_SERVICE \
--security-opt=no-new-privileges:true \
# Storage mounts
-v payment_data:/var/lib/payments \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
# Runtime configuration
-e NODE_ENV=production \
-e DATABASE_URL="postgres://user:pass@db.internal:5432/pay" \
# Container health check
--health-cmd="curl -f http://localhost:8080/healthz || exit 1" \
--health-interval=10s \
--health-timeout=3s \
--health-retries=3 \
ghcr.io/myorg/payment-api:v2.1.0
# Check container health status
docker inspect --format='{{json .State.Health}}' payment-api | jqDocker Containers vs Virtual Machines (VMs)
| Aspect | Docker Containers | Virtual Machines (VMs) |
|---|---|---|
| Operating System | Shares the host OS kernel directly | Runs a complete, independent Guest OS |
| Startup Time | Seconds or milliseconds | One to several minutes |
| Resource Usage | Lightweight: only the application and required libraries | Heavy: full OS kernel, memory overhead, and disk storage |
| Server Density | Can run many containers on a single host | Fewer virtual machines can run on the same physical server |
| Isolation Type | Process-level isolation via kernel namespaces | Hardware-level isolation via a hypervisor |
How Linux Namespaces & cgroups Work Under the Hood
Advantages
- Environment Consistency: Guarantees that code runs identically across development, staging, and production.
- Efficient Resource Usage: Shares the host kernel, letting you run more services on the same physical hardware.
- Fast Startup: Starts in seconds because there is no full operating system boot process.
- Portability: Standard container images run on local machines, on-premises servers, and all major cloud providers.
Limitations
- Shared Kernel Model: Because containers share the host kernel, security relies on kernel namespaces and isolation controls.
- Linux Dependency: Containers need a Linux kernel to run (Docker on Windows or macOS runs inside a lightweight Linux virtual machine behind the scenes).
Interview Questions
How do Linux Namespaces and Control Groups (cgroups) enable containerization?
Namespaces provide isolation by giving each container its own private view of system resources: PID namespaces isolate running processes, NET namespaces isolate network interfaces and IPs, and MNT namespaces isolate filesystems. Control Groups (cgroups) provide resource management by setting hard limits on how much CPU, memory, and disk I/O each container can use.
Practice Questions
- Start an NGINX container with a memory limit of 64MB using `--memory=64m` and inspect its resource usage with `docker stats`.
- Mount a local folder into an NGINX container using `-v $(pwd):/usr/share/nginx/html:ro` and update an HTML file to see live changes.
