<p>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,</p>

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

<p>I can create a service that selects the pods I want using a service-definition yaml file - </p>

<pre><code>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
</code></pre>

<p>However, I need to achieve the same via commandline. I tried the following - </p>

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

<p>and a few other variations without success.</p>

<p><em>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.</em></p>

<p><em>Also note: These pods are not part of a deployment unfortunately. Otherwise, <code>expose deployment</code> might have worked.</em></p>

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

<p>My <code>kubernetes</code> version: 1.12.5 upstream</p>

<p>My <code>kubectl</code> version: 1.12.5 upstream</p>

<p>You can do:</p>

<pre><code>kubectl expose $(kubectl get po -l abc.property=rakesh -o name) --port 30005 --name np-service --type NodePort
</code></pre>
