介绍
nsenter是用来进入容器内部的一个命令,它的优势之处在于可以自己选择加载容器的那些namespaces。
说直白一点就是 排查docker容器可以具备inux宿主命令的的方法。
一典型的用途容器网络命令空间。容器为了轻量级,不包含基础的命令,如说 ip address,ping,telnet,ss,tcpdump 等,给调试容器网络带来很大困扰:只能通过 docker inspect ContainerID 获取容器IP,无法测试和其他网络的连通性。这时使用nsenter命令仅进入该容器的网络命名空间,使用宿主机的命令调试容器网络。nsenter也可以进入 mnt, uts, ipc, pid, user 命令空间,指定根目录和工作目录。
namespace是Linux中一些进程的属性的作用域,使用命名空间,可以隔离不同的进程。
1、nsenter的安装
yum install util-linux -y
2、nsenter的使用
[root@localhost ~]# nsenter --help
用法:
nsenter [options] <program> [<argument>...]
Run a program with namespaces of other processes.
选项:
-t, --target <pid> 要获取名字空间的目标进程
-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 执行 <程序> 前不 fork
-Z, --follow-context set SELinux context according to --target PID
-h, --help 显示此帮助并退出
-V, --version 输出版本信息并退出
中文说明
--mount参数是进去到mount namespace中
--uts参数是进入到uts namespace中
--ipc参数是进入到System V IPC namaspace中
--net参数是进入到network namespace中
--pid参数是进入到pid namespace中
--user参数是进入到user namespace中
nsenter命令要获取到docker容器的进程,然后再使用nsenter工具进去到docker容器中
# docker inspect -f {{.State.Pid}} 容器名或者容器id #查询容器的PID
# nsenter -t 容器PID(容器名) -m -u -i -n -p #输入该命令进入容器
示例:
# 起一个Nginx镜像
[root@localhost ~]# docker run -p 80:80 -d --name nginx nginx
# 查看pid
[root@localhost ~]# docker inspect -f {{.State.Pid}} nginx
4552
3、说明
进入容器,使用宿主机的namespace进行排错,就可以排错linux宿主机一样进行容器排错了。