Kubernetes Services -2 NodePort

NodePort is a type of Service that exposes a pod (or set of pods) to external traffic by opening a specific port on each node in the cluster.

So, NodePort Service works the same as a Cluster IP but also provides the additional feature of external access.
Cluster IP is used for internal communication.

apiVersion: v1
kind: Service
metadata:
  name: my-service-nodeport
spec:
  type: NodePort
  selector:
    tier: frontend
  ports:
    - port: 80 # Port where service is listening 
      targetPort: 80 # Port where endpoint(pod) is listening 
      nodePort: 30007 # Port where nodes are listening. # will allocate a port from a range (default: 30000-32767)

If you see the manifest/yaml file of the service, you can see 3 ports:

  1. port : The service will listen on this port.

  2. targetPort: This is the target port on which endpoint pod is listening

  3. nodePort: This is the port exposed on each node which will redirect the traffic to the service. If value is not provided, will allocate a port from a range (default: 30000-32767).

For the practical, we created one frontend-pod (nginx-frontend) & 2 backend pods( nginx-backend & nginx-backend2). All these pods are running on node01.

We created the NodePort service named my-service-nodeport using the manifest provided above.
The selector label is already applied to the pods, allowing the service to use the backend pods as its endpoints.

So, here's how the flow works:

Internally:
When we try to access port 80 of the service, it redirects traffic to the backend pods.

Externally :

As I am performing this in killercode practice env, I don’t have these external IPs of the nodes

But i am using functionality provided by the console which allow me to access some ports on the host without giving me actual IP

For Host 1 : I am trying to access NodePort 30007

at first it redirected traffic to backend pod1

When I refreshed the page multiple times, it redirected traffic to pod 2 as well.

Similarly for Host 2:

So, the basic traffic flow looks like this: