Services running in Kubernetes are not exposed to the public by default so, no one can access them from outside.To access services running in K8s that are not exposed publicly we have few ways which are secure and will not bring to opening security holes in our systems and services. One of them is the Ingress Controller or API Gateway that most of the service meshes are using which basically mapping domains and subdomains to the services.
Another option is Kubernetes CLI (kubectl)using which you can bind any services or POD/container port to your localhost and access private service from your localhost.
Letβs assume we have a service called customer-dashboard and we want to access it using Kubernetes CLI (kubectl).
Connecting to Pod
If we want to connect to Pod/Container we should know the exact name of the Pod, for that we can run this command:
kubectl get pod | grep customer-dashboard
the output would be something similar:
customer-dashboard-7945c779f4-27c5k 1/1 Running 0 4d
customer-dashboard-7945c779f4-885h9 1/1 Running 0 4d
Now when you know the pod name you can bind pods specific port to your localhost using this command:
kubectl port-forward pod/customer-dashboard-7945c779f4-27c5k 8080:80
You will see this output:
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80
So first port is the port to which you want to bind the service in localhost (so you can access it using 127.0.0.1:8080 or localhost:8080), second port is the pod/container port number.
If you need to open few ports you can do the same for another port too, for that you need to open new terminal tab and type kubectl port-forward customer-dashboard-7945c779f4β27c5k 8081:81 to bind 81 port as well to your 8081 on localhost.
Connecting to Service
Connecting to Service (or internal K8s load balancer) is almost same as connecting to the pod but in this case you will need the service name instead of Pod name. To get the service name type:
kubectl get service | grep customer-dashboard
and you will get the service names:
customer-dashboard ClusterIP 10.24.2.124 <none> 80/TCP,81/TCP
To bind it to your localhost type:
kubectl port-forward service/customer-dashboard 8080:80
You will see this output:
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80
Like to learn?
Follow me on twitter where I post all about the latest and greatest AI, DevOps, VR/AR, Technology, and Science! Connect with me on LinkedIn too!
Top comments (1)
Nice.