A Quick Guide to Running X11 Apps on WSL2

In WSL1, all you had to do was install an X server and you could run X11 apps normally. But in WSL2, it gets a bit harder. It runs in a VM instead of being run as a compatibility layer.

Starting VcXsrv

First, start up VcXsrv (or whatever X server you use). Make sure to turn off access control to allow WSL to access it without being blocked, and make sure it runs on 0.0.0.0 to ensure that it's possible to access it outside of the current computer.

Setting environment variables

Since WSL is running in a VM, it can't directly connect to localhost; it has to connect to the IP address.
Here is a script (albeit lengthy) to set the $DISPLAY variable by grabbing the IP address by invoking powershell, cutting off the last character (a carriage return), and appending :0.0 to the IP:

export DISPLAY=$(powershell.exe -Command '(Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.AddressState -eq "Preferred" -and ($_.InterfaceAlias -eq "Wi-Fi" -or $_.InterfaceAlias -eq "Ethernet")}).IPAddress' | sed 's/.$//'):0.0

We also need to make sure that OpenGL tells the X server to draw graphics and doesn't try to directly access the hardware.

export LIBGL_ALWAYS_INDIRECT=1

Here is a Github Gist containing a shell script that does this for you.

Running apps

There are no special instructions for running apps, just run them like you would in a regular Linux system.