Kubernetes NodePort Custom Port
Asked Answered
C

5

37

Is there way to specify a custom NodePort port in a kubernetes service YAML definition? I need to be able to define the port explicitly in my configuration file.

Connate answered 12/5, 2017 at 10:28 Comment(0)
C
60

You can set the type NodePort in your Service Deployment. Note that there is a Node Port Range configured for your API server with the option --service-node-port-range (by default 30000-32767). You can also specify a port in that range specifically by setting the nodePort attribute under the Port object, or the system will chose a port in that range for you.

So a Service example with specified NodePort would look like this:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    name: nginx
spec:
  type: NodePort
  ports:
    - port: 80
      nodePort: 30080
      name: http
    - port: 443
      nodePort: 30443
      name: https
  selector:
    name: nginx

For more information on NodePort, see this doc. For configuring API Server Node Port range please see this.

Contortionist answered 12/5, 2017 at 18:30 Comment(3)
Hi, is it a bad practice to specify a fixed nodeport?Andi
@Andi I would say that depends on your architecture. If your scenario is somewhat simple and you use cluster external load balancing and gateways it would not be uncommon to work with fixed nodeports. However, it can get hard to manage with complex deployments and they become a scarce resource/source of conflict. Additionally if your security setup requires cluster internal rules, Nodeports may allow bypassing those and give you additional headaches.Contortionist
Thanks for your reply (after 2years) :)Andi
P
5

You can define static NodePort using nodeport in service.yaml file

spec:
  type: NodePort
  ports:
    - port: 3000
      nodePort: 31001
      name: http

Phloem answered 23/8, 2019 at 9:59 Comment(0)
E
5

Yeah you can define all those three port by your own

apiVersion: v1
kind: Service
metadata:
  name: posts-srv
spec:
  type: NodePort
  selector:
    app: posts
  ports:
    - name: posts
      protocol: TCP
      port: 4000
      targetPort: 4000
      nodePort: 31515

Euthenics answered 8/3, 2021 at 16:32 Comment(0)
O
2

you can actually run this command to see how you can achieve that in yaml.

kubectl create service hello-svc --tcp=80:80 --type NodePort --node-port 30080 -o yaml --dry-run > hello-svc.yaml

https://pachehra.blogspot.com/2019/11/kubernetes-imperative-commands-with.html

Omnivorous answered 23/7, 2020 at 6:9 Comment(0)
J
1

For those who need to use kubectl commands without creating a yaml file, you can create a NodePort service with a specified port:

kubectl create nodeport NAME [--tcp=port:targetPort] [--dry-run=server|client|none]

For example:

kubectl create service nodeport myservice --node-port=31000 --tcp=3000:80

You can check Kubectl reference for more:

Joella answered 8/10, 2021 at 5:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.