Lightweight OS Virtualisation Techniques (chroot, namespace)
OS-level virtualisation creates isolated environments on a single kernel, sharing the kernel among multiple instances. Unlike hardware virtualisation (KVM, VMware), which emulates complete hardware, OS-level virtualisation uses kernel features to partition resources without the overhead of a hypervisor.
chroot: Change Root Directory
The chroot system call changes the apparent root directory for a process and its children. After a chroot("/newroot"), the process sees /newroot as / and cannot access files outside that directory.
Limitations of chroot:
- Only root can
chroot(privilege required). - Processes can escape if they gain root within the chroot.
- Only isolates the filesystem namespace; processes, users, and networking are shared.
chroot is useful for:
- Recovery: Booting from a rescue disk and
chroot-ing into the installed system to repair it. - Building: Creating isolated build environments (e.g., Debian's
pbuilder). - Service confinement: Running network services in a restricted filesystem view.
Example:
mkdir -p /srv/chroot/nginx cp -a /usr/sbin/nginx /srv/chroot/nginx/usr/sbin/ cp -a /etc/nginx /srv/chroot/nginx/etc/ chroot /srv/chroot/nginx nginx
Linux Namespaces
Namespaces are a Linux kernel feature that isolates global system resources, making each process (or group of processes) believe it has its own private instance. Namespaces are the foundation of containers (Docker, LXC).
Namespace Types
Linux provides seven namespace types:
- PID namespace: Isolates process IDs. The init process in a PID namespace is PID 1, and it cannot see processes in other namespaces.
- Network namespace: Provides isolated network stacks (interfaces, routing tables, iptables rules, ports).
- Mount namespace: Provides isolated filesystem mount points.
- UTS namespace: Isolates hostname and domain name.
- IPC namespace: Isolates inter-process communication resources (message queues, semaphores, shared memory).
- User namespace: Maps UIDs/GIDs between the namespace and the host. A process can be root inside the namespace but unprivileged on the host.
- Cgroup namespace: Isolates cgroup root directories.
Creating Namespaces
Namespaces are created using the unshare system call (via the unshare command) or clone:
# Start a shell in new PID and network namespaces unshare --pid --net /bin/sh
Namespaces can be combined for stronger isolation. Docker and LXC use a combination of namespaces plus cgroups for resource control.
cgroups: Resource Control
While namespaces provide isolation, control groups (cgroups) provide resource management and accounting. See Article - Resource management (cgroup, quota) for cgroup details.