Kubernetes local cluster Pod hostPort - application not accessible

6/19/2020

I am trying to access a web api deployed into my local Kubernetes cluster running on my laptop (Docker -> Settings -> Enable Kubernetes). The below is my Pod Spec YAML.

kind: Pod
apiVersion: v1
metadata:
  name: test-api
  labels:
    app: test-api
spec:
  containers:
  - name: testapicontainer
    image: myprivaterepo/testapi:latest
    ports:
    - name: web
      hostPort: 55555
      containerPort: 80      
      protocol: TCP

kubectl get pods shows the test-api running. However, when I try to connect to it using http://localhost:55555/testapi/index from my laptop, I do not get a response. But, I can access the application from a container in a different pod within the cluster (I did a kubectl exec -it to a different container), using the URL

http://*test-api pod cluster IP*/testapi/index

. Why cannot I access the application using the localhost:hostport URL?

-- Thomas
kubernetes
kubernetes-networking
kubernetes-pod

1 Answer

6/19/2020

I'd say that this is strongly not recommended. According to k8s docs: https://kubernetes.io/docs/concepts/configuration/overview/#services

Don't specify a hostPort for a Pod unless it is absolutely necessary. When you bind a Pod to a hostPort, it limits the number of places the Pod can be scheduled, because each <hostIP, hostPort, protocol> combination must be unique. If you don't specify the hostIP and protocol explicitly, Kubernetes will use 0.0.0.0 as the default hostIP and TCP as the default protocol.

If you only need access to the port for debugging purposes, you can use the apiserver proxy or kubectl port-forward.

If you explicitly need to expose a Pod's port on the node, consider using a NodePort Service before resorting to hostPort.

So... Is the hostPort really necessary on your case? Or a NodePort Service would solve it?

If it is really necessary , then you could try using the IP that is returning from the command:

kubectl get nodes -o wide

http://ip-from-the-command:55555/testapi/index

Also, another test that may help your troubleshoot is checking if your app is accessible on the Pod IP.

UPDATE

I've done some tests locally and understood better what the documentation is trying to explain. Let me go through my test:

  • First I've created a Pod with hostPort: 55555, I've done that with a simple nginx.
  • Then I've listed my Pods and saw that this one was running on one of my specific Nodes.
  • Afterwards I've tried to access the Pod in the port 55555 through my master node IP and other node IP without success, but when trying to access through the Node IP where this Pod was actually running, it worked.

So, the "issue" (and actually that's why this approach is not recommended), is that the Pod is accessible only through that specific Node IP. If it restarts and start in a different Node, the IP will also change.

-- Juliano Costa
Source: StackOverflow