0
0
KubernetesHow-ToBeginner · 3 min read

How to Port Forward to Pod in Kubernetes: Simple Guide

Use the kubectl port-forward pod/ : command to forward a local port to a port on a Kubernetes pod. This allows you to access the pod's service locally without exposing it externally.
📐

Syntax

The basic syntax for port forwarding to a pod is:

  • kubectl port-forward pod/<pod-name> <local-port>:<pod-port>

Here:

  • <pod-name> is the name of the pod you want to access.
  • <local-port> is the port on your local machine you want to use.
  • <pod-port> is the port inside the pod you want to forward to.
bash
kubectl port-forward pod/<pod-name> <local-port>:<pod-port>
💻

Example

This example forwards local port 8080 to port 80 on a pod named my-pod. You can then access the pod's service at http://localhost:8080.

bash
kubectl port-forward pod/my-pod 8080:80
Output
Forwarding from 127.0.0.1:8080 -> 80 Forwarding from [::1]:8080 -> 80
⚠️

Common Pitfalls

  • Wrong pod name: Make sure the pod name is correct by running kubectl get pods.
  • Port conflicts: The local port must not be in use by another process.
  • Namespace issues: If your pod is in a different namespace, add -n <namespace> to the command.
  • Pod not running: Port forwarding only works if the pod is in Running state.
bash
kubectl port-forward pod/my-pod 8080:80
# Wrong way if pod is in 'dev' namespace:
kubectl port-forward pod/my-pod 8080:80

# Correct way specifying namespace:
kubectl -n dev port-forward pod/my-pod 8080:80
📊

Quick Reference

CommandDescription
kubectl get podsList all pods in the current namespace
kubectl port-forward pod/ :Forward local port to pod port
kubectl -n port-forward pod/ :Port forward in a specific namespace
kubectl port-forward svc/ :Port forward to a service (alternative)

Key Takeaways

Use kubectl port-forward pod/ : to access pod ports locally.
Ensure the pod is running and the pod name is correct before port forwarding.
Specify the namespace with -n if the pod is not in the default namespace.
Avoid local port conflicts by choosing an unused local port.
Port forwarding is temporary and stops when the command is terminated.