<p>I need to create Kubernetes services that their nodePort are auto-allocated by K8S, and port/targetPort must equal to nodePort. (The requirement comes from the spec of a spark YARN node as the backend of the services).
Maybe I can first create the service with a fixed dummy port/targetPort and an auto-allocated nodePort, then update the service to set port/targetPort to the same value as the nodePort.
But is there any better way of doing this?</p>

Jarod
<p>There are two main ways to expose a resource on k8s</p>
<p>First one using <code>kubectl expose</code> command: using this one you can choose the pod/deploy to expose but not the nodePort value. Then as you already know you must set the nodeport value on the created yaml</p>
<p>Another way to expose is using <code>kubectl create service nodeport</code> command: using this one you can set the port, target port and nodeport.</p>
<p>If you know the label of the pod to expose (for example <code>app: superPod</code> ) you can create a file, then replace a label (for example <code>TOREPLACE</code>)
with the value of your choosen port (for example 30456):</p>
<p>On linux:</p>
<pre class="lang-bash prettyprint-override"><code>portValue=30456 &amp;&amp; k create service nodeport TOREPLACE \
--node-port=$portValue --tcp=$portValue --dry-run=client -oyaml &gt; file.yaml \
&amp;&amp; sed -i 's/app: TOREPLACE/app: yourselector/g' file.yaml \
&amp;&amp; sed -i 's/name: TOREPLACE/name: yourselector-name/g' file.yaml
</code></pre>
<p>This will creates the file with preferred values.</p>
<p>After that, you can apply the file using <code>kubectl -f file.yaml apply</code></p>
<p>However, depending on your needs, and if you want a reliable customizations of your resources, you could try to use:</p>
<p><a href="https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/</a>
or
<a href="https://helm.sh/docs/" rel="nofollow noreferrer">https://helm.sh/docs/</a></p>
<p>Hope it helps.</p>
