Kubernetes: Service : NodePort

Kubernetes

The NodePort is one of the three services in Kubernetes.

When a pod is deployed with a container, the worker node in which the pod gets deployed has an IP accessible from the master node, etc and the pod also has a private IP that can be accessed once you are inside the worker node.

If the pod hosts a container that runs httpd, the site can be accessed from within the worker node, by default via the pod’s private IP, but not from anywhere outside the worker node. This is were one of the “service” by Kubernetes comes to play.

The Kubernetes service that connects the pod’s port, which may be TCP 80 to a newly assigned TCP port of 30008 of the worker is the NodePort service. We are talking about 3 ports here:

Node Port: The port of the worker node. This has to be within the range of 30,000 to 32,767

Pod Port: The port used by the Pod

Port: The port in the “service” that connects to Pod Port.

As every pod got an IP, every service too have an IP.

WorkerNode with IP 192.168.146.130 (listening tcp/30001) –> Service with IP 10.98.33.154 (connecting port tcp/80) –> Pod with IP 172.16.135.84 (listening to port 80)

Below is a configuration file for the service.

[root@kubmaster01 ~]# cat mynodeport.yml

===== ===
apiVersion: v1
kind: Service
metadata:
    name: mynodeportservice
spec:
    type: NodePort
    ports:
        – targetPort: 80
           port: 80
          nodePort: 30001
    selector:
        theApp: sv1

===== ===

Now create a pod named “mypod” using a manifest file in yaml format and deploy the pod. Ensure there is a label attached to the pod that reads “theApp: sv1“. The image can be httpd.

[root@kubmaster01 ~]# kubectl create -f mynodeport.yml

This will spin-up a “service” and work with any running pod were the label is “theApp: sv1“.

The below command from your laptop, or even from the master node should display the default webpage hosted by mypod.

  • httpd://192.168.146.130:30001