Reverse Port Forwarding
Connecting from a Kubernetes to a Service running on your local machine
Introduction
Sometimes you need to connect from a service running in a Kubernetes cluster to a service running on your local machine. This can be useful for debugging, testing, or development purposes. In this article, we’ll explore how to set up reverse port forwarding to enable this kind of connection.
High-Level Architecture
As shown in the diagram, the service running in the Kubernetes cluster needs to connect to a service running on your local machine.
The kubectl port-forward
command is used to forward a local port 8022
to the ssh server pod port 22
running in the Kubernetes cluster.
The ssh -R
command is used to let us forward the remote port 50080
from the ssh server pod to the local machine port 8080
.
The kubernetes service fwd-to-local-dev
is used to expose the ssh server pod port 50080
as port 8080
to all services running on the Kubernetes cluster and the test pod as well.
For testing purposes, a simple netcat
is used to listen on a port 8080
on the local machine, and a test pod is used to connect to this service with netcat
client through the reverse port forwarding tunnel.
Kubernetes Resources Congifurations
Preapare the following configurations to deploy the resources in the Kubernetes cluster.
Create a directory to store the configurations
Pod Configuration
The Alpine Linux
is used as a base image for the ssh server pod.
Service Configuration
Test pod configuration
Deploy the resources
Setting up the Reverse Port Forwarding
To set up the reverse port forwarding, you need to run the following command on your local machine:
[Terminal 1] Forward the local port 8022 to the ssh server pod
[Terminal 2] Start locally service listening on port or netcat
in my case
NOTE: 8080
port is port where my netcat service is listening on.
Just skip this step if you already have a service running on your local machine.
Please do not forget to replace the port number in the next step with the port your service is listening on.
[Terminal 3] Open a reverse ssh tunnel to the ssh server pod
NOTE: 8080
port is port where your local service is listening on.
You can replace it with the port your service is listening on.
NOTE: Password: dummy_passwd
[Terminal 4] Testing the Connection
To test the connection, you can run the following command in the test pod: