问题

在项目中遇到了一些网络问题,想要在容器中抓一些包,但发现容器没有tcpdump命令,如果直接安装的话比较麻烦。

namespace资源隔离

Linux 命名空间对全局操作系统资源进行了抽象,对于命名空间内的进程来说,他们拥有独立的资源实例,在命名空间内部的进程可以实现资源可见。对于命名空间外部的进程,则不可见,实现了资源的隔离。这种技术广泛的应用于容器技术里。

列举下几个方面的资源隔离

namespace隔离内容
UTS主机名与域名
IPC信号量、消息队列和共享内存
PID进程号
Network网络设备、网络栈、端口等
Mount挂载点(文件系统)
User用户和用户组

容器进程隔离

当启动一个容器时,在主机上看其实只是起了一个进程,而在容器内部,只能看到自己内部的进程。这就是进程隔离了。
找到容器在主机上的进程id(注意不是容器id):

[root@test ~]# docker inspect --format "{{ .State.Pid }}" 58bef8a847ef
57805

58bef8a847ef 为容器id。
上面命令返回的结果就是容器在主机上的进程id了

[root@test ~]# ps -ef | grep 57805
root       57805   57785  0 May06 ?        00:00:20 /usr/local/bin/archer

nsenter 进入namespace

nsenter 在指定的namespace下运行你想要执行的命令。
介绍下nsenter几个重要的参数:

   -m, --mount[=file]
          Enter the mount namespace.  
          If no file is specified, enter the mount namespace of the target process. 
          If file is specified, enter the mount namespace specified by file.

   -u, --uts[=file]
          Enter the UTS namespace.  
          If no file is specified,  enter  the  UTS  namespace  of  the  target process.  
          If file is specified, enter the UTS namespace specified by file.

   -i, --ipc[=file]
          Enter the IPC namespace.  
           If  no  file  is specified, enter the IPC namespace of the target process. 
          If file is specified, enter the IPC namespace specified by file.

   -n, --net[=file]
          Enter the network namespace.  
          If no file is specified, enter the network namespace of the  target process. 
          If file is specified, enter the network namespace specified by file.

   -p, --pid[=file]
          Enter  the  PID  namespace.   
          If  no  file  is specified, enter the PID namespace of the target process.  
          If file is specified, enter the PID namespace specified by file.

   -U, --user[=file]
          Enter the user namespace.  
          If no file is specified, enter the  user  namespace  of  the  target process.   
          If  file  is  specified,  enter  the user namespace specified by file.  
          See also the --setuid and --setgid options.

抓包

虽然容器内没有tcpdump命令,但是我们是在宿主机上执行命令来抓取容器内的包,只要宿主机有相应的命令就能够抓取。
抓包命令:

nsenter -n -t 57805 tcpdump -i eth0 -vnn dst port 80

通过nsenter命令,就不需要担心容器里缺少命令工具了,只要宿主机上有相应的命令,就能使用,比如:

[root@test ~]# nsenter -n -t 57805 telnet 192.168.51.206 80
Trying 192.168.51.206...
Connected to 192.168.51.206.
Escape character is '^]'.
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