I'd like to specify port when using NodePort, but how can I know which port is available on all nodes, I don't want to port conflicts.
You could do netstat | grep <port>
.
If you set the type field to NodePort, the Kubernetes control plane will allocate a port from a range specified by --service-node-port-range flag (default: 30000-32767). Each node will proxy that port each (the same port number on every Node) into your Service.
You could get all services, grep node port and see what comes out.
$ kubectl get services --all-namespaces -o yaml |grep "nodePort:"|sort
nodePort: 30215
nodePort: 30274
nodePort: 30312
nodePort: 30342
nodePort: 30344
nodePort: 30386
nodePort: 30517
nodePort: 30738
nodePort: 30863
nodePort: 31063
nodePort: 31162
nodePort: 31445
Or pipe to jq with json output if you want a more elaborate listing with service names and so on.
Edit: the port range for node ports is normally 30000-32767 and should be reserved for Kubernetes use to avoid conflicts.
You can get all the services using
kubectl get svc --all-namespaces
Then you can grep
using the type.
There you can see all the assigned ports. It's basic piping and output filtering.
kubectl get svc --all-namespaces | grep ClusterIP | while read -r _ _ _ _ _ port _; do echo "$port" ; done
Right approach is to let Kubernetes choose the nodePort
automatically from the default allocated range(30000–32767). Don't include nodePort
in your yaml.