How kubectl port-forward works?

karthikeayan picture karthikeayan · Jul 22, 2018 · Viewed 63.2k times · Source

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?

Answer

lvthillo picture lvthillo · Jul 22, 2018

To start, it's useful to note and remember that in Kubernetes, every pod gets its own ip address from 10.*, that is usable only within the cluster. 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.

Below is the name of the pod and it will forward it's port 6379 to localhost:6379.

kubectl port-forward redis-master-765d459796-258hz 6379:6379 

which is the same as

kubectl port-forward pods/redis-master-765d459796-258hz 6379:6379

or

kubectl port-forward deployment/redis-master 6379:6379 

or

kubectl port-forward rs/redis-master 6379:6379 

or

kubectl port-forward svc/redis-master 6379:6379

Here is also some small port forwarding example to access a database service (clusterip) without exposing it.