Search code examples
servicekubernetes

How to expose a Kubernetes service on a specific Nodeport?


I have create a pod with the below yaml definition.

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

And now I expose the pod, which creates a service.

kubectl expose pod myapp-pod --type=NodePort

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.

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

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.

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   <none>        80:31316/TCP   12s

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.

How do I expose a service on a specific port instead of a random port?


Solution

  • I will try to answer your query here.

    Also, I am able to access the page using curl on the random port (31316 in this case) and not port 80.

    -- Because, kubernetes exposed the port 31316 on the host (maps to the service) and hence it can be accessed on host:31316.

    -- Service port is visible only within the kubernetes cluster. You can exec into a pod container and do a curl on servicename:service port instead of the NodePort.
    

    Note the terms - container port: the port container listens on. Service port: the port where kubernetes service is exposed on cluster internal ip and mapped to the container port. Nodeport: the port exposed on the host and mapped to kubernetes service.