Home » Docker and Kubernetes » Kubernetes (K8s) + Kubectl Port-Forward: A Comprehensive Guide (2023)
Kubernetes (K8s) + Kubectl Port-Forward: A Comprehensive Guide (2023)
The Kubernetes command-line tool, kubectl, allows you to run commands against Kubernetes clusters. We can use kubectl to deploy applications, inspect and manage cluster resources, and view logs. For more information including a complete list of kubectl operations.
As per my knowledge to access something inside the cluster, there ae a couple of different options available to,
Cluster IP service with Ingress-Nginx
NodePort Service to expose the pod directly to the outside world.
Above both approach will require to write config file.
Note: In case if you want to access a pod without writing a config file then it comes to 3rd option (kubectl port-forward).
Port Forward: We can run a command at our terminal that tells our Kubernets (k8) cluster to port-forward a port off a very specific pod inside of our cluster when we use this port forwarding thing that’s going to cause our cluster to essentially behaves as though it has a node port service running inside it. It’s going to expose this pod or a very specific port on it to the outside world and allow us to connect to it directly from our local machine. In this article we will discuss on 3rd option I mean Port Forward. Remember following important points during microservices implementation.
kubectl exposes commands that can be used to create a Service for an application and assigns an IP address to access it from internet.
As far as I understand, to access any application within Kubernetes cluster there should be a Service resource created and that should have an IP address which is accessible from an external network.
But in case of port-forward how does kubectl create a connection to the application without an IP address which is accessible externally?
As per understanding in Kubernetes, every pod gets its own ip address from 10.*, that is usable only within the cluster right. Now, the port-forward feature of kubectl simply tunnels the traffic from a specified port at your local host machine to the specified port on the specified pod. API server then becomes, in a sense, a temporary gateway between your local port and the Kubernetes cluster.
kubectl port-forward forwards connections to a local port to a port on a pod. Compared to kubectl proxy, kubectl port-forward is more generic as it can forward TCP traffic while kubectl proxy can only forward HTTP traffic.
kubectl port-forward is useful for testing/debugging purposes so you can access your service locally without exposing it.