Song
Song

Reputation: 23

How to know which nodeport can be allocated from Kubernetes API Server?

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

Upvotes: 2

Views: 718

Answers (1)

Chris
Chris

Reputation: 5673

The Nodeport is chosen randomly between 30000-32767. You can set it in the service definition.

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

From the documentation: https://kubernetes.io/docs/concepts/services-networking/service/#nodeport

Update

The classes placed in the package kubernetes/pkg/registry/core/service/portallocator are 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.

Upvotes: 3

Related Questions