In Kubernetes, a NodePort is a service (Service) type that allows services to be accessed from outside the cluster. When a service of type NodePort is created, Kubernetes opens a static port (called a NodePort) on each node, and all traffic destined for that port is forwarded to the Pod on the backend of the service.
By default, Kubernetes assigns the NodePort service a range of ports from 30000 to 32767. this range is for the following reasons:
- Avoid conflicts: ports in this range are less likely to conflict with ports used by other services within the cluster.
- Conformity to standards: this range is typically used for registered ports, meaning that they can be assigned to users or user-level applications.
If you wish to use specific ports instead of letting Kubernetes assign them automatically, you can specify the port number via the --port and --target-port parameters when creating the Service. Example:
kubectl expose deployment/my-deployment --port=8080 --target-port=80 --type=NodePort
In this example, --port=8080 specifies the port on which the NodePort service listens on each node. If you do not specify --port, Kubernetes will automatically select an unused port from the default NodePort range.
If you need to modify the default NodePort range, you can start the API server by setting the --service-node-port-range flag. Example:
kube-apiserver --service-node-port-range=12000-22000
To summarize, set the NodePort range to 12000 to 22000. note that this setting needs to be configured at cluster startup and all API server instances must use the same range.
Once the custom NodePort range is set, Kubernetes will assign ports to the NodePort service within this range. If there are not enough ports available within this range, the operation to create the NodePort service will fail with a message that there are no ports available. Therefore, if you have many NodePort services, you may need to choose a larger range to avoid running out of ports.