0

I have a service which is accessible on 8081. If I do via docker-compose or swarm without any specific changing on port it's work.

 http://$(minikube ip):8081

but when i run my app via Kubernetes(minikube) is assign a nodePort in range of 30000-32767. Then i have to call as follow:

http://$(minikube ip):30546

which is not acceptable from my service. Is there any way to map randomly given port to my own defined port? When call second url then i am getting connection refused I also used

kubectl port forward my-service 8081

but still no success.

  • 1
    This may be duplicate https://stackoverflow.com/questions/43935502/kubernetes-nodeport-custom-port/57623930#57623930 – Sachin Arote Oct 01 '19 at 11:49
  • You are using wrong command to forward the port. You need to use ```kubectl port-forward svc/my-service 8081:8081``` – Sachin Arote Oct 01 '19 at 11:56
  • Possible duplicate of [Kubernetes NodePort Custom Port](https://stackoverflow.com/questions/43935502/kubernetes-nodeport-custom-port) – Black_Bacardi Oct 07 '19 at 11:34

2 Answers2

1

kubectl port-forward command is incorrect. try below one

kubectl port-forward svc/my-service 8081:8081

then you should be able to access the service at http//:127.0.0.1:8081

P Ekambaram
  • 15,499
  • 7
  • 34
  • 59
  • There is no kubectl port forward. Only able to to kubectl port-forward. are u sure? @P –  Oct 01 '19 at 10:09
0

This answer is not specific to Minikube but applicable to any Kubernetes cluster running inside a docker container.

In order to send a request from the host machine to the Kubernetes pod running in a container, you have to map ports from host machine to all the way to the pod.

Here is how you do it:

  1. Publish the NodePort you want to use inside container to the host machine using --publish or -p.
# Map port 8080 on host machine to 31080 inside the container
docker run -p 8080:31080 ...
  1. Use a custom NodePort when creating the service:
# You need to specify the exposed port as the nodePort value
# Otherwise Kubernetes will generate a random nodePort for you 
kubectl create service nodeport myservice --node-port=31080 --tcp=3000:80

The application inside the pod listens to port 80 which is exposed as a service at port 3000. The traffic received at port 31080 on Kubernetes node will be directed at this service.

The query you send to 8080 on your host machine will follow this path:

Request -> Host Machine -> Docker Container -> Kubernetes Node -> Service -> Pod
               ↑                   ↑                 ↑              ↑         ↑
          localhost:8080         :31080           :31080          :3000      :80

References:

snnsnn
  • 10,486
  • 4
  • 39
  • 44