How can I access a service running on WSL2 from inside a Docker container?

So what you need to do in the windows machine port forward the port you are running on the WSL machine, this script port forwards the port 4000

netsh interface portproxy delete v4tov4 listenport="4000" # Delete any existing port 4000 forwarding
$wslIp=(wsl -d Ubuntu -e sh -c "ip addr show eth0 | grep 'inet\b' | awk '{print `$2}' | cut -d/ -f1") # Get the private IP of the WSL2 instance
netsh interface portproxy add v4tov4 listenport="4000" connectaddress="$wslIp" connectport="4000"

And on the container docker run command you have to add

--add-host=host.docker.internal:host-gateway

or if you are using docker-compose:

    extra_hosts:
      - "host.docker.internal:host-gateway"

Then inside the container you should be able to curl to

curl host.docker.internal:4000

and get a response!

Leave a Comment