π³ 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/exe
refers to the currently running executable -
Cloneflags
create new Linux namespaces for:- π·
CLONE_NEWUTS
: hostname isolation - π’
CLONE_NEWPID
: new PID tree (starts from PID 1) - π
CLONE_NEWNS
: new mount namespace - π§
CLONE_NEWIPC
: new shared memory namespace - π‘
CLONE_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/sh
so 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)