Port Forwarding from Ubuntu WSL to Windows Host

Smart ShockSmart Shock
2 min read

Port forwarding is a powerful technique that allows us to access services running on different machines and networks. If you're working on developing a FastAPI service on your Ubuntu installation running on the Windows Subsystem for Linux (WSL), you may want to access it from your Windows host machine. In this tutorial, we'll show you how to do port forwarding from your Ubuntu WSL installation to your Windows host machine and access a FastAPI service developed on Ubuntu from Windows.

Prerequisites:

  • Ubuntu installation running on Windows Subsystem for Linux (WSL)

  • Windows host machine

Step 1: Start the SSH server on Ubuntu WSL

The first step is to start the SSH server on your Ubuntu WSL installation. Open a terminal window on Ubuntu and run the following command:

sudo service ssh start

Step 2: Find the IP address of Ubuntu WSL

Next, you need to find the IP address of your Ubuntu WSL installation. Open a terminal window on Ubuntu and run the following command:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

Step 3: Run netsh command on Windows host machine

On your Windows host machine, open the Command Prompt as an administrator and run the following command:

netsh interface portproxy add v4tov4 listenaddress=127.0.0.1 listenport=<LOCAL_PORT> connectaddress=<WSL_IP_ADDRESS> connectport=<WSL_PORT>

Replace [WSL_IP_ADDRESS] with the IP address of your Ubuntu WSL installation that you found in Step 2.

Step 4: Test the port forwarding

Test the port forwarding by opening a web browser on your Windows machine and navigating to http://localhost:<LOCAL_PORT> (where <LOCAL_PORT> is the port number that you specified in step 4).

If the port forwarding is set up correctly, you should see the web content from your Ubuntu WSL instance displayed in your web browser on your Windows machine.


Example: Running a sample FastAPI service on Ubuntu WSL and accessing the same on a windows browser.

Step 1: create a file called hello.py with the below content

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=5001)

Step 2: Start the FastAPI service

python3 hello.py

Step 3: Access the FastAPI service on Windows browser


NOTE:

Note that you will need to keep the SSH server running on your Ubuntu WSL instance for the port forwarding to work. If you restart your Ubuntu WSL instance, you will need to start the SSH server again before you can use the port forwarding.

1
Subscribe to my newsletter

Read articles from Smart Shock directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Smart Shock
Smart Shock