
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
metadata:
name: nginx-pod
labels:
app: myapp
spec:
containers:
- 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
metadata:
name: my-nginx-service
spec:
type: NodePort
selector:
app: myapp
ports:
- 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 10.96.0.1 <none> 443/TCP 47d
my-backend-service ClusterIP 10.101.205.61 <none> 80/TCP 30d
my-nginx-service NodePort 10.99.63.77 <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.