1.安装nsenter
nsenter 工具在util-linux包2.23版本后包含。如果系统中 util-linux 包没有该命令,可以按照下面的方法从源码安装。
[root@localhost ~]
# cd /usr/local/src/
[root@localhost src]
# curl https://www./pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz | tar -zxf-; cd util-linux-2.24;
[root@localhost util-linux-2.24]
# ./configure --without-ncurses
[root@localhost util-linux-2.24]
# make nsenter && cp nsenter /usr/local/bin
2.nsenter使用
在使用nsenter命令之前需要获取到docker容器的进程,然后再使用nsenter工具进去到docker容器中,具体的使用方法如下:
# docker inspect -f {{.State.Pid}} 容器名或者容器id //每一个容器都有.State.Pid,所以这个命令除了容器的id需要我们根据docker ps -a去查找,其他的全部为固定的格式
# nsenter --target 上面查到的进程id --mount --uts --ipc --net --pid // 输入该命令便进入到容器中
解释nsenter指令中进程
id
之后的参数的含义:
--
mount
参数是进去到
mount
namespace中
--uts参数是进入到uts namespace中
--ipc参数是进入到System V IPC namaspace中
--net参数是进入到network namespace中
--pid参数是进入到pid namespace中
--user参数是进入到user namespace中
在Linux中,最爱简单的查看指定命令参数含义的办法是在终端中输入:
# nsenter --help #会回显所有与该命令有关的参数
# man nsenter #能查到更加详细的使用示例和参数说明
[root@localhost ~]
# nsenter --help
Usage:
nsenter [options] <program> [args...]
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
user namespace
-G, --setgid <gid>
set
gid
in
user namespace
-r, --root [=<
dir
>]
set
the root directory
-w, --wd [=<
dir
>]
set
the working directory
-F, --no-fork
do
not fork before
exec
'ing <program>
-h, --help display this help and
exit
-V, --version output version information and
exit
实例如下:
[root@localhost ~]
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2faf24118766 192.168.1.23:5000
/tomcat7
"/bin/bash"
4 days ago Up 23 minutes 0.0.0.0:8888->8080
/tcp
tomcat
[root@localhost ~]
# docker inspect -f {{.State.Pid}} tomcat
31356
[root@localhost ~]
# nsenter --target 31356 --mount --uts --ipc --net --pid
[root@2faf24118766 /]
# exit //退出当前窗口,容器不会停止。
logout
[root@localhost ~]
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2faf24118766 192.168.1.23:5000
/tomcat7
"/bin/bash"
4 days ago Up 27 minutes 0.0.0.0:8888->8080
/tcp
tomcat
或者:
[root@localhost ~]
# nsenter -m -u -n -i -p -t 31356 bash
[root@2faf24118766 /]
#
[root@localhost ~]
# nsenter -m -u -n -i -p -t 31356 uptime
10:17:08 up 164 days, 2:50, 0
users
, load average: 0.00, 0.01, 0.05
[root@localhost ~]
# nsenter -m -u -n -i -p -t 31356 free -m
total used
free
shared buff
/cache
available
Mem: 65759080 591904 58142584 419724 7024592 64301784
Swap: 2097148 0 2097148