Kubernetes Services - NodePort

Updated: Aug 14, 2020

In the last article we studied about ClusterIP service type which is useful only for testing purpose as it makes the service available locally and if we want to access it from outside, we have to do a port forward or use a kube-proxy. Next we are going to discuss another type of service which is NodePort which allows us to access service from outside.

Services in Kubernetes Enable communication within and outside application.Helps us connect application together with other applications or users. A service is like a virtual server inside the node and has its own IP address. Its called the Cluster IP of the service.

It helps communication between back-end and front-end pods. There are a number of types of services and here we will discuss about NodePort

NodePort : This type of service helps in mapping a port on the node to port on the pod. Has a range of 30000 - 32767

Port on the pod : Target port

Port on the Service : Port

If we do not provide a Target port, its assumed to be the same as Port and if we don't provide a NodePort, a random port number is automatically allotted.

To select a pod for which a service needs to be created, we use labels and selectors

If multiple pods serving the application is running on different nodes, then kubernetes creates a service that spans all nodes and maps the same nodePort on every node.

First we will create a pod with a label "app: myapp" and refer it in the selector of nodeport service.

apiVersion: v1
kind: Pod
   name: nginx-pod
     app: myapp
   - name: nginx-container
     image: nginx
## Execute kubectl create -f  nginx_pod.yaml 

Now we will create a service of the type NodePort as below. We will use the label of this pod to create the service.

[root@node1 kubernetes]# cat nodeport-service.yaml

kind: Service
apiVersion: v1
  name: my-nginx-service
  type: NodePort
    app: myapp
    - nodePort: 30008
      port: 80
      targetPort: 80

# Make sure that nginx-pod used for the service is running

Now we will use the kubectl command to create a service.

[root@node1 kubernetes]# kubectl create -f nodeport-service.yaml
[root@node1 kubernetes]# kubectl get svc
NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes           ClusterIP       <none>        443/TCP        47d
my-backend-service   ClusterIP   <none>        80/TCP         30d
my-nginx-service     NodePort     <none>        80:30008/TCP   7m41s

What this service does is that it forwards traffic from port number 80 of the port to port number 30008 of the node. We will see that we will now be able to access the webpage on

Once the service is started, we can just curl or go to the browser and open the cluster node IP on the nodePort

That is it for NodePort Service , in the next article we will read about LoadBalancer type of service.

230 views0 comments

Recent Posts

See All

Subscribe Form

©2020 by Linux Advise