Forward traffic from Kubernetes pod to local server

3/17/2021

How can I forward traffic from a remote Kubernetes pod to a server running on my local machine? The intention is to test a remote server making calls to a service running on my local machine. I've used kubectl port-forward to forward traffic from my local service to remote service, but I need to do this the other way around.

This solution is for minikube, which is used to run Kubernetes locally, so this probably doesn't apply to me.

-- user2233706
kubernetes

2 Answers

3/17/2021

There's probably a "more K8s" way, but here's an idea in case you don't find anything better - use ssh.

Specifically, set up and expose SSH on the pod so it's accessible from your local machine. Then just use ssh on your machine to create a remote ssh tunnel.

For instance ssh -R 8080:localhost:80 <exposed-pod-ssh> will forward the pod's localhost:8080 to your local machine port 80.

-- Malt
Source: StackOverflow

3/17/2021

This is a very annoying task.

With nothing special on hands, you need to redirect a port from your modem to your machine. Most of people have non-fixed public ips, so you need to find your public ip address (you cant search for "what is my ip") and hope that it don't change between your tests. With your public ip address you can try to access directly from pod, ex:

kubectl exec -ti alpine-pod -- curl 150.136.143.228:8080

Some clusters don't let the pod go outside from their own, so, better create an service without selectors and then add the an endpoint pointing to your ip:

apiVersion: v1
kind: Service
metadata:
  name: to-my-home
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080

Then, add the endpoint:

apiVersion: v1
kind: Endpoints
metadata:
  name: to-my-home
subsets:
  - addresses:
      - ip: 150.136.143.228
    ports:
      - port: 8080

Now, if you're inside in the same namespace that service, you cand do this:

kubectl exec -ti alpine-pod -- curl to-my-home

An better, and easy, solution is to use vagrant share, https://www.vagrantup.com/docs/share, but you need some steps:

  1. Install an hypervisor (VirtualBox, Libvirt, HyperV, VMWare)
  2. Install Vagrant
  3. Create and account on https://app.vagrantup.com
  4. Start a machine and use vagrant share
  5. Grab the URL showed on command return and use on pod/service, the port is always 80

Example:

vagrant init debian/buster64
vagrant login
vagrant up
vagrant share
-- Hector Vido
Source: StackOverflow