Sign In

Curriculum 12: Pod Management

kubectl port-forward

12 min · 25 XP

Port Forwarding with kubectl port-forward

The kubectl port-forward command creates a tunnel between your local machine and a pod or service inside the cluster. This is invaluable for local development, debugging, and accessing internal services without exposing them externally.

Forwarding to a Pod

Map a local port to a port on a specific pod:

# Forward local port 8080 to pod port 80
kubectl port-forward pod/my-pod 8080:80

# Use the same port number locally
kubectl port-forward pod/my-pod 3000:3000

# Let kubectl pick a random local port
kubectl port-forward pod/my-pod :80

Once running, access the pod at http://localhost:8080 from your browser or tools.

Forwarding to a Service

You can also forward to a service, which routes through the service's selector to a backing pod:

kubectl port-forward svc/my-service 8080:80
kubectl port-forward service/my-database 5432:5432

This is useful when you do not know the exact pod name or when pods are frequently replaced.

Common Use Cases

# Access a web dashboard not exposed externally
kubectl port-forward svc/grafana 3000:3000 -n monitoring

# Connect a local database client to an in-cluster database
kubectl port-forward svc/postgres 5432:5432

# Debug an API service locally
kubectl port-forward deploy/api-server 9090:8080

Important Considerations

Port forwarding runs in the foreground and stops when you press Ctrl+C. It only works while your terminal session is active. The connection binds to localhost by default. To bind to all interfaces, use --address 0.0.0.0:

kubectl port-forward --address 0.0.0.0 pod/my-pod 8080:80

Port forwarding is a development tool, not a production traffic solution. For production access, use Ingress or LoadBalancer services.