How to patch specific port of Kubernetes service?

1/19/2022

I have Kubernetes service with two ports, something like this:

apiVersion: v1
kind: Service
metadata:
name: application-service
...
spec:
    ports:
        - name: main
          nodePort: 32766
          port: 8010
          protocol: TCP
          targetPort: 8010
        - name: healthcheck
          nodePort: 32002
          port: 8080
          protocol: TCP
          targetPort: 8080

I'd like to change the 'port' value of the port with name 'healthcheck'. I am able to do it with such command:

kubectl patch svc application-service --type='json' -p='[{"op": "replace", "path": "/spec/ports/1/port", "value": 8020}]'

where 1 is the order of my 'healthcheck' port in the ports array, but I'd like to use the port name ('healthcheck') for selecting the right one. How could I do that?

And I need to use kubectl patch as we already use it for service modification (through Kubernetes Java client) and I'd like try to extend this functionality with port modification I described.

-- Hleb Kastseika
kubectl
kubernetes
kubernetes-service

0 Answers