<p>I want to figure out how does kubernetes knows which nodeport can be allocated when create a new service with nodeport type like this:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: MyApp
  ports:
    - port: 80
      targetPort: 80
</code></pre>
<p>I had search google and find these kubernetes soure code, but I don't understand how does it works.
<a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/allocator.go" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/allocator.go</a></p>

<p>The Nodeport is chosen randomly between 30000-32767. You can set it in the service definition.</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: MyApp
  ports:
      # By default and for convenience, the `targetPort` is set to the same value as the `port` field.
    - port: 80
      targetPort: 80
      # Optional field
      # By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
      nodePort: 30007
</code></pre>
<p>From the documentation: <a href="https://kubernetes.io/docs/concepts/services-networking/service/#nodeport" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/services-networking/service/#nodeport</a></p>
<p><strong>Update</strong></p>
<p>The classes placed in the package <code>kubernetes/pkg/registry/core/service/portallocator</code> are responsible for allocating a node port for a service.</p>
<p>This test documents the behavior: <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/operation_test.go" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/blob/master/pkg/registry/core/service/portallocator/operation_test.go</a></p>
<p>Kubernetes just takes a random port and if that one isn't free it takes the next one.</p>
<p>If you can read go the other classes in that package are a good starting point to understand the behavior.</p>
