Skip to content

Instantly share code, notes, and snippets.

@alepez
Created September 25, 2024 14:13
Show Gist options
  • Save alepez/20da3a84a0af606e45240d2bc509a2cd to your computer and use it in GitHub Desktop.
Save alepez/20da3a84a0af606e45240d2bc509a2cd to your computer and use it in GitHub Desktop.
kubernetes k8s kubectl remote port forwarding

You are debugging a program which is running in a container.

The program usually connects to some remote tcp port (e.g. for it's output, telemetry, logging...).

For faster debugging, you want to make it connect to a service which is running locally on your workstation.

Usually, you can do this with ssh remote port forwaring. But you're on k8s and you don't have access to the container directly with ssh.

Currently (2024), kubectl can do local port forwarding (like ssh -L), but it does not support remote port forwarding (like ssh -R).

If you can install sshd in the container, you can do remote port forwarding.

For instance, if the container is running a debian linux:

  • Access to the container with kubectl exec -ti -n $namespace $pod -- bash

Run these commands in the container:

apt-get install -y openssh-server vim
mkdir /root/.ssh
echo $your_ssh_public_key >> /root/.ssh/authorized_keys
/usr/sbin/sshd -D

Run these commands locally:

kubectl port-forward -n $namespace $pod 2222:22 &
ssh root@localhost -p2222 -R8080:localhost:8080 -Nf

Test the connection in the container:

curl http://localhost:8080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment