kubernetes services: NodePort type usage

2 min read | by Jordi Prats

To be able to expose a given Service externally, we can use NodePort as a quick-and-dirty way of achieving it. NodePort Services use a port on each Node to expose the Service outside of the cluster network

Using a Service of type NodePort is as easy of changing an existing service type to NodePort. For instance, for an existing ClusterIP service we can change the type on the spec section to NodePort:

apiVersion: v1
kind: Service
metadata:
  labels:
    app: demo
  name: demo
  namespace: default
spec:
  ports:
  - name: web
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: demo
  type: NodePort

Getting the list of services we will be able to see that the type have changed and on the PORT(S) column we will be able to see the exposed port, on the following example it is 30431:

$ kubectl get svc demo
NAME   TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
demo   NodePort   10.100.20.98   <none>        80:30431/TCP   2d1h

This port can also set to a specific port using nodePort on the spec.ports section:

spec:
  ports:
  - name: http
    nodePort: 31070
    port: 9000
    protocol: TCP
    targetPort: 9000

This port must be withing a given range, by default this range is: 30000-32767 so be advised that you can't set it to port 80 by default.


Posted on 02/03/2021