Learn to use kubectl port-forward for local access to Kubernetes cluster resources without internet exposure, ideal for testing and debugging.
In this lesson, you’ll learn how to use the kubectl port-forward command—a powerful technique that enables local access to internal Kubernetes cluster resources without exposing them to the internet. This method is ideal for testing, debugging, or accessing services in development and user acceptance testing environments.Port forwarding is particularly useful when working with ClusterIP services, such as a typical “notes-app-deployment” running in the “uat” (user acceptance testing) namespace. Since ClusterIP services are only accessible within the cluster, port forwarding creates a secure tunnel from your local machine directly to the service.
To securely access the internal service, you can use the kubectl port-forward command. This command establishes a local tunnel where traffic from a specified local port is redirected to the service’s port in the cluster.For example, to forward local port 8000 to the service’s port 80 (which then directs traffic to the pod target port 3000), run the following command:
Copy
Ask AI
controlplane ~ ➜ k port-forward -n uat svc/notes-app-deployment 8000:80Forwarding from 127.0.0.1:8000 -> 3000
Once the port forward is active, you can access the notes application locally. For instance, execute:
Similarly, you can port-forward other internal services. For example, if you need secure access to the Kubernetes Dashboard (a ClusterIP service), forward a local port to the Dashboard’s port as shown:
Copy
Ask AI
controlplane ~ ➜ k port-forward -n kubernetes-dashboard svc/kubernetes-dashboard-web 8000:8000
After running the command, open your web browser and navigate to http://localhost:8000 to access the Kubernetes Dashboard securely.
In summary, the kubectl port-forward command is an essential tool that enables a secure, temporary tunnel from your local machine directly to services or pods within a Kubernetes cluster. This technique is widely used for debugging, testing APIs, or accessing internal services without the need for an external load balancer.For further reading on Kubernetes concepts and commands, check out these resources: