‘kubectl’ on WSL2 gives you “The connection to the server localhost:8080 was refused – did you specify the right host or port?” when using ‘sudo’

I ran into this problem trying to do a port-forward on port 443 in WSL2. Normally you don’t use ‘sudo’ for ‘kubectl’ commands but when it comes to port-forwarding ports under port 1024, 443 in this case, you need ‘sudo’ to get your OS to accept the binding of the port

The solution for me was to make sure the root user had access to the .kube/config file of my normal user. I did this via the environment variable KUBECONFIG:

1. Open a root shell

sudo su

2. Export the KUBECONFIG with a path to my regular users .kube/config

export KUBECONFIG=/home/niklas/.kube/config

3. Do the port-forward to port 443 (or anything else that needs root access)

kubectl port-forward -n ingress-nginx service/ingress-nginx-controller 443:443

I wasn’t looking for a permanent solution so this worked for the few tests I needed to do while setting up my Ingress for mTLS authentication

Tested on ‘kubectl’ 1.26, WSL2 with Ubuntu 20.08 and Kubernetes v1.26 on Minikube

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.