kubectl expose pods using selector as a NodePort service via command-line

10/28/2019

I have a requirement to expose pods using selector as a NodePort service from command-line. There can be one or more pods. And the service needs to include the pods dynamically as they come and go. For example,

NAMESPACE     NAME                                     READY   STATUS    RESTARTS   AGE
rakesh        rakesh-pod1                              1/1     Running   0          4d18h
rakesh        rakesh-pod2                              1/1     Running   0          4d18h

I can create a service that selects the pods I want using a service-definition yaml file -

apiVersion: v1
kind: Service
metadata:
  name: np-service
  namespace: rakesh
spec:
  type: NodePort
  ports:
    - name: port1
      port: 30005 
      targetPort: 30005
      nodePort: 30005 
  selector:
    abc.property: rakesh

However, I need to achieve the same via commandline. I tried the following -

kubectl -n rakesh expose pod --selector="abc.property: rakesh" --port=30005 --target-port=30005 --name=np-service --type=NodePort

and a few other variations without success.

Note: I understand that currently, there is no way to specify the node-port using command-line. A random port is allocated between 30000-32767. I am fine with that as I can patch it later to the required port.

Also note: These pods are not part of a deployment unfortunately. Otherwise, expose deployment might have worked.

So, it kind of boils down to selecting pods based on selector and exposing them as a service.

My kubernetes version: 1.12.5 upstream

My kubectl version: 1.12.5 upstream

-- Rakesh N
kubectl
kubernetes

2 Answers

10/29/2019

is there a reason why you are not using deployment or replicaset ?

-- Praveen
Source: StackOverflow

10/28/2019

You can do:

kubectl expose $(kubectl get po -l abc.property=rakesh -o name) --port 30005 --name np-service --type NodePort
-- suren
Source: StackOverflow