💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] 现在很多软用已经打包好镜像,但是很常见的命令都可能没有。出问题了,有时候排查起来很困难。这里介绍一种使用宿主机的命令在容器中使用。容器运行相当于宿主机的进程。在主机找到容器的pid,然后进入该命名空间。就可以使用宿主机的命名空间。 这里演示一个nginx容器 ## 前提 1. 容器启动清单 ```yaml apiVersion: v1 kind: Pod metadata: name: nginx labels: app: nginx spec: containers: - name: nginx image: nginx:1.21.4 imagePullPolicy: IfNotPresent ports: - name: http protocol: TCP containerPort: 80 ``` 2. 启动nginx容器 ```shell $ kubectl apply -f nginx.yml pod/nginx created ``` 3. 测试是否有ping命令 ```shell $ kubectl exec -it nginx -- ping www.baidu.com 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 ``` ## 进入容器Pid 4. 获取容器Pid ```shell # 容器ID docker ps | grep nginx | grep -v pause | awk '{print $1}' f807acc55709 # 查看容器Pid docker inspect -f {{.State.Pid}} f807acc55709 ``` > 需要在容器所在节点执行,可通过 `kubectl get pod -n <namespace> -owide` 来确认在哪个节点执行命令 5. 进入容器Pid ```shell $ nsenter -t 102944 -n ``` ## 测试 6. 测试 ```shell $ ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000 link/ipip 0.0.0.0 brd 0.0.0.0 4: eth0@if11: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1480 qdisc noqueue state UP group default link/ether 1a:96:85:57:76:0c brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 20.0.32.189/32 brd 20.0.32.189 scope global eth0 valid_lft forever preferred_lft forever $ ping -c4 www.baidu.com PING www.a.shifen.com (14.215.177.38) 56(84) bytes of data. 64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=1 ttl=127 time=5.20 ms 64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=2 ttl=127 time=5.20 ms 64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=3 ttl=127 time=5.06 ms 64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=4 ttl=127 time=5.21 ms --- www.a.shifen.com ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 3005ms rtt min/avg/max/mdev = 5.066/5.169/5.212/0.093 ms $ exit ``` > 注意: > **测试前**:要确认是否进入容器,可以通过查看IP地址来确定,但是有些容器IP就是宿主机IP地址。 > **测试完**:记得退出容器的命名空间。 ## 简洁版 ```shell # 确定哪个节点运行容器。 kubectl get pod -owide # 在对应的节点执行。 NAME=nginx nsenter -t `docker ps | grep $NAME | grep -v "pause" | awk '{print $1}' | xargs docker inspect -f {{.State.Pid}}` -n ```