kindのNodePortにアクセスできない問題の解決方法

発生した問題

Kubernetes学習のため Using a Service to Expose Your App | Kubernetes に取り組んでいたところ、kubectl exposeしたNodePortにアクセスできなかった。

$ kubectl expose deployment/kubernetes-bootcamp --type="NodePort" --port 8080
service/kubernetes-bootcamp exposed

$ kubectl describe services/kubernetes-bootcamp
Name:                     kubernetes-bootcamp
Namespace:                default
Labels:                   app=kubernetes-bootcamp
Annotations:              <none>
Selector:                 app=kubernetes-bootcamp
Type:                     NodePort
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.96.171.15
IPs:                      10.96.171.15
Port:                     <unset>  8080/TCP
TargetPort:               8080/TCP
NodePort:                 <unset>  30519/TCP
Endpoints:                10.244.0.8:8080
Session Affinity:         None
External Traffic Policy:  Cluster
Internal Traffic Policy:  Cluster
Events:                   <none>

$ export NODE_PORT="$(kubectl get services/kubernetes-bootcamp -o go-template='{{(index .spec.ports 0).nodePort}}')"
echo "NODE_PORT=$NODE_PORT"
NODE_PORT=30519

$ curl http://"localhost:$NODE_PORT"
curl: (7) Failed to connect to localhost:30519 after 0 ms: Could not connect to server

解決策

kubectl get nodes -o wide でNodeのIPアドレスが INTERNAL-IP 列に出るので、そのIPアドレスとNodePortにアクセスできる。

$ kubectl get nodes -o wide
NAME                 STATUS   ROLES           AGE   VERSION   INTERNAL-IP     EXTERNAL-IP   OS-IMAGE                       KERNEL-VERSION           CONTAINER-RUNTIME
kind-control-plane   Ready    control-plane   41m   v1.37.0   192.168.208.2   <none>        Debian GNU/Linux 13 (trixie)   7.2.11-arch1-1 (amd64)   containerd://2.3.4

$ curl 192.168.208.2:30519
Hello Kubernetes bootcamp! | Running on: kubernetes-bootcamp-5cc66bcc9b-7vc7d | v=1