In this article, I will show you how to access Kubernetes Cluster Metrics using Port Forwarding. If you want to directly communicate from your local system to a given port on a Pod then Port Forwarding is the best method to use here. Kubernetes support this feature through kubectl utility. It is important to note here that this feature is also available for Kubernetes deployment, replicaset and service. Port forwarding does not start by default. One has to manually start and stop it.
Kubectl port-forward command is much more generic in comparison to kubectl proxy command. It is so because kubectl port-forward can forward TCP traffic while kubectl proxy can only forward HTTP traffic. We will understand the concept further by using a real time example in below section. More on official website.
What is Port Forwarding
It is Port mapping technique in which requests from the outside world can be mapped to an internal port of a private network resource which is not otherwise accessible over the public network.
Why Port Forwarding Required
If you want to access pods and services which are not exposed to the external world, then Port forwarding technique can be used to route the traffic from the localhost port to access those services.
How to Access Kubernetes Cluster Metrics Using Port Forwarding
You can first switch to the context in which the pods exist. In our case, the context is
test-app-uat so to switch to this context we need to run
kubectl config use-context test-app-uat command as shown below.
root@cyberithub:~# kubectl config use-context test-app-uat Switched to context test-app-uat
Next step is to check all the pods running in the current context by using
kubectl get pods command as shown below. For the demo purpose, here we are going to access the metrics of one of our running pod called
test-app-consumer-b89c48763d-5khg7 using port forwarding technique.
root@cyberithub:~# kubectl get pods
To enable the Port Forwarding, you need to use below kubectl port-forward command. This will forward all the requests or connections going to your localhost
Port 8081 to Pod
Port 8081. Here you just need to make sure the local port you are sending requests to must be free and available to use.
root@cyberithub:~# kubectl port-forward test-app-consumer-b89c48763d-5khg7 8081:8081 Forwarding from 127.0.0.1:8081 -> 8081 Forwarding from [::1]:8081 -> 8081 Handling connection for 8081 Handling connection for 8081
which is the same as
root@cyberithub:~# kubectl port-forward pods/test-app-consumer-b89c48763d-5khg7 8081:8081
root@cyberithub:~# kubectl port-forward deployment/test-app-consumer 8081:8081
root@cyberithub:~# kubectl port-forward rs/test-app-consumer 8081:8081
root@cyberithub:~# kubectl port-forward svc/test-app-consumer 8081:8081
Once the forwarding is enabled, you can now open your favorite web browser in your local System and access the Cluster metrics by accessing URL
http://localhost:8081. To stop the forwarding, you can just