Search code examples
pythondockergrpcwindows-subsystem-for-linux

Access gRPC python server with "localhost" security in WSL2 docker from windows


The issue is this. I am getting a zip file made by pyinstaller. Inside the file there is a setting making the server listen only to localhost server.add_insecure_port(f'localhost:{port_num}'). I want to run this python file from a centos docker. Docker is running on WSL2.

So far I was able to run the docker but the issue is as follow: I can make grpcUrl calls to localhost:port from the WSL2 (in my case ubunty). But when I try to make those calls from windows cmd I get the following error:

Failed to dial target host "localhost:9111": dial tcp [::1]:9111: connectex: No connection could be made because the target machine actively refused it. Or this Failed to dial target host "127.0.0.1:9111": dial tcp 127.0.0.1:9111: connectex: No connection could be made because the target machine actively refused it.

I have started the docker using --network="host" hoping it can help me, but it only help ubuntu to do grpcUrl calls, but not windows.

Any help would be appriciated. Note that I cannot change localhost to 0.0.0.0...


Solution

  • SSH tunneling was an answer for me.

    Install SSH server on WSL:

    1. sudo apt install openssh-server
    2. sudo vi /etc/ssh/sshd_config -> insert next block at the end
    Port 2222
    ListenAddress 0.0.0.0
    PubkeyAuthentication no
    PasswordAuthentication yes
    

    search for any additional PasswordAuthentication in the file and make it yes.

    1. Create ssh key
    sudo ssh-keygen -A
    sudo service ssh --full-restart
    
    1. Add a script to run SSH on startup vi ~/.bashrc -> insert next block at the end of the file
    #Start ssh automatically
    RUNNING=`ps aux | grep sshd | grep -v grep`
    if [ -z "$RUNNING" ]; then
        sudo service ssh start > /dev/null 2>&1 &
        disown
    fi
    
    1. Make ssh server run without password sudo visudo -> insert next code at the end of the file
    %sudo ALL=NOPASSWD: /usr/sbin/service ssh *
    
    1. Restart WSL -> from CMD run wsl --shutdown and open wsl again (for example by running ubuntu)

    Get the ip of the wsl - run from CMD wsl hostname -I

    Now run from CMD ssh -L 127.0.0.1:<port>:localhost:<port> <wsl username>@<ip from wsl hostname -I> -p 2222