A Minimal Container in Go — ELI5
This Go program creates a tiny container, kind of like Docker, but from scratch using Linux syscalls. No Docker or container engine involved!
What It Does
- Runs itself twice — once as a parent, once as a child
- The parent sets up Linux namespaces for isolation
- The child changes its environment to behave like a container
- Finally, it runs a shell (
/bin/sh) inside that container
Step-by-Step Breakdown
The Golang program we discuss here consists of this header, plus three functions:
|
|
1. Main Function
|
|
- If the program was run with the argument
"child", it does container setup - Otherwise, it behaves as the parent and starts a new containerized child process
2. Parent Process
|
|
-
Runs the same binary again with
"child"as argument -
/proc/self/exerefers to the currently running executable -
Cloneflagscreate new Linux namespaces for:CLONE_NEWUTS: hostname isolationCLONE_NEWPID: new PID tree (starts from PID 1)CLONE_NEWNS: new mount namespaceCLONE_NEWIPC: new shared memory namespaceCLONE_NEWNET: separate networking stack
This isolates the child process just like a real container.
3. Child Process (the “Container”)
|
|
- Sets the container’s hostname to
"container" - Uses
chroot("rootfs")to change the root directory — this limits what the container can “see” on the host filesystem - Changes directory to
/inside that new root - Mounts
/proc, so commands likeps,top, etc. work - Finally, replaces the process with
/bin/shso you’re inside the container shell
Requirements to Make It Work
You need a minimal Linux root filesystem (rootfs/) that includes:
/bin/sh(a shell like BusyBox)- A basic directory structure (
/proc,/etc,/bin, etc.) - Correct permissions and mountable directories
You can build this using BusyBox:
|
|
Why Is This Cool?
You’re building a container runtime like Docker from scratch:
- Isolated process tree
- Isolated hostname and network
- Own root filesystem
- Interactive shell inside the container
All in ~50 lines of Go code, using only Linux syscalls.
Want to Try It?
Containers from Scratch - Building a Container Runtime with Nothing But Syscalls (in Go)