Sobes.tech
Senior

How is container isolation implemented at the Linux kernel level? Please tell me more about namespaces.

sobes.tech AI

Answer from AI

Container isolation in Linux is achieved through the mechanism of namespaces — a kernel feature that allows creating separate spaces for various system resources. Each namespace isolates a specific aspect of the process environment, for example:

  • PID namespace — isolates process identifiers, so processes in one namespace see only their own PIDs.
  • Mount namespace — isolates filesystem mount points, allowing a container to have its own filesystem structure.
  • Network namespace — isolates network interfaces and settings, creating a separate network stack.
  • UTS namespace — isolates hostname and domain name.
  • IPC namespace — isolates inter-process communication.
  • User namespace — isolates user and group IDs, allowing a container to have its own UID/GID.

When a container is created, the kernel creates a set of such namespaces for it, so processes inside the container see only their environment and do not affect processes outside the container. This ensures security and isolation.

An example of creating a new PID namespace in Go using syscall:

package main

import (
    "fmt"
    "syscall"
    "os"
)

func main() {
    cmd := os.Args[0]
    if len(os.Args) > 1 && os.Args[1] == "child" {
        fmt.Printf("[child] PID: %d\n", syscall.Getpid())
        select {} // wait
    } else {
        fmt.Printf("[parent] PID: %d\n", syscall.Getpid())
        attr := &syscall.ProcAttr{
            Files: []uintptr{0, 1, 2},
            Sys: &syscall.SysProcAttr{
                Cloneflags: syscall.CLONE_NEWPID,
            },
        }
        pid, err := syscall.ForkExec(cmd, []string{cmd, "child"}, attr)
        if err != nil {
            panic(err)
        }
        fmt.Printf("Process with new PID namespace started, PID: %d\n", pid)
    }
}

This example demonstrates creating a process with a new PID namespace, where the child process will have its own set of PIDs, isolated from the parent space.