kubectl port-forward is a Kubernetes command that allows to access internal cluster resources from outside the cluster.
It tunnels a traffic from a specified port on a localhost to the specified port on the specified Pod.
The kubectl port-forward command is useful for troubleshooting issues, setting up services locally without exposing them, and debugging applications within the cluster.
This post shows the examples of how to use the kubectl port-forward command to access the internal cluster resources from the locathost.
Cool Tip: How to connect to K8s cluster using kubectl from Windows! Read more →
Kubectl Port-Forward
To forward traffic from a specified port a localhost to a specified port on a Pod in a Kubernetes cluster, you can use the kubectl port-forward command:
$ kubectl port-forward <resourceName> <localPort>:<remotePort>
For example, to forwards traffic from port 8080 on your local machine to port 80, exposed by nginx Service, execute:
$ kubectl port-forward service/nginx 8080:80 - or - $ kubectl port-forward svc/nginx 8080:80 - sample output - Forwarding from 127.0.0.1:8080 -> 80 Forwarding from [::1]:8080 -> 80
Then, to access the Service running on the Pod – navigate to http://localhost:8080 in your web-browser.
ℹ️ Note kubectl port-forward is not intended for exposing services publicly. It is primarily used for local debugging and troubleshooting purposes.
To find out what are the exposed ports, running Pods, Services and other resources on your Kubernetes cluster, execute:
$ kubectl get all
- sample output -
NAME READY STATUS RESTARTS AGE
pod/nginx-68db7f646-cnlp 1/1 Running 0 14d
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/nginx ClusterIP 10.96.0.1 <none> 80/TCP 14d
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/nginx 1/1 1 1 14d
NAME DESIRED CURRENT READY AGE
replicaset.apps/nginx-68db7f646 1 1 1 14d
As a <resourceName> in the kubectl port-forward command you can specify Pods, Services, Deployments or ReplicaSets, for example:
# Port-Forward to Pod $ kubectl port-forward nginx-68db7f646-cnlp 8080:80 - or - $ kubectl port-forward pod/nginx-68db7f646-cnlp 8080:80 # Port-Forward to Deployment $ kubectl port-forward deployment/nginx 8080:80 # Port-Forward to ReplicaSet $ kubectl port-forward replicaset/nginx-68db7f646 8080:80 - or - $ kubectl port-forward rs/nginx-68db7f646 8080:80 # Port-Forward to Service $ kubectl port-forward service/nginx 8080:80 - or - $ kubectl port-forward svc/nginx 8080:80
All the commands above are identical and execution of any of them will forward traffic from http://localhost:8080 on your local machine to the exposed Service on your Kubernetes cluster, i.e. port 80 exposed by nginx.