The Essence of Containers
About 2485 words
1. Clearing Up Misconceptions: What a Container Is Not
Before understanding containers, it helps to clear up two common misconceptions.
A container is not a virtual machine.
A virtual machine uses a hypervisor to virtualize a complete set of hardware, and each VM runs its own guest OS kernel. A container runs directly on the host kernel: it has no kernel of its own and is fundamentally an ordinary process that has been "isolated".
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
│ VM architecture │ │ Container architecture │
│ │ │ │
│ App A │ App B │ App C │ │ App A │ App B │ App C │
│ Bins/Libs │ Bins/Libs │ ... │ │ Bins/ │ Bins/ │ Bins/ │
│ Guest OS │ Guest OS │ │ │ Libs │ Libs │ Libs │
│─────────────────────────────────│ │─────────────────────────────────│
│ Hypervisor │ │ Container Runtime │
│─────────────────────────────────│ │─────────────────────────────────│
│ Host OS Kernel │ │ Host OS Kernel │
│─────────────────────────────────│ │─────────────────────────────────│
│ Physical Hardware │ │ Physical Hardware │
└─────────────────────────────────┘ └─────────────────────────────────┘This is also why:
- Containers must use the same kernel family as their host: Linux cannot run Windows containers, or vice versa.
- Containers start in milliseconds, because starting one means starting a process, while VMs take seconds.
- Container overhead is tiny, allowing one physical machine to run thousands or tens of thousands of containers.
2. Containers Combine Three Linux Kernel Features
A container is not a single "technology"; it is a combination of three Linux kernel features:
Container=Namespaces (view isolation)+Cgroups (resource limits)+UnionFS (filesystem layers)
2.1 Namespaces: "What Can I See?"
Linux namespaces provide isolation of resource views. Each process can have an independent "view of the world". Linux currently supports eight namespace types:
| Namespace type | Isolated resource | Effect |
|---|---|---|
| Mount (mnt) | Filesystem mount points | The container has its own root filesystem. |
| PID | Process ID number space | Processes inside see PIDs starting at 1. |
| Network (net) | Network devices, IP addresses, and ports | Independent network interfaces and IP addresses. |
| IPC | Interprocess communication resources | Isolates semaphores, message queues, and shared memory. |
| UTS | Hostname and domain name | The container can have its own hostname. |
| User | User and group IDs | Root inside a container can map to an ordinary user on the host. |
| Cgroup | View of the cgroup root | The container sees different cgroup paths. |
| Time | System time | The container can have an independent system clock. |
Key idea: Namespaces determine what a process can see. Once placed in a namespace, a process can see only the resources within that namespace's scope.
2.2 Cgroups: "How Much Can I Use?"
Control groups provide resource limiting and accounting in the kernel. They limit, account for, and isolate physical resource usage by groups of processes.
Common cgroups v2 controllers:
| Controller | Controlled resource |
|---|---|
| cpu | CPU time quota. |
| memory | Memory usage limit, including OOM behavior. |
| io | Block-device I/O bandwidth and IOPS. |
| pids | Maximum process count. |
| cpuset | Binding to specific CPU cores or NUMA nodes. |
| hugetlb | Huge-page memory usage. |
Key idea: Cgroups determine how much a process can use. They prevent a container from consuming an entire machine's resources.
2.3 UnionFS: "Where Are My Files?"
Union filesystems such as OverlayFS combine multiple directories, or layers, into one unified view. Container image layering and fast distribution depend on this capability.
┌────────────────────────────┐
│ Container Layer (RW) │ ← Writable layer for runtime changes
├────────────────────────────┤
│ Image Layer 3 (RO) │ ← RUN apt-get install nginx
├────────────────────────────┤
│ Image Layer 2 (RO) │ ← COPY app binary
├────────────────────────────┤
│ Image Layer 1 (RO) │ ← FROM ubuntu:22.04
└────────────────────────────┘Key idea: UnionFS determines where files live and how they are reused. Image layers are read-only; all changes go into the top writable container layer.
3. Hands-On: Building a Container Manually on Linux
With the principles established, try them directly. Run the following steps on a physical or virtual Linux machine; Ubuntu 22.04 is recommended.
3.1 Prepare a Root Filesystem
First prepare a Linux root filesystem to act as the container "image". The simplest options are debootstrap or exporting a Docker image:
# Option 1: Export a rootfs with Docker
docker export $(docker create ubuntu:22.04) -o ubuntu.tar
mkdir rootfs && tar -xf ubuntu.tar -C rootfs
# Option 2: Use debootstrap; first run apt install debootstrap
# sudo debootstrap jammy rootfs http://archive.ubuntu.com/ubuntu3.2 Step 1: Isolate the Filesystem with a Mount Namespace
Make the process see only the prepared rootfs:
# unshare creates a mount namespace; chroot then changes the root directory
sudo unshare --mount --fork /bin/bash -c "
# Remount /proc inside the new namespace
mount -t proc proc rootfs/proc
# Switch the root filesystem
chroot rootfs /bin/bash
"Running ls / now shows files from rootfs, rather than the host root directory.
3.3 Step 2: Isolate the Process View with a PID Namespace
Add --pid so the container process sees itself as PID 1:
sudo unshare --mount --pid --fork /bin/bash -c "
mount -t proc proc rootfs/proc
chroot rootfs /bin/bash
# ps aux would fail now because /proc is not mounted correctly yet
mount -t proc proc /proc
ps aux
"Only a few processes appear inside the container, and bash itself has PID 1.
3.4 Step 3: Isolate Networking with a Network Namespace
Add --net to give the container an independent network stack:
sudo unshare --mount --pid --net --fork /bin/bash -c "
# Initialize the lo loopback interface
ip link set lo up
# ifconfig now shows only lo, without an eth0 interface
mount -t proc proc rootfs/proc
chroot rootfs /bin/bash
"To reach external networks, create a veth pair connecting the container's network namespace to a host bridge. That is precisely what Docker and CNI do.
3.5 Step 4: Isolate the Hostname with a UTS Namespace
Add --uts so the container can have its own hostname:
sudo unshare --mount --pid --net --uts --fork /bin/bash -c "
hostname my-container
mount -t proc proc rootfs/proc
chroot rootfs /bin/bash
hostname # Output: my-container
"3.6 Step 5: Limit Resources with Cgroups
unshare cannot configure cgroup limits directly. You must manipulate the cgroup filesystem manually:
# Create a cgroup, using cgroups v2 here
sudo mkdir /sys/fs/cgroup/mycontainer
# Limit memory to 128MB
echo "134217728" | sudo tee /sys/fs/cgroup/mycontainer/memory.max
# Limit CPU usage to 0.5 cores; 50000 represents 50%
echo "50000 100000" | sudo tee /sys/fs/cgroup/mycontainer/cpu.max
# Start the container process and add it to the cgroup
sudo unshare --mount --pid --net --uts --fork /bin/bash -c "
echo \$\$ | sudo tee /sys/fs/cgroup/mycontainer/cgroup.procs
mount -t proc proc rootfs/proc
chroot rootfs /bin/bash
"3.7 Complete Container Startup Script
Combine the preceding steps into my-container.sh:
#!/bin/bash
set -e
ROOTFS="./rootfs"
CGROUP_NAME="mycontainer"
HOSTNAME="my-container"
# 1. Create the cgroup and configure resource limits
sudo mkdir -p /sys/fs/cgroup/$CGROUP_NAME
echo "134217728" | sudo tee /sys/fs/cgroup/$CGROUP_NAME/memory.max > /dev/null
echo "50000 100000" | sudo tee /sys/fs/cgroup/$CGROUP_NAME/cpu.max > /dev/null
echo "256" | sudo tee /sys/fs/cgroup/$CGROUP_NAME/pids.max > /dev/null
# 2. Start the isolated process
sudo unshare \
--mount \
--pid \
--net \
--uts \
--ipc \
--cgroup \
--fork \
/bin/bash -c "
# Add this process to the cgroup
echo \$\$ > /sys/fs/cgroup/$CGROUP_NAME/cgroup.procs
# Set the hostname
hostname $HOSTNAME
# Mount essential filesystems
mount -t proc proc ${ROOTFS}/proc
mount -t sysfs sysfs ${ROOTFS}/sys
mount -t tmpfs tmpfs ${ROOTFS}/tmp
mount -t tmpfs tmpfs ${ROOTFS}/run
mkdir -p ${ROOTFS}/dev/pts
mount -t devpts devpts ${ROOTFS}/dev/pts
# Initialize the lo interface
ip link set lo up
# Switch the root filesystem
chroot ${ROOTFS} /bin/bash
"Run bash my-container.sh to get a hand-built "container" with an independent filesystem, process space, network stack, hostname, and resource limits.
Key insight: Container runtimes such as Docker and containerd essentially automate these steps: parse images, prepare rootfs, create namespaces, configure cgroups, and set up networking. No magic is involved.
3.8 Further Detail: System Calls Behind Namespace Operations
Does Linux have a dedicated command to "create a namespace"? No. A namespace is not an independently existing kernel object: it is associated with processes, created by them and automatically destroyed when the last process exits.
The kernel offers three system calls for namespace operations. The unshare command is a command-line wrapper around one of them:
| System call | Purpose | Analogy |
|---|---|---|
clone(flags) | Creates a child process with independent namespaces when CLONE_NEW* flags are specified. | "Have a child and give them a new house." |
unshare(flags) | Detaches the calling process from existing namespaces and gives it new ones. | "Move into a new house myself." |
setns(fd, nstype) | Joins an existing namespace. | "Move into someone else's existing house." |
Their relationship is illustrated below:
clone() ──→ Create a child process in a new namespace
┌──────────┐
│ Parent │ (old NS)
└────┬─────┘
│ clone(CLONE_NEWNET)
┌────▼─────┐
│ Child │ (new NS)
└──────────┘
unshare() ──→ Leave the old namespace and obtain a new one
┌──────────┐ ┌──────────┐
│Self oldNS│ ──→ │Self newNS│
└──────────┘ └──────────┘
setns() ──→ Join an existing namespace
┌──────────┐ ┌──────────┐
│Self NS A │ ──→ │Self NS B │
└──────────┘ └──────────┘The three corresponding command-line tools used in practice are:
| Command | Underlying operation | Typical use |
|---|---|---|
unshare | unshare() | Manually simulate a container by starting a shell in new namespaces. |
nsenter | setns() | Enter a running container or Pod for debugging. |
lsns | Reads /proc | List all namespaces on the system. |
Some practical examples:
# unshare: create new net and PID namespaces for bash, as above
sudo unshare --net --pid --fork /bin/bash
# nsenter: enter a running container's network namespace for troubleshooting
# First obtain the container process PID
PID=$(docker inspect <container_id> --format '{{.State.Pid}}')
sudo nsenter --net --target $PID
# ifconfig now shows the container interfaces, allowing network troubleshooting
# lsns: list all namespaces on the system
lsns
# NS TYPE NPROCS PID USER COMMAND
# 4026531834 time 4 1234 root /sbin/init
# 4026531835 cgroup 4 1234 root /sbin/init
# 4026531992 net 2 5678 root /pause ← A Pod's Pause containerThis explains why Pods need Pause containers: A namespace's lifecycle depends on the processes referencing it. When the last process exits, the kernel reclaims the namespace. The Pause container stays alive, anchoring the network namespace so that application containers can join through setns(). If the Pause container dies, the Pod's network namespace disappears.
4. Kubernetes Pods: Containers Sharing Namespaces
4.1 Pod = The Smallest Scheduling Unit
In Kubernetes, the Pod is the smallest scheduling and deployment unit. A container cannot be scheduled directly: Kubernetes always schedules Pods.
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: app
image: nginx:latest
- name: sidecar
image: busybox:latest
command: ["sh", "-c", "while true; do echo hello; sleep 5; done"]4.2 A Pod Is a Group of Containers Sharing Namespaces
Returning to namespace theory: a Pod is a group of containers sharing specific namespaces.
┌─────────────────────────────────────────┐
│ Pod │
│ │
│ Shared network namespace: same IP/ports │
│ Shared IPC namespace: interprocess IPC │
│ Shared UTS namespace: same hostname │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Container│ │Container│ │Container│ │
│ │ A │ │ B │ │ C │ │
│ │ │ │ │ │ │ │
│ │Separate │ │Separate │ │Separate │ │
│ │Mount NS │ │Mount NS │ │Mount NS │ │
│ │PID NS │ │PID NS │ │PID NS │ │
│ └─────────┘ └─────────┘ └─────────┘ │
│ Shared Volumes through mounts │
└─────────────────────────────────────────┘Specifically, containers in a Pod share the following namespaces:
| Namespace | Shared? | Description |
|---|---|---|
| Network | ✅ Yes | All containers share one IP address and port space and communicate through localhost. |
| IPC | ✅ Yes | They can communicate using System V semaphores or POSIX message queues. |
| UTS | ✅ Yes | They share a hostname, which defaults to the Pod name. |
| Mount | ❌ Separate | Each has its own image filesystem, but Volumes can share directories. |
| PID | Optional | shareProcessNamespace: true enables sharing; disabled by default. |
4.3 How Pods Work: The Infra or Pause Container
How does Kubernetes implement a shared network namespace? Through an infra container, also called the Pause or sandbox container.
When a Pod starts:
- Start the Pause container first: A minimal container, such as
registry.k8s.io/pause:3.9, whose sole job is to callpause()and sleep forever. - The Pause container creates the network and IPC namespaces.
- Application containers join those namespaces.
Startup order:
Step 1: Create Pause container, holding the network and IPC namespaces
Step 2: Container A → Join Pause's network and IPC namespaces
Step 3: Container B → Join Pause's network and IPC namespaces
Step 4: Container C → Join Pause's network and IPC namespacesThis is why even a single-container Pod has a running Pause container: it anchors the entire Pod's namespaces.
To verify:
# On any Kubernetes node
crictl ps | grep pause
# A corresponding Pause container appears for each Pod5. Multi-Container Pod Design Patterns
A Pod is more than a wrapper around one container. It can run several tightly cooperating containers that share networking and IPC, forming a logical "multiple processes on one machine" model.
5.1 Sidecar Pattern (Most Common)
A sidecar enhances or assists the main container, with a lifecycle tied to that container.
Classic example: log collection
apiVersion: v1
kind: Pod
metadata:
name: app-with-log-sidecar
spec:
containers:
- name: app # Main container: writes logs
image: my-app:latest
volumeMounts:
- name: logs
mountPath: /var/log/app
- name: log-shipper # Sidecar: collects and forwards logs
image: fluentd:latest
volumeMounts:
- name: logs
mountPath: /var/log/app
volumes:
- name: logs
emptyDir: {}The sidecar reads application logs from a shared Volume and forwards them to a logging platform. The containers can communicate through localhost.
5.2 Init Containers
Init containers run before application containers to perform initialization. They execute sequentially, and all must exit successfully before application containers start.
apiVersion: v1
kind: Pod
metadata:
name: app-with-init
spec:
initContainers:
- name: init-db
image: busybox:latest
command: ["sh", "-c", "until nslookup mysql; do sleep 2; done"]
- name: init-config
image: busybox:latest
command: ["sh", "-c", "cp /config-template/* /config/"]
containers:
- name: app
image: my-app:latestKey differences:
| Init Container | Sidecar Container | |
|---|---|---|
| When it runs | Before application containers | Alongside application containers |
| Execution order | Strictly sequential | Starts concurrently |
| Failure handling | Must succeed before the Pod starts | Can restart without affecting other containers |
| Purpose | Preprocessing and waiting for dependencies | Ongoing assistance to the main container |
5.3 Ambassador Pattern
An ambassador container acts as a proxy between the main container and external services, handling tasks such as connection pooling, retries, and TLS termination.
┌───────────────────────────┐
│ Pod │
│ │
│ ┌──────────┐ ┌────────┐ │ ┌──────────────┐
│ │ App │─▶│Ambassador│─┼──TLS────▶│ External │
│ │Container │ │Container│ │ │ Service │
│ │localhost │ │ (Envoy) │ │ └──────────────┘
│ └──────────┘ └────────┘ │
└───────────────────────────┘The application only accesses localhost:port; the ambassador handles complex communication with external services.
5.4 Adapter Pattern
An adapter transforms the main container's output to match the interface expected by an external system. A Prometheus exporter sidecar is a typical example.
┌───────────────────────────────┐
│ Pod │
│ │
│ ┌──────────┐ ┌────────────┐ │ ┌──────────────┐
│ │ Redis │─▶│ Adapter │──┼────────▶│ Prometheus │
│ │Container │ │ (exporter) │ │ /metrics│ Server │
│ │ :6379 │ │ :9121 │ │ └──────────────┘
│ └──────────┘ └────────────┘ │
└───────────────────────────────┘5.5 Communication Methods Within a Pod
| Communication method | Use case | Example |
|---|---|---|
| localhost networking | High performance and low latency | Application → sidecar proxy over localhost:8080. |
| Shared Volume | File exchange | Application writes logs; log-shipper reads them. |
| Shared IPC | Interprocess semaphores/message queues | Specialized high-performance scenarios. |
| Unix domain socket | Communication between processes in one Pod | abstract:///my_socket. |
6. Summary
The article establishes the following chain of ideas:
ContainerPodK8s=Namespaces+Cgroups+UnionFS=Containers sharing Network/IPC/UTS namespaces=A system that orchestrates Pods
- Containers are fundamentally process isolation: Ordinary Linux processes with resource limits and layered filesystems, rather than lightweight virtualization.
- Building a container manually is straightforward:
unshare,chroot, and cgroups can produce a homemade container. - A Pod declares namespace-sharing relationships: It defines how a group of containers share networking, IPC, and other namespaces.
- Containers in a Pod form a tightly cooperating unit: Sidecars, init containers, ambassadors, and adapters compose functionality.
With these mechanisms understood, Docker's "magic" becomes a convenient encapsulation of Linux kernel features, and Kubernetes Pod design becomes declarative management of namespace sharing.