How to expose a Kubernetes service on a specific Nodeport? How to expose a Kubernetes service on a specific Nodeport? kubernetes kubernetes

How to expose a Kubernetes service on a specific Nodeport?


Your question is about exposing the NodePort type of service on a specific port. For that you need to specify the nodePort field under ports in your service definition.

kind: ServiceapiVersion: v1metadata:  name: my-servicespec:  selector:    app: myapp  ports:  - protocol: TCP    port: 3000    nodePort: 32321  type: NodePort

Note that it has to be within a given range provided in the configs. Which defaults to 30000-32767. This range can be specified in the kube-apiserver configs using the --service-node-port-range option.


When an existing Dashboard service already exists, remove it.

kubectl delete service kubernetes-dashboard -n kube-system

Expose the Dashboard deployment as a NodePort.

kubectl expose deployment kubernetes-dashboard -n kube-system --type=NodePort

The above will assign a random port >= 30000. So use the Patch command to assign the port to a known, unused and desired port >= 30000.

kubectl patch service kubernetes-dashboard --namespace=kube-system --type='json' --patch='[{"op": "replace", "path": "/spec/ports/0/nodePort", "value":30000}]'

Caution: Never expose your dashboard publicly without authentication.


If your cluster does not have a LoadBalancer Provider, you can specify externalIPs in IP of nodes' network interface.

For example:

apiVersion: v1kind: Servicemetadata:  name: nginxspec:     type: ClusterIP  externalIPs:    - 125.100.99.101 # Node1-IP    - 125.100.99.102 # Node2-IP    - 192.168.55.112 # Node2-IP2  selector:    pod: nginx  ports:    - name: http      port: 80          - name: https      port: 443      

This will listen 80 and 443 on the specified node, and forward to the nginx service.