Docker 常被當成新技術,但除了 Go 語言之外,它其實是個「新瓶裝舊酒」——The New "Old Stuff"。Docker 與其生態用了許多很有意思的技術,這個系列會逐一拆解,目標是讓你能自己動手做一個山寨版。第一站:Linux Namespace。

Linux Namespace 是核心層級的環境隔離機制。它其實是 chroot 的進化版:chroot 透過換根目錄,讓程序看不到外面的檔案系統,隔離能力僅限於此。Namespace 則把 UTS、IPC、mount、PID、network、User 等資源都納入隔離範圍。
舉例說,Linux 的 1 號進程是 init,地位特殊。如果我們能把使用者的進程空間關進某個分支,並讓它看到的父進程 PID 是 1,就達到了資源隔離的效果——不同 PID namespace 的進程彼此不可見。

clone():建立新進程,透過參數指定要隔離哪些 namespace。unshare():讓進程脫離某個 namespace。setns():讓進程加入某個 namespace。後兩者行為單純,man 手冊寫得很清楚。以下範例建議在 3.8 以上核心測試(本文使用 Ubuntu 14.04)。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sched.h>
#define STACK_SIZE (1024 * 1024)
static char container_stack[STACK_SIZE];
char* const container_args[] = { "/bin/bash", NULL };
int container_main(void* arg) {
printf("Container - inside the container!\n");
execv(container_args[0], container_args);
printf("Something's wrong!\n");
return 1;
}
int main() {
printf("Parent - start a container!\n");
int container_pid = clone(container_main, container_stack+STACK_SIZE, SIGCHLD, NULL);
waitpid(container_pid, NULL, 0);
printf("Parent - container stopped!\n");
return 0;
}
玩法與 pthread 幾乎一樣,但此時父子進程的資源完全共享,沒有任何隔離。
int container_main(void* arg) {
printf("Container - inside the container!\n");
sethostname("container", 10);
execv(container_args[0], container_args);
return 1;
}
int main() {
int container_pid = clone(container_main, container_stack+STACK_SIZE, CLONE_NEWUTS | SIGCHLD, NULL);
waitpid(container_pid, NULL, 0);
return 0;
}
需 root 執行,子進程的 hostname 變成 container:
root@container:~# hostname container root@container:~# uname -n container
IPC 包含共享記憶體、信號量、訊息佇列,靠全域 ID 定位。要隔離就必須讓這個 ID 也只在 namespace 內可見:
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWIPC | SIGCHLD, NULL);
先在主機建一個佇列:
hchen@ubuntu:~$ ipcmk -Q Message queue id: 0 hchen@ubuntu:~$ ipcs -q ------ Message Queues -------- key msqid owner perms used-bytes messages 0xd0d56eb2 0 hchen 644 0 0
沒有加 CLONE_NEWIPC 時,子進程看得到這個佇列;加上之後:
root@container:~/linux_namespace# ipcs -q ------ Message Queues -------- key msqid owner perms used-bytes messages
佇列消失,隔離成立。
int container_main(void* arg) {
printf("Container [%5d] - inside the container!\n", getpid());
sethostname("container", 10);
execv(container_args[0], container_args);
return 1;
}
int main() {
printf("Parent [%5d] - start a container!\n", getpid());
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWPID | SIGCHLD, NULL);
waitpid(container_pid, NULL, 0);
return 0;
}
Parent [ 3474] - start a container! Container [ 1] - inside the container!
1 號進程在傳統 UNIX 中負責回收孤兒進程、屏蔽部分信號,地位極特殊。但此時在容器裡跑 ps、top,仍看得到主機全部進程——因為這些工具讀的是 /proc,而 /proc 還沒被隔離。
int container_main(void* arg) {
printf("Container [%5d] - inside the container!\n", getpid());
sethostname("container", 10);
system("mount -t proc proc /proc");
execv(container_args[0], container_args);
return 1;
}
int main() {
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);
waitpid(container_pid, NULL, 0);
return 0;
}
root@container:~# ps -elf F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD 4 S root 1 0 0 80 0 - 6917 wait 19:55 pts/2 00:00:00 /bin/bash 0 R root 14 1 0 80 0 - 5671 - 19:56 pts/2 00:00:00 ps -elf
只剩兩個進程,1 號就是我們的 bash,/proc 也乾淨了。

