<p>I have create a pod with the below yaml definition.</p>

<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: praveensripati/docker-demo:1.2
    ports:
    - containerPort: 3000
</code></pre>

<p>And now I expose the pod, which creates a service.</p>

<pre><code>kubectl expose pod myapp-pod --type=NodePort
</code></pre>

<p>The port 3000 on the container is exposed to port 31728 on the nodes. And I am able to do access the page using curl on port 31728.</p>

<pre><code>kubectl get service myapp-pod
NAME        TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
myapp-pod   NodePort   10.107.254.254   &lt;none&gt;        3000:31728/TCP   5s
</code></pre>

<p>This time I wanted to expose the service not a random port, but on port 80. And so I specify the port number as 80, by using --port. The service details are a bit odd. It says that port 80 on the container is exposed to port 31316 on the nodes. Also, I am able to access the page using curl on the random port (31316 in this case) and not port 80.</p>

<pre><code>kubectl expose pod myapp-pod --type=NodePort --target-port=3000 --port=80

kubectl get service myapp-pod
NAME        TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
myapp-pod   NodePort   10.105.123.73   &lt;none&gt;        80:31316/TCP   12s
</code></pre>

<p>I am not able to expose a service on a specific port and not on a random port. I tried a few combinations and read the k8s documentation, but no success.</p>

<p>How do I expose a service on a specific port instead of a random port?</p>

<p>Your question is about exposing the NodePort type of service on a specific port. For that you need to specify the <code>nodePort</code> field under <code>ports</code> in your service definition.</p>

<pre><code>kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: myapp
  ports:
  - protocol: TCP
    port: 3000
    nodePort: 32321
  type: NodePort
</code></pre>

<p>Note that it has to be within a given range provided in the configs. Which defaults to <code>30000-32767</code>. This range can be specified in the <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/" rel="noreferrer">kube-apiserver</a> configs using the <code>--service-node-port-range</code> option.</p>
