Kubernetes : What is hostPort and hostIp used for?

Viewed 20368

I try to understand hostIP and hostPort in Kubernetes.

Here is my cluster configuration :

3 vagrant nodes :

nodes = [
  { :hostname => 'k8s-master', :ip => '192.168.150.200', :ram => 4096 },
  { :hostname => 'k8s-minion1', :ip => '192.168.150.201', :ram => 4096 },
  { :hostname => 'k8s-minion2', :ip => '192.168.150.202', :ram => 4096 },
]

I write the following manifest to test it :

apiVersion: v1
kind: Pod
metadata:
  name: firstpod
spec:
  containers:
  - name: container
    image: nginx
    ports:
    - containerPort: 80
      hostIP: 10.0.0.1
      hostPort: 8080

I deploy with kubectl apply -f port.yml The pod runs on k8s-minion2

kubectl get pods -o wide gives :
NAME       READY     STATUS    RESTARTS   AGE       IP          NODE
firstpod   1/1       Running   0          2m        10.38.0.3   k8s-minion2

I can curl the ngnix from inside the cluster as follows:

#ssh inside the cluster
    vagrant ssh k8s-master
#curl the containerPort on the pod ip
    curl 10.38.0.3:80

But, I have no idea how to use hostIp and hostPort. curl 10.0.0.1:8080 gives :

curl: (7) Failed to connect to 10.0.0.1 port 80: Connection timed out

and curling the node or the cluster Ip gives :

curl: (7) Failed to connect to 10.38.0.3 port 8080: Connection refused

So where is port 8080 open and what does hostIp intended for?

Thanks

2 Answers

If you take a look at the kubernetes API reference you'll find that hostIP is IP that is being assigned once the pod is scheduled into node.

hostIP (string) - IP address of the host to which the pod is assigned. Empty if not yet scheduled.

This can be further exposed as env inside the pod if needed (spec.hostIP)

With hostPort you can expose container port to the external network at the address <hostIP>:<hostPort>, where the hostIP is the IP address of the Kubernetes node where the container is running and the hostPort is the port requested by the user. You can read more about here.

If you want to reach your pod there are also other ways to do that, such as ClusterIP or NodePort depending if the request comes internally or externally. This article goes thru them and their differences.

ClusterIP (10.38.0.3) will only be accessed from within the cluster. To hit the service from outside the cluster, try nodeIP:port 192.168.150.202:8080

NodePort Service type allows us to expose our services on each Node’s IP at a static port. Therefore, it allows accessing the service from outside the cluster.

Related