Kubernetes Pod 内の起動中の Container で iptables を確認したい

たまーにやりたいときがあるけど毎回忘れるのでメモ

やりたいこと

今回は Kubernetes Pod 内の起動中の Container で iptables を確認します。

対象のコンテナが iptables コマンドをもっていて securityContext. capabilitiesNET_ADMIN があれば kubectl exec [pod name] -- iptables で確認できます。iptables コマンドが入ってることはあるかもしれませんが NET_ADMIN は何か理由がないと付与しないと思うので実現するためには manifest の更新が必要になるため Pod が再起動されてしまいます。

これが Pod 内の任意のポートに対して tcpdump したいとかであれば tcpdump もっているイメージ (e.g. nicolaka/netshoot) を kubectl debug を使い実行中の Pod に対してエフェメラルコンテナを追加することで実現できます。しかし iptables に関しては netns に対して生成されるので各コンテナごとにみてあげる必要があるのでこの方法が使えない(はず)。

環境

手順

Node に入れることが前提となるが下記の方法で Pod 内の起動中の Container で iptables を確認することができます。

  1. 対象の Pod がある Node と ContainerID を取得します
    • Node は kubectl get po [pod name] -o jsonpath="{.spec.nodeName}"
    • ContainerID は kubectl get po [pod name] -o jsonpath="{.status.containerStatuses[*].containerID}"
      • format は containerd://[container id] となっています
  2. Node にログインする
  3. crictl inspect -o go-template --template "{{(index .info.pid)}}" [container id] で PID を取得する
    • crictl がない場合はこちらから入手できます
  4. nsenter コマンドに --net option をつけて iptables を実行します
    • e.g. nsenter -t [pid] --net iptables -L -t nat