I want to figure out how does kubernetes knows which nodeport can be allocated when create a new service with nodeport type like this:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: NodePort
selector:
app: MyApp
ports:
- port: 80
targetPort: 80
I had search google and find these kubernetes soure code, but I don't understand how does it works. https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/allocator.go
The Nodeport is chosen randomly between 30000-32767. You can set it in the service definition.
From the documentation: https://kubernetes.io/docs/concepts/services-networking/service/#nodeport
Update
The classes placed in the package
kubernetes/pkg/registry/core/service/portallocatorare responsible for allocating a node port for a service.This test documents the behavior: https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/operation_test.go
Kubernetes just takes a random port and if that one isn't free it takes the next one.
If you can read go the other classes in that package are a good starting point to understand the behavior.