眾所周知,docker 使用的是 Linux 的 namespace 技術實現進程隔離,如果我想看到 docker 的視角觀察宿主機的文件結構,特別是對于 mac 系統(tǒng),運用到一些虛擬機的技術,導致無法從 Linux 進程角度看到具體的文件目錄。
在 mac 上經常有如下需求得不到滿足,我們現在就可以利用命名空間技術,還原 Linux 視角。
在一個 shell A 下執(zhí)行
$ docker run --rm -it --name bb busybox sh
在另一個 shell B 下執(zhí)行
$ docker inspect bb
可以觀察到里面的很多目錄前綴都是 /var/lib/docker 開頭,如果想在 mac 上查看這些目錄發(fā)現 mac 上根本是沒有這些目錄,這時候 namespace 技術登場,用魔法打敗魔法。
在另一個 shell B 下執(zhí)行
$ docker run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
$ cd /var/lib/docker/overlay2/2602d5ba5ba42b115a88fe71b98ce079a95211e9bdd459e1febe8038da956a54/work
這里相當于啟動一個 debian 容器,這個容器的進程命名空間是當前的宿主機進程的命名空間,并且使用 nsenter 進入 pid 為 1 的進程的命名空間,這個空間和宿主機是一個空間,
我們在這個命名空間內就很容易進入到 /var/lib/docker 所在的目錄了。
這里在補充一下 nsenter 可使用的參數
# nsenter -h
Usage:
nsenter [options] <program> [<argument>...]
Run a program with namespaces of other processes.
Options:
-t, --target <pid> target process to get namespaces from
-m, --mount[=<file>] enter mount namespace
-u, --uts[=<file>] enter UTS namespace (hostname etc)
-i, --ipc[=<file>] enter System V IPC namespace
-n, --net[=<file>] enter network namespace
-p, --pid[=<file>] enter pid namespace
-U, --user[=<file>] enter user namespace
-S, --setuid <uid> set uid in entered namespace
-G, --setgid <gid> set gid in entered namespace
--preserve-credentials do not touch uids or gids
-r, --root[=<dir>] set the root directory
-w, --wd[=<dir>] set the working directory
-F, --no-fork do not fork before exec'ing <program>
-Z, --follow-context set SELinux context according to --target PID
-h, --help display this help and exit
-V, --version output version information and exit
For more details see nsenter(1).
注意:對于 --pid 參數我本以為可以支持系統(tǒng)上任意的命名空間,但是實際測試下來只有 host 參數可用。