0
0
Kubernetesdevops~5 mins

kubectl port-forward for local access in Kubernetes - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to access an app running inside Kubernetes from your own computer without exposing it publicly. kubectl port-forward lets you connect your local computer to a port inside a Kubernetes pod securely and easily.
When you want to test a web app running inside a pod without changing its service or ingress setup
When you need to connect to a database inside Kubernetes for debugging or data checks
When you want to securely access an internal service without opening firewall ports
When you want to forward traffic from your local machine to a pod port for development
When you want to quickly check logs or metrics exposed on a pod port
Commands
This command lists all pods in the current namespace so you can find the pod name to forward ports from.
Terminal
kubectl get pods
Expected OutputExpected
NAME READY STATUS RESTARTS AGE my-app-pod-1234567890 1/1 Running 0 10m
This command forwards your local port 8080 to port 80 on the pod named my-app-pod-1234567890. Now you can access the pod's app at http://localhost:8080 on your computer.
Terminal
kubectl port-forward pod/my-app-pod-1234567890 8080:80
Expected OutputExpected
Forwarding from 127.0.0.1:8080 -> 80 Forwarding from [::1]:8080 -> 80
This command tests the connection by sending a request to the forwarded local port. It should return the app's response from inside the pod.
Terminal
curl http://localhost:8080
Expected OutputExpected
<html><body>Welcome to my app!</body></html>
Key Concept

kubectl port-forward creates a secure tunnel from your local machine to a pod port, letting you access pod services without exposing them externally.

Common Mistakes
Using the pod name incorrectly or misspelling it in the port-forward command
kubectl cannot find the pod and the port-forward fails with an error
Run 'kubectl get pods' first to copy the exact pod name and use it in the command
Trying to forward to a port that the pod is not listening on
The connection will fail because no service is running on that port inside the pod
Check the pod's container ports or app configuration to confirm the correct port
Not keeping the port-forward command running in the terminal
Port forwarding stops as soon as the command exits, losing the connection
Keep the terminal open or run the command in a separate window or background
Summary
Use 'kubectl get pods' to find the pod name you want to access.
Run 'kubectl port-forward pod-name local-port:pod-port' to forward traffic from your computer to the pod.
Test the connection by accessing the forwarded local port in a browser or with curl.