重點:建立 mount namespace 後,父進程會把檔案結構複製一份給子進程,此後子進程的所有掛載動作都不影響外界,隔離更嚴格。
先準備 rootfs 目錄:
hchen@ubuntu:~/rootfs$ ls bin dev etc home lib lib64 mnt opt proc root run sbin sys tmp usr var
把需要的指令複製進 bin(bash 一定要,否則沒法 chroot):
hchen@ubuntu:~/rootfs$ ls ./bin ./usr/bin
./bin: bash cat chgrp chmod chown cp echo grep hostname ip kill ln ls
more mount mountpoint mv nc netstat ping ps pwd rm sed sh sleep
sort tac tail tar tee test timeout touch tr truncate tty umount uname which
./usr/bin: awk env groups head id mesg sort strace tail top uniq vi wc xargs
依賴的 so 用 ldd 查出來:
hchen@ubuntu:~/rootfs/bin$ ldd bash linux-vdso.so.1 => (0x00007fffd33fc000) libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 /lib64/ld-linux-x86-64.so.2 (0x00007f4bd4504000)
連帶的設定檔也要補齊:
hchen@ubuntu:~/rootfs$ ls ./etc bash.bashrc group hostname hosts ld.so.cache nsswitch.conf passwd profile resolv.conf shadow
但 hosts、hostname、resolv.conf 這類檔案應該在容器啟動時才決定,不該寫死在鏡像裡。所以在外層再開一個 conf 目錄:
hchen@ubuntu:~$ ls ./conf hostname hosts resolv.conf
父進程就能動態產生這些設定,再 bind mount 進容器。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <sched.h>
#define STACK_SIZE (1024 * 1024)
static char container_stack[STACK_SIZE];
char* const container_args[] = { "/bin/bash", "-l", NULL };
int container_main(void* arg) {
printf("Container [%5d] - inside the container!\n", getpid());
sethostname("container", 10);
mount("proc", "rootfs/proc", "proc", 0, NULL);
mount("sysfs", "rootfs/sys", "sysfs", 0, NULL);
mount("none", "rootfs/tmp", "tmpfs", 0, NULL);
mount("udev", "rootfs/dev", "devtmpfs", 0, NULL);
mount("devpts", "rootfs/dev/pts", "devpts", 0, NULL);
mount("shm", "rootfs/dev/shm", "tmpfs", 0, NULL);
mount("tmpfs", "rootfs/run", "tmpfs", 0, NULL);
/* 模仿 Docker 從外部掛入設定檔 */
mount("conf/hosts", "rootfs/etc/hosts", "none", MS_BIND, NULL);
mount("conf/hostname", "rootfs/etc/hostname", "none", MS_BIND, NULL);
mount("conf/resolv.conf", "rootfs/etc/resolv.conf", "none", MS_BIND, NULL);
/* 模仿 docker run -v */
mount("/tmp/t1", "rootfs/mnt", "none", MS_BIND, NULL);
if (chdir("./rootfs") != 0 || chroot("./") != 0) { perror("chdir/chroot"); }
execv(container_args[0], container_args);
perror("exec");
return 1;
}
int main() {
printf("Parent [%5d] - start a container!\n", getpid());
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);
waitpid(container_pid, NULL, 0);
printf("Parent - container stopped!\n");
return 0;
}
執行後可以看到掛載狀況與一個「鏡像」的雛形:
hchen@ubuntu:~$ sudo ./mount Parent [ 4517] - start a container! Container [ 1] - inside the container! root@container:/# mount proc on /proc type proc (rw,relatime) sysfs on /sys type sysfs (rw,relatime) none on /tmp type tmpfs (rw,relatime) udev on /dev type devtmpfs (rw,relatime,size=493976k,nr_inodes=123494,mode=755) devpts on /dev/pts type devpts (rw,relatime,mode=600,ptmxmode=000) tmpfs on /run type tmpfs (rw,relatime)
rootfs 目錄的製作可以參考 DebootstrapChroot 這類工具。剩下的就交給你的想像力了。
下篇會談 User Namespace、Network Namespace,以及其他 Namespace 的細節。