Tunneling via Kubernetes

2020-10-02 Rameez Khannetworking


For security reasons, you might find your database (or any service for that matter) in an internal subnet, somewhere in the cloud. Accessing this for local debugging/development can be a pain.

Using Kubernetes (assuming you have a cluster already), you can use this to your advantage.

Create the tunnel

What you need:

  • Kubernetes (with API access via kubectl ofcourse)
  • An image with netcat installed (Nice opportunity to punt mine 😉)
  • tcpserver (should come with any Debian based distro)

Next, ensure your pod is running. I have a handy alias for this.

alias kdebug='kubectl exec -it debuggery -- zsh || kubectl run --rm -it debuggery --image=rameezk/debuggery --restart=Never'

In another terminal window, run the following:

tcpserver "$local_port" kubectl exec -i debuggery -- nc "$remote_host" "$remote_port"

Where $local_port is the local port you would access the service on (i.e.$local_port). Similarly $remote_host and $remote_port are the remote host and port respectively. The host, for example, will be the DB host address.

If all goes well, you won’t see any output, but the TCP tunnel should have been established.

You can make this a script as well and add to it to your .zshrc or .bashrc. You can see mine here.

Other ways of tunneling

If you have a Jumphost (or Bastion) and assuming it can access your private subnet, you can create an SSH tunnel as well.