nsenter命令的語法:
nsenter [options] [program [arguments]]
options:
-t, --target pid:指定被進入命名空間的目標(biāo)進程的pid
-m, --mount[=file]:進入mount命令空間。如果指定了file,則進入file的命令空間
-u, --uts[=file]:進入uts命令空間。如果指定了file,則進入file的命令空間
-i, --ipc[=file]:進入ipc命令空間。如果指定了file,則進入file的命令空間
-n, --net[=file]:進入net命令空間。如果指定了file,則進入file的命令空間
-p, --pid[=file]:進入pid命令空間。如果指定了file,則進入file的命令空間
-U, --user[=file]:進入user命令空間。如果指定了file,則進入file的命令空間
-G, --setgid gid:設(shè)置運行程序的gid
-S, --setuid uid:設(shè)置運行程序的uid
-r, --root[=directory]:設(shè)置根目錄
-w, --wd[=directory]:設(shè)置工作目錄
如果沒有給出program,則默認執(zhí)行$SHELL
示例:
運行一個nginx容器,查看該容器的pid:
docker inspect -f {{.State.Pid}} nginx
54325
# 進入net命令空間
nsenter -n -t54325
ip addr
# 進入容器nsenter -m -u -i -n -p -t
nsenter --target 54325 --mount --uts --ipc --net --pid
root@164f44ff58d1:/bin#
在Kubernetes中,在得到容器pid之前還需獲取容器的ID,可以使用如下命令獲?。?/p>
kubectl get pod test -oyaml|grep containerID
- containerID: docker://cf0873782d587dbca6aa32f49605229da3748600a9926e85b36916141597ec85
或者更為精確地獲取containerID:
kubectl get pod test -o template --template='{{range .status.containerStatuses}}{{.containerID}}{{end}}'
docker://cf0873782d587dbca6aa32f49605229da3748600a9926e85b36916141597ec85
原理
namespace是Linux中一些進程的屬性的作用域,使用命名空間,可以隔離不同的進程。
Linux在不斷的添加命名空間,目前有:
- mount:掛載命名空間,使進程有一個獨立的掛載文件系統(tǒng),始于Linux 2.4.19
- ipc:ipc命名空間,使進程有一個獨立的ipc,包括消息隊列,共享內(nèi)存和信號量,始于Linux 2.6.19
- uts:uts命名空間,使進程有一個獨立的hostname和domainname,始于Linux 2.6.19
- net:network命令空間,使進程有一個獨立的網(wǎng)絡(luò)棧,始于Linux 2.6.24
- pid:pid命名空間,使進程有一個獨立的pid空間,始于Linux 2.6.24
- user:user命名空間,是進程有一個獨立的user空間,始于Linux 2.6.23,結(jié)束于Linux 3.8
- cgroup:cgroup命名空間,使進程有一個獨立的cgroup控制組,始于Linux 4.6
Linux的每個進程都具有命名空間,可以在/proc/PID/ns目錄中看到命名空間的文件描述符。
pwd
/proc/1/ns
ll
total 0
lrwxrwxrwx 1 root root 0 Sep 23 19:53 ipc -> ipc:[4026531839]
lrwxrwxrwx 1 root root 0 Sep 23 19:53 mnt -> mnt:[4026531840]
lrwxrwxrwx 1 root root 0 Sep 23 19:53 net -> net:[4026531956]
lrwxrwxrwx 1 root root 0 Sep 23 19:53 pid -> pid:[4026531836]
lrwxrwxrwx 1 root root 0 Sep 23 19:53 user -> user:[4026531837]
lrwxrwxrwx 1 root root 0 Sep 23 19:53 uts -> uts:[4026531838]