宿主机的命令在容器中使用

现在很多软用已经打包好镜像,但是很常见的命令都可能没有。出问题了,有时候排查起来很困难。这里介绍一种使用宿主机的命令在容器中使用。容器运行相当于宿主机的进程。在主机找到容器的pid,然后进入该命名空间。就可以使用宿主机的命名空间。

创建测试容器

$ kubectl run nginx01 --image=nginx

$ kubectl run nginx01 --image=nginx

$ kubectl get pod -owide
NAME      READY   STATUS    RESTARTS   AGE   IP            NODE         NOMINATED NODE   READINESS GATES
nginx01   1/1     Running   0          61s   20.0.40.195   k8s-node03   <none>           <none>
nginx02   1/1     Running   0          51s   20.0.30.2     k8s-node02   <none>           <none>

测试两个容器的连通性

$ kubectl exec nginx01 -- ping 20.0.30.2
OCI runtime exec failed: exec failed: container_linux.go:349: starting container process caused "exec: "ping": executable file not found in $PATH": unknown
command terminated with exit code 126

容器使用宿主机命令

找到对应的容器id

$ docker ps | grep nginx01
2449c734f760        nginx                       "/docker-entrypoint.…"   3 minutes ago       Up 3 minutes                            k8s_nginx01_nginx01_default_02cdc367-77ce-4107-b4f0-abb72059d30a_0
90c7eeec7393        ecloudedu/pause-amd64:3.0   "/pause"                 4 minutes ago       Up 4 minutes                            k8s_POD_nginx01_default_02cdc367-77ce-4107-b4f0-abb72059d30a_0

找容器的pid

$ docker inspect -f {{.State.Pid}} 2449c734f760
37336

进入容器的命名空间

nsenter -t 37336 -n

验证是否进入容器IP

$ ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1480
        inet 20.0.40.195  netmask 255.255.255.255  broadcast 20.0.40.195
        ether a2:6b:8b:ec:cb:71  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

验证ping命令

$ ping -c4 20.0.30.2
PING 20.0.30.2 (20.0.30.2) 56(84) bytes of data.
64 bytes from 20.0.30.2: icmp_seq=1 ttl=62 time=2.43 ms
64 bytes from 20.0.30.2: icmp_seq=2 ttl=62 time=0.406 ms
64 bytes from 20.0.30.2: icmp_seq=3 ttl=62 time=0.479 ms
64 bytes from 20.0.30.2: icmp_seq=4 ttl=62 time=0.384 ms

--- 20.0.30.2 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3002ms
rtt min/avg/max/mdev = 0.384/0.925/2.434/0.872 ms

简写版

# 确定哪个节点运行容器。
kubectl get pod -owide    

# 以下步骤在对应的节点执行。
NAME=nginx01
nsenter -t `docker ps | grep $NAME | grep -v "/pause" | awk '{print $1}' | xargs docker inspect -f {{.State.Pid}}` -n
ifconfig eth0
exit
原文地址:https://www.cnblogs.com/mycloudedu/p/15079409.html