angelnu / pod-gateway

Container image used to set a pod gateway
Apache License 2.0
56 stars 29 forks source link

fix port forwarding in k8s environments #51

Closed jgilfoil closed 1 month ago

jgilfoil commented 9 months ago

Problem Statement In Kubernetes environments, the hostname command will return something like pod-bcf579d67-c9plq instead of just pod. And since you can't know the pod name ahead of time, the value being matched for in /config/nat.conf will be just 'pod' and will fail to match, causing the NAT_ENTRY variable to be empty and enter the dhclient if statement instead of setting the static ip logic. This means port forwarding won't work.

Description of the change

This change checks for the presence of the KUBERNETES_SERVICE_HOST environment variable to determine if the client_init.sh script is being run in k8s. If it is, it strips off the pod name after the first dash, so you'll get just the deployment name, which you can then set in pod-gateway chart values publicPorts.hostname and it will match.

If the env variable isn't present, then it proceeds with the full value from hostname.

Benefits

Port forwarding in Kubernetes will now work properly.

Possible drawbacks

The only limitation with this is if the deployment name has a dash in it, under those circumstances the pod name would be cut off too early. You could probably work around this by cutting off the hostname in the pod-gateway chart.

I've tested this in my own cluster in kubernetes and it worked, the static ip was properly set to 10 per my config and the traffic is getting forwarded to my pod. https://github.com/jgilfoil/home-cluster/pull/121/files

I did not test this change in a regular docker environment.

samip5 commented 1 month ago

This is not needed when one uses statefulsets as the naming is different for deployments and sts.

This will probably also break the port forwarding when the pod name is like pod-0, pod-1.