Vcxsrv windows x server wsl

I needed to set up a WSL2 GUI recently on my machine (WSL2 running uBuntu 20.04.1 LTS). I found a guide that runs through the process but found that a few tweaks needed to be made. Specifically, the communication to VcXsrv was being blocked by Windows Firewall.

There were also a couple of extra tweaks needed for audio passthrough using PulseAudio and setting a windowed resolution.

Setting up a WSL2 GUI X-Server in Windows

Start by installing xfce4 and goodies.

sudo apt install xfce4 xfce4-goodies

If you’re running Kali you should use:

sudo apt install kali-desktop-xfce

During the install you’ll be prompted about which display manager to use. This is up to you, though I personally chose lightdm.

Download this .zip package which contains VcXsrv and PulseAudio along with some configuration and a shortcut to launch.

Extract it to the root of your C:\ drive. You should end up with contents under C:\WSL VcXsrv.

WSL2 GUI vcxsrv package contents

Run the vcxsrv-64.1.20.8.1.installer.exe installer in this folder, choosing defaults for the install.

Once installed, you’ll want to enable High DPI scaling for VcXsrv in Windows.

  • Navigate to C:\Program Files\VcXsrv
  • Right-click xlaunch.exe and go to Compatibility
  • Click Change high DPI settings and choose Override high DPI scaling behavior. Ensure Application is in the dropdown.

Next, edit the startWSLVcXsrv.bat batch file and change the last line that reads ubuntu.exe run to one of:

  • ubuntu2004.exe run in the case you are using uBuntu 20.04 from the Microsoft Store for WSL
  • ubuntu1804.exe run if you are using uBuntu 18.04 from the Microsoft Store for WSL
  • ubuntu.exe run for when you are using standard uBuntu from the Microsoft Store for WSL
  • kali.exe run if you installed Kali-Linux from the Microsoft Store for WSL

Pin the WSL VcXsrv shortcut somewhere convenient like the taskbar.

Opening Windows Firewall for VcXsrv and PulseAudio

Next you need to allow inbound traffic to Windows for VcXsrv and PulseAudio.

Open Windows Defender Firewall with Advanced Security and add two new Inbound Rules as follows:

  • Type: Program
  • Program path: %ProgramFiles%\VcXsrv\vcxsrv.exe for VcXsrv and %SystemDrive%\WSL VcXsrv\pulseaudio-1.1\bin\pulseaudio.exe for PulseAudio
  • Allow the connection
  • Profile: Domain, Private
  • Name: vcxsrv or pulseaudio depending which rule you are adding

I personally added the following to ExtraParams under the XLaunch node of config.xlaunch. This sets windowed mode to 1920×1080 for monitor #1 on my machine.

-screen 0 1920x1080@1

Viewing your WSL2 GUI

With all of that setup out of the way, you should be able to simply launch VcXsrv from the pinned shortcut and everything should work.

Try it out and you should get Desktop up and running for your WSL2 environment.

WSL2 gui example with audio settings open

PulseAudio passthrough should also be available if you check your sound / volume settings. Try an audio test using alsa-utils:

sudo apt install alsa-utils
speaker-test

Kudos to this guide on reddit for most of the setup instructions. As mentioned before, I needed to configure my firewall and also added some tweaks for windowed mode.

Troubleshooting

If you find your VcXsrv Server display window is blank when launching, try the following:

  • Double-check your firewall rule is allowing inbound connections for vcxsrv.exe for the domain and private scopes.
  • With the black X-server / display window from VcXsrv still open, launch a WSL shell separately, and run the following to set your DISPLAY environment variable:
export DISPLAY=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'):0

This takes the IP address of your host machine (conveniently used as a nameserver in your WSL Linux environment for DNS lookups) and sets it as the Display remote location (with :0 for the display number appended).

Now, try to launch a xfce4 session with:

xfce4-session

If all goes to plan, the session should target your machine where VcXsrv Server is running and your display window should come to life with your WSL environment desktop.

Время на прочтение9 мин

Количество просмотров99K

Введение

Данная статья предназначена вниманию системных администраторов, которые подготавливают типовые рабочие места на компьютерах под управлением ОС Windows 10, в том числе для разработчиков ПО.

Следует отметить, что существует определенная проблема, связанная с невозможностью интеграции ПО, полученного в on-line магазине Microsoft Store для использования в пользовательском образе Windows 10. Не вдаваясь в подробности уточню, что данная проблема связана с тем, что установленные из Microsoft Store программы связываются со служебной учетной записью Administrator, и при завершении создания пользовательского образа утилитой sysprep возникают обусловленные этим обстоятельством ошибки.

Рассмотренный в данной статье способ позволить избежать такой проблемы при подготовке образа ОС Windows 10 с предварительно настроенной подсистемой WSL2, а также с заранее подготовленным и настроенным образом ОС Ubuntu 20.04 с GUI KDE Plasma, который в свою очередь может иметь свой набор пользовательского ПО.

В сети Интернет имеется большое количество примеров и руководств по настройке подсистем WSL (т.е. WSL1 и сравнительно новой WSL2), с настройкой GUI интерфейса для linux систем на базе ОС начиная с версии Ubuntu 16.04 и заканчивая Ubuntu 20.04, но в основном это касалось рабочих столов на основе т.н. «легковесного» xfce4, имеющий вполне объяснимые ограничения в пользовательских настройках. Но что касается GUI KDE Plasma для Ubuntu 20.04, в сети не нашлось какой-либо существенной информации. Но именно этот вариант предоставляет конечному пользователю практически неограниченный набор настроек как внешнего вида системы, так и настроек оборудования, конечно с учетом текущих возможностей интеграции linux-систем, реализованных в подсистеме WSL2.

Установка требуемого набора ПО и настройка WSL2

Проверяем текущую версию Windows, для этого в строке поиска Windows вводим команду winver и получаем примерно следующее:

Важно, чтобы ОС имела версию 1903 или 1909 (указанные версии ОС должны быть с установленным накопительным обновлением KB4566116), либо 2004 (номер сборки не менее чем 19041), остальная информация не имеет значения. Если номер версии меньше, то для корректного повторения результатов, изложенных в данной статье, рекомендуется обновиться до последней версии Windows.

Для удобства дальнейших действий устанавливаем бесплатный Windows Terminal, используя Microsoft Store (также существует возможность загрузки из других источников):

Устанавливаем X Server X410 через тот же Microsoft Store, это ПО платное, но имеется бесплатный период в 15 дней, что вполне достаточно для проведения различных тестов.

В качестве бесплатной альтернативы X410 скачиваем и устанавливаем X-сервер VcXsrv.

В любом удобном месте на диске создаем каталог, в котором будем хранить наши файлы. В качестве примера создадим каталог C:\wsl.

Скачиваем и устанавливаем автономный установщик Ubuntu 20.04, распаковываем полученный файл с помощью архиватора (например 7-zip). Переименовываем распакованный каталог с длинным именем Ubuntu_2004.2020.424.0_x64 во что-то более приемлемое, например Ubuntu-20.04 и копируем его в каталог C:\wsl (далее по тексту просто \wsl).

Скачиваем и распаковываем в каталог \wsl кроссплатформенный звуковой сервер PulseAudio v.1.1., также вносим исправления в его конфигурационные файлы.

В файле \wsl\pulseaudio-1.1\etc\pulse\default.pa в разделе Load audio drivers statically редактируем строку:

load-module module-waveout sink_name=output source_name=input record=0

а в разделе Network access редактируем строку:

load-module module-native-protocol-tcp auth-ip-acl=127.0.0.1 auth-anonymous=1

В файле \wsl\pulseaudio-1.1\etc\pulse\daemon.conf раскомментируем и изменяем строку

exit-idle-time = -1

Настраиваем подсистему WSL2 в соответствии с документацией Microsoft. Единственное замечание — дистрибутив Ubuntu мы уже скачали, и устанавливать его будем на следующем шаге. В основном, настройка сводится к включению дополнительных компонентов «Подсистема Windows для Linux» и «Платформа виртуальной машины», и последующей перезагрузки для применения изменений в настройках компьютера:

При необходимости скачиваем и устанавливаем пакет обновлений для ядра Linux в WSL2.
Запускаем Windows Terminal и выбираем режим работы Command Prompt нажатием клавиш Ctrl+Shift+2.

В первую очередь устанавливаем режим работы WSL2, для этого вводим команду:

wsl  --set-default-version 2

Переходим в каталог с автономным загрузчиком Ubuntu 20.04, в моем случае это \wsl\Ubuntu-20.04 и запускаем файл ubuntu2004.exe. При появлении запроса имени пользователя указываю имя engineer (можно ввести любое другое имя), ввести свой пароль и подтвердить введенный пароль для указанной учетной записи:

Появилась строка приглашения терминала, ядро Ubuntu 20.04 установлено. Проверим правильность настройки режима WSL2, для этого в Windows Terminal выбираем закладку Windows PowerShell и вводим команду:

wsl -l -v

результат выполнения должен быть такой:

Настраиваем брандмауэр Microsoft Defender, т.е. отключаем его для общедоступной сети:

Настройка Ubuntu 20.04

В Windows Terminal снова выбираем закладку Command Prompt и устанавливаем обновления для Ubuntu 20.04. Для этого в командной строке вводим:

sudo apt update && sudo apt upgrade –y

Устанавливаем рабочий стол KDE Plasma:

sudo apt install kubuntu-desktop -y

установка занимает до 30 минут в зависимости от производительности компьютера и пропускной способности канала доступа в Internet, при появлении запроса установщика подтверждаем OK.
Устанавливаем русскую локализацию и словари Ubuntu 20.04. Для этого в командной строке вводим:

sudo apt install language-pack-ru language-pack-kde-ru -y
sudo apt install libreoffice-l10n-ru libreoffice-help-ru -y
sudo apt install hunspell-ru mueller7-dict -y
sudo update-locale LANG=ru_RU.UTF-8
sudo dpkg-reconfigure locales # примечание: выбираем ru_RU.UTF-8 UTF-8, см. скриншоты ниже.
sudo apt-get install --reinstall locales

Добавляем последнюю версию рабочего стола KDE Plasma:

sudo add-apt-repository ppa:kubuntu-ppa/backports
sudo apt update && sudo apt full-upgrade -y

Добавляем свой набор консольных приложений, например mc и neofetch:

sudo apt install mc neofetch -y

Проверяем, что получилось, вводим в командную строку neofetch, см. скриншот:

Редактируем конфигурационный файл WSL /etc/wsl.conf:

sudo nano /etc/wsl.conf

в открывшееся пустое окно текстового редактора копируем текст:

[automount]
enabled = true
root = /mnt
options = «metadata,umask=22,fmask=11»
mountFsTab = true
[network]
generateHosts = true
generateResolvConf = true
[interop]
enabled = true
appendWindowsPath = true

сохраняем изменения (Ctrl+O), подтверждаем операцию и выходим из текстового редактора (Ctrl+X).

Экспортируем настроенный образ Ubuntu-20.04 в созданный нами каталог \wsl. Для этого в Windows Terminal снова выбираем закладку Windows PowerShell и вводим команду:

wsl --export Ubuntu-20.04 c:\wsl\Ubuntu-plasma-desktop

созданный образ поможет нам автоматизировать операции запуска/переустановки настроенной Ubuntu 20.04, при необходимости позволит легко перенести на другой компьютер.

Подготовка bat-файлов и ярлыков на рабочий стол Windows

С помощью редактора Notepad++ создаем bat-файлы (обязательно в кодировке OEM-866 для корректного вывода символов кириллицы):
Файл Install-Ubuntu-20.04-plasma-desktop.bat — предназначен для автоматизации первоначальной установки созданного образа Ubuntu 20.04 на компьютере с уже настроенной подсистемой WSL2 и X-сервером. Если имя пользователя и пароль отличается от указанных в примере, то необходимо внести соответствующие изменения в этот bat-файл:

@echo off
wsl --set-default-version 2
cls
echo Ожидайте окончания установки дистрибутива Ubuntu-20.04...
wsl --import Ubuntu-20.04 c:\wsl c:\wsl\Ubuntu-plasma-desktop
wsl -s Ubuntu-20.04
cls
echo Дистрибутив Ubuntu-20.04 успешно установлен!
echo Не забудьте сменить учетную запись по умолчанию «root» на существующую учетную запись пользователя,
echo либо используйте предустановленную учетную запись «engineer», пароль: «password».
pause

Файл Reinstall-Ubuntu-20.04-plasma-desktop.bat — предназначен для переустановки подготовленного образа Ubuntu 20.04 на компьютере.

@echo off
wsl --unregister Ubuntu-20.04
wsl --set-default-version 2
cls
echo Ожидайте окончания переустановки дистрибутива Ubuntu-20.04...
wsl --import Ubuntu-20.04 c:\wsl c:\wsl\Ubuntu-plasma-desktop
wsl -s Ubuntu-20.04
cls
echo Дистрибутив Ubuntu-20.04 успешно переустановлен!
pause

Файл Set-default-user.bat — для установки пользователя «по умолчанию».

@echo off
set /p answer=Введите существующую учетную запись в Ubuntu (engineer):
c:\wsl\Ubuntu-20.04\ubuntu2004.exe config --default-user %answer%
cls
echo Учетная запись пользователя %answer% в Ubuntu-20.04 установлена по умолчанию!
pause

Файл Start-Ubuntu-20.04-plasma-desktop.bat — собственно запуск рабочего стола KDE Plasma.

@echo off
echo ===================================== Внимание! ============================================
echo  Для корректной работы GUI Ubuntu 20.04 в WSL2 необходимо использовать X Server.
echo  Примечание: в случае использования VcXsrv Windows X Server необходимо раскомментировать
echo  строки в файле Start-Ubuntu-20.04-plasma-desktop.bat, содержащие "config.xlaunch" и
echo  "vcxsrv.exe", и закомментировать все строки, содержащие "x410".
echo ============================================================================================
rem start "" /B "c:\wsl\vcxsrv\config.xlaunch" > nul
start "" /B x410.exe /wm /public > nul
start "" /B "c:\wsl\pulseaudio-1.1\bin\pulseaudio.exe" --use-pid-file=false -D > nul
c:\wsl\Ubuntu-20.04\Ubuntu2004.exe run "if [ -z \"$(pidof plasmashell)\" ]; then cd ~ ; export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0 ; setxkbmap us,ru -option grp:ctrl_shift_toggle ; export LIBGL_ALWAYS_INDIRECT=1 ; export PULSE_SERVER=tcp:$(grep nameserver /etc/resolv.conf | awk '{print $2}') ; sudo /etc/init.d/dbus start &> /dev/null ; sudo service ssh start ; sudo service xrdp start ; plasmashell ; pkill '(gpg|ssh)-agent' ; fi;"
rem taskkill.exe /F /T /IM vcxsrv.exe > nul
taskkill.exe /F /T /IM x410.exe > nul
taskkill.exe /F /IM pulseaudio.exe > nul

Файл Start-Ubuntu-20.04-terminal.bat — запуск графического терминала без рабочего стола KDE Plasma.

@echo off
echo ===================================== Внимание! ============================================
echo  Для корректной работы GUI Ubuntu 20.04 в WSL2 необходимо использовать X Server.
echo  Примечание: в случае использования VcXsrv Windows X Server необходимо раскомментировать
echo  строки в файле Start-Ubuntu-20.04-plasma-desktop.bat, содержащие "config.xlaunch" и
echo  "vcxsrv.exe", и закомментировать все строки, содержащие "x410".
echo ============================================================================================
rem start "" /B "c:\wsl\vcxsrv\config.xlaunch" > nul
start "" /B x410.exe /wm /public > nul
start "" /B "c:\wsl\pulseaudio-1.1\bin\pulseaudio.exe" --use-pid-file=false -D > nul
c:\wsl\Ubuntu-20.04\Ubuntu2004.exe run "cd ~ ; export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0 ; export LIBGL_ALWAYS_INDIRECT=1 ; setxkbmap us,ru -option grp:ctrl_shift_toggle ; export PULSE_SERVER=tcp:$(grep nameserver /etc/resolv.conf | awk '{print $2}') ; sudo /etc/init.d/dbus start &> /dev/null ; sudo service ssh start ; sudo service xrdp start ; konsole ; pkill '(gpg|ssh)-agent' ;"
taskkill.exe /F /T /IM x410.exe > nul
rem taskkill.exe /F /T /IM vcxsrv.exe > nul
taskkill.exe /F /IM pulseaudio.exe > nul

Также для удобства использования в каталоге \wsl подготавливаем ярлыки, указывающие на соответствующие bat-файлы. После чего содержимое каталога \wsl выглядит следующим образом:

Запуск рабочего стола KDE Plasma

Проверяем, что все подготовительные действия выполнены, пробуем запустить ярлык Plasma-desktop. Появляется запрос пароля, вводим пароль для учетной записи и… окно закрывается. В первый раз это нормально. Пробуем еще раз — и видим знакомую панель задач KDE Plasma. Настраиваем требуем внешний вид панели задач, на примере для удобства использования панель переносится в правую часть экрана и центрируется. Проверяем настройки локализации, при необходимости добавляем русский язык:

При необходимости выносим ярлыки для установленных linux-приложений на панель задач KDE Plasma.

Если Ubuntu 20.04 требует выйти из учетной записи пользователя для применения изменений в настройках, или Вам необходимо перезагрузить ОС, для этого в Windows Terminal введите команду:

wsl -d Ubuntu20.04 --shutdown

С помощью ярлыка Plasma-desktop или Konsole можно запустить GUI KDE Plasma Ubuntu 20.04. Например, установим с помощью Konsole графический редактор GIMP:

После окончания установки запускаем из Konsole графический редактор GIMP:

GIMP работает, что и требовалось проверить.
А вот как работают различные linux-приложения в KDE Plasma в WSL2:

настроенная панель задач KDE Plasma находится в правой части экрана. а видео в окне Firefox воспроизводится со звуком.

При необходимости можно настроить доступ к Ubuntu20.04 по SSH и RDP, для этого необходимо установить соответствующие службы командой:

sudo apt install ssh xrdp -y

примечание: для включения парольного доступа по SSH необходимо отредактировать файл /etc/ssh/sshd_config, а именно параметр PasswordAuthentication no необходимо установить в значение PasswordAuthentication yes, сохранить изменения и перезагрузить Ubuntu20.04.

При каждом запуске Ubuntu20.04 меняется внутренний ip-адрес, перед настройкой удаленного доступа необходимо уточнить текущий ip-адрес с помощью команды ip a:

Соответственно, этот ip-адрес необходимо внести в настройки сессий SSH и RDP перед запуском.
Вот так выглядит удаленный доступ по SSH с помощью MobaXterm:

А вот так выглядит удаленный доступ по RDP:

Использование X-сервера vcxsrv вместо x410

Запускаем и настраиваем vcxsrv, внимательно устанавливаем соответствующие флажки:

Сохраняем настроенную конфигурацию в каталоге \wsl\vcxsrv со стандартным именем config.xlaunch.

Редактируем bat-файлы Start-Ubuntu-20.04-plasma-desktop.bat и Start-Ubuntu-20.04-terminal.bat в соответствии с имеющимися в них инструкциями.

Запускаем ярлык Plasma-desktop, и вот что получаем:

Рабочий стол KDE Plasma полностью закрывает рабочий стол Windows, для переключения между окнами linux- и windows-приложений используем известную комбинацию клавиш Alt+Tab, что не совсем удобно.
Кроме того, выяснилась неприятная особенность X-сервера vcxsrv – он «падает» при запуске некоторых приложений, в частности того же GIMP или LibreOffice Writer. Возможно следует подождать, когда разработчики уберут замеченные «баги», но это не точно… Так что для получения приемлемых результатов лучше использовать X Server Microsoft x410.

Заключение

Все-таки надо отдать должное компании Microsoft, продукт WSL2 получился вполне рабочим, и на мой неискушенный взгляд — весьма удачным. И насколько мне известно, разработчики продолжают усиленно его «допиливать», и возможно — через годик-другой, данная подсистема предстанет во всей своей функциональной полноте.

If you have already read some of my WSL related articles, chances are that you are using and/or have discovered the potential of WSL 2. However, you might have experimented problems if tried to launch any graphical application within it.

Nowadays, a third-party app is required to run GUI apps, but Microsoft announced on Build 2020 that adding Linux GUI app native support to WSL is on their roadmap. I currently use VcXsrv Windows X Server for that purpose, and that’s the tool I will explain on this post. It’s an old open-source tool that updates quite frequently. You can check it on Sourceforge.

Installing and configuring VcXsrv

The first step is to download and run the .exe installer from Sourceforge. On the installation wizard, be sure to check the Disable access control option. This will save us time, avoiding some permission denied errors.

Be sure to disable access control

Click on image to enlarge

To be sure that this option is always checked, save the configuration to later launch VcXsrv using that config file.

How to save VcXsrv configuration

Click on image to enlarge

Setting permissions in Windows Firewall

Once VcXsrv is installed, we need to set the proper permissions on our firewall. Here, I assume you use the default Windows Firewall, but if you use a custom firewall (like a firewall provided by an antivirus), you may need to configure it manually.

When executing VcXsrv for the first time, a Windows Firewall pop-up should appear. Just be sure to give it permissions on both private and public networks.

Setting permissions in Windows Firewall

Click on image to enlarge

If the pop-up doesn’t appear, or if you gave it the wrong permissions by mistake, you can just change the permissions manually. To do so, open Windows Security app and go to Firewall & network protection -> Allow an app through firewall and ensure VcXsrv windows x server has both permissions.

Setting the DISPLAY env var

The last step is to set the DISPLAY environment variable on our WSL 2 Linux instance. We need to configure the Windows host’s IP address as DISPLAY (where the VcXsrv X server is running). Also, because WSL 2 network changes on every restart, so the Windows host’s IP does too, it’s needed to dynamically set this value on WSL2 launch.

We can use one of the following statements to dynamically set the DISPLAY env var to the correct value.

export DISPLAY="`grep nameserver /etc/resolv.conf | sed 's/nameserver //'`:0"
export DISPLAY="`sed -n 's/nameserver //p' /etc/resolv.conf`:0"
export DISPLAY=$(ip route|awk '/^default/{print $3}'):0.0

If you run one of the above commands on your Linux terminal, then, you should see and local IP address when reading the var value. Just use whatever of the above that works correctly on your machine.

export DISPLAY=....
echo $DISPLAY # Example working output: 192.168.128.1:0.0

Lastly, to ensure the DISPLAY env var is updated on every restart, we should add the chosen export statement to our ~/.bashrc file (if you are using bash as your command interpreter) or in ~/.zshrc (if using zsh instead).

Testing it out

Let’s test it! First, ensure the VcXsrv is running. You can check it by looking at the icons on your task bar. You should be able to see the VcXsrv icon if the server is up and running.

Click on image to enlarge

If you can’t see any icon, just start the server by double-clicking on the config file you saved when installing. It will launch VcXsrv server with the configuration on that file. You can open the file with a text editor, if you want to check the configuration inside.

If you have followed all the above steps, you should be able to execute GUI apps within WSL2 already. Let’s try with the x11-apps, some very low resources and low dependencies apps made for testing X server configurations.

sudo apt install x11-apps
xeyes
xcalc

GUI apps running on WSL2 Ubuntu

Click on image to enlarge

After executing the above commands, you should see two eyes following your mouse. Congratulations! You have successfully configured your WSL2 instance to run GUI apps.

Now what’s next? If you want to know how to write code inside WSL with VS Code and run containerized apps using Docker, I wrote about it too.

Troubleshooting

I particularly had an issue trying to use the default 0.0 display as my X server. Indeed, trying to use 0.0 will make the X server to crash on my Windows machine. It took me a few hours to realize, after searching on Google for a while and trying multiple different fixing options.

If you have the same problem, may you can fix it by using the 1.0 display instead. This is how I set the DISPLAY value.

export DISPLAY=$(ip route | awk '/default/ { print $3 }'):1.0

And this is my VcXsrv config.xlaunch config file.

<?xml version="1.0" encoding="UTF-8"?>
<XLaunch WindowMode="MultiWindow" ClientMode="NoClient" LocalClient="False" Display="1" LocalProgram="xcalc" RemoteProgram="xterm" RemotePassword="" PrivateKey="" RemoteHost="" RemoteUser="" XDMCPHost="" XDMCPBroadcast="False" XDMCPIndirect="False" Clipboard="True" ClipboardPrimary="True" ExtraParams="" Wgl="True" DisableAC="True" XDMCPTerminate="False"/>

I hope my article has helped you, or at least, that you have enjoyed reading it. I do this for fun and I don’t need money to keep the blog running. However, if you’d like to show your gratitude, you can pay for my next coffee with a one-time donation of just $1.00. Thanks!

Cover image for How to Install and Run X Server in Windows 11?

Run X Server in Windows 11 : In our previous articles, we have covered a lot about virtualization, hypervisor platforms, containers, and more. If you have a piece of code or testing an application without affecting the stability of the central system, then you can opt for Containers. If you want to run an entire system(same or different operating systems) inside a central system, then you can opt for Virtual machines and Native Hypervisor Platforms like Hyper-V in Windows 11. Then, why do we need X Server? and What is it?

Key Steps:

  • The most important step is to install WSL and set WSL 2 as the default version.
  • Once the WSL is installed, choose your Distro and install it.
  • Alongside, Install VcXsrv from the setup file and confgure it.
  • Setup the Environment variable in the WSL.
  • Finally, run a Linux Based GUI Application, you can find it running in the Graphical Interface in the Windows 11.

Why do we need X Server in Windows 11?

Well, there is a popular and interesting feature available in the Windows operating system, the Windows Subsystem for Linux (WSL) which allows users to run a Linux distribution directly on their Windows machine without needing a virtual machine or dual-boot setup. Here, is where the purpose of X Server pops in. An X Server allows Windows to display graphical applications that run on Unix-like operating systems such as Linux on your Windows desktop. This article will navigate through the detailed steps of How to install and effectively use X Server in Windows 11 OS. Let’s get started!

  • This first step of the process is to enable the Windows Subsystem for Linux. To do so, we have a detailed article on How to Enable Windows Subsystem for Linux in Windows 11. Please refer to it.

  • We have enabled Windows Subsystem for Linux. You can either enable WSL in Windows 11 using the Windows Features or directly using a command in the PowerShell. The choice is yours. To install WSL via PowerShell, open PowerShell , Run as Administrator , and then execute the following command. wsl --install

Install WSL on Windows 11

Install WSL on Windows 11

  • The next step is to ensure that we are running the WSL 2, the latest version. This version uses a real Linux kernel in a lightweight virtual machine , providing better performance and full compatibility with Linux system calls. Run the following command in the PowerShell. wsl --update
  • It’s time to restart the PC.
  • After the restart, let’s set the default WSL version as WSL 2 using the following command in the PowerShell. wsl --set-default-version 2

Set WSL 2 as the default version

Set WSL 2 as the default version

  • Once, the Windows Subsystem for Linux is installed, you will be presented with a list of Distros.

Finalize your Distro

Finalize your Distro

You can always run Windows Subsystem for Linux using the following command in the Windows Terminal. wsl

  • Choose your Distro accordingly. I am going with Ubuntu 24.04 LTS , as long-term support versions are more stable. Run the following command in the PowerShell. wsl --install -d Ubuntu-24.04

Install the Distro

Install the Distro

  • Ubuntu 24.04 LTS will now be installed.

Distro Installed

Distro Installed

  • The OS will open in the Windows Terminal , you have to set up your Unix username and root password. Please make sure to remember this information.

Enter username and password

Enter username and password

  • Let’s keep this aside, now, we will install a third-party X Server Application. The X Server runs on your computer and manages the display, handling input from the mouse, keyboard, and other peripherals. When you run Linux applications with a graphical interface (like a text editor or a file manager) on a Linux environment within Windows, the X Server on Windows handles the display of these applications. Without an X Server, you can only run command-line (CLI) applications in WSL. You can find X Server software for Windows from several sources, including official websites of popular X Server tools. Some of the most commonly used are
  1. Xming
  2. VcXsrv
  3. MobaXterm
  4. Cygwin/X

Each of these software has its strengths, so you can choose the one that best suits your needs based on factors like ease of use, additional features, and your specific use case.

VcXsrv:

If you’re looking for a balance between ease of use, configuration, and performance , I would recommend VcXsrv. It is an open-source X Server that seamlessly connects with WSL, making it a popular choice among the Developer communities. It is actively maintained and offers a good level of customization for advanced users. Let’s download VcXsrv via its SourceForge page.

  • It’s time to install VcXsrv. Install the downloaded setup file.

Click Next

Click Next

  • Once installed, you can find the application shortcut on the Desktop. Open the Application.
  • Choose Multiple Windows as Default Settings and then click Next.

Choose Multiple Windows

Choose Multiple Windows

  • In the Client Startup , by default, “ Start no Client ” would be selected. This option will just start the X Server. You will be able to start local clients later. Click Next.

Client Startup

Client Startup

  • In the Extra Settings , leave the default options and proceed with Next.

Extra Settings

Extra Settings

  • Finally, click Finish to complete the VcXsrv setup.

Finish

Finish

  • You can find the application running in the background in the system tray.

X Server running in the system tray

  • Let’s get back to the PowerShell where the WSL is installed. We now have WSL, and X Server configured.
  • To set up the Display Environment Variable , run the following command. This command will ensure WSL where to display GUI Applications. You can add this line to your .bashrc or .zshrc to run it automatically when you open a terminal. export DISPLAY=$(grep -oP "(?<=nameserver ).+" /etc/resolv.conf):0.0

Setup the Display Variable

Setup the Display Variable

  • Finally, it is time to test our setup. Let’s install a Linux GUI Application, say, Gedit , and run it. The following command will install Gedit on your WSL environment in the Windows Terminal
    sudo apt update
    sudo apt install gedit

sudo apt install gedit

sudo apt install gedit

  • Simply execute the command gedit to run the application.

Run Gedit

Run Gedit

  • You can find gedit application opening in GUI inside your WSL Environment on Windows 11 OS. That’s all Folks! We did it!

gedit running in the GUI in Windows 11

gedit running in the GUI in Windows 11

Information on the Go!

WSLg (Windows Subsystem for Linux GUI) is an extension of WSL 2 that allows you to run Linux GUI (Graphical User Interface) applications directly on Windows 10 and 11, without the need for a third-party X Server like VcXsrv and any additional configurations.

Take away:

While Windows Subsystem for Linux GUI (WSLg) is sufficient and preferred for running Linux GUI apps on Windows due to its tight integration, ease of use, and performance benefits , these third-party X Servers offer customization, compatibility, or advanced configurations. Setting up and running an X Server on Windows 11 opens possibilities for users looking to run Linux GUI applications natively within the Windows environment. By enabling WSL (Windows Subsystem for Linux) and using tools like VcXsrv , you can seamlessly integrate Linux graphical applications into your workflow without the need for a full virtual machine or dual boot. This setup not only enhances productivity but also bridges the gap between Windows and Linux, giving you the best of both operating systems. Happy Dual Computing! Peace out!

Setup WSL2 Ubuntu 22.04 development environment with GUI and audio

GUI

2 GUI options:

  • WSLg by Microsoft(recommended)
  • VcXsrv X server

WSLg (recommended)

C:\Users<UserName>.wslconfig

[wsl2]
;enable WSLg
guiApplications=true

memory=10GB
swap=8GB

C:\Users<UserName>.wslgconfig

[system-distro-env]
;scale 2x
WESTON_RDP_DEBUG_DESKTOP_SCALING_FACTOR=200

VcXsrv

First of all, download and install VcXsrv. Find vcxsrv.exe, right click -> properties -> compatibility mode > override high DPI > Application.

Write a PowerShell script to start VcXsrv and WSL: C:\Users<UserName>\start-wsl.ps1

# Start "vcxsrv" if it's not running
if (Get-Process -Name vcxsrv -ErrorAction SilentlyContinue) {
    Write-Host "VcXsrv is running."
} else {
    Write-Host "VcXsrv is not running. Starting"
    Start-Process -FilePath "C:\Program Files\VcXsrv\vcxsrv.exe" -ArgumentList "-ac -multiwindow -clipboard -noprimary -wgl"
}
# Start windows terminal
wt

Create a shortcut on desktop to start it: C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -command "& '%userprofile%\start-wsl.ps1'". Remember to change Windows terminal settings and set WSL linux distro as the default profile.

Double-click the shortcut to start wsl terminal. In .bashrc, add:

# VcXsrv
export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}'):0.0
export LIBGL_ALWAYS_INDIRECT=1

# Scale UI(causes problem with WSLg)
export GDK_SCALE=2

Run source ~/.bashrc and try start a GUI app, such as: xfce4-terminal. Note that VcXsrv needs to be running before starting WSL.

References:

  • On high resolution monitor, X apps are blurry
  • VcXsrv Windows X Server Wiki

Fcitx

Install fcitx5: sudo apt install fcitx5 fcitx5-chinese-addons

In ~/.bashrc, add

# Fcitx
export INPUT_METHOD=fcitx
export QT_IM_MODULE=fcitx
export GTK_IM_MODULE=fcitx
export XMODIFIERS=@im=fcitx
if ! pgrep dbus-launch &> /dev/null; then
  dbus-launch --sh-syntax --exit-with-session > /dev/null
fi
if ! pgrep fcitx5 &> /dev/null; then
  daemonize -e /tmp/fcitx5.log -o /tmp/fcitx5.log -p /tmp/fcitx5.pid -l /tmp/fcitx5.pid -a /usr/bin/fcitx5 --disable=wayland
fi

fcitx5 will be automatically started everytime you start WSL.

PulseAudio

Download PulseAudio for windows: https://www.freedesktop.org/wiki/Software/PulseAudio/Ports/Windows/Support/. Extract it to C:\pulseaudio

Create a config.pa file at C:\pulseaudio\etc\pulse\config.pa

load-module module-native-protocol-tcp auth-ip-acl=127.0.0.1;172.16.0.0/12
load-module module-esound-protocol-tcp auth-ip-acl=127.0.0.1;172.16.0.0/12
load-module module-waveout sink_name=output source_name=input record=0

Download nssm from https://nssm.cc/download. Extract and copy nssm.exe to C:\pulseaudio\bin\nssm.exe. Open a cmd or PowerShell at C:\pulseaudio\bin\, and run nssm.exe install PulseAudio for cmd, or .\nssm.exe install PulseAudio for PowerShell. In the dialogue, set:

  • Path: C:\pulseaudio\bin\pulseaudio.exe
  • Startup directory: C:\pulseaudio\bin
  • Arguments: -F C:\pulseaudio\etc\pulse\config.pa –exit-idle-time=-1
  • (optional) set a display name in “Details” tab

Click “Install” to install PulseAudio as a windows service. Win + R and run services.msc to review it. Now pulseaudio will automatically start on each windows launch.

In .bashrc, add:

# PulseAudio
export HOST_IP="$(ip route |awk '/^default/{print $3}')"
export PULSE_SERVER="tcp:$HOST_IP"

Forwarding WSL ports to Windows

First of all, make sure ifconfig is installed in your WSL Linux distro. Then write a PowerShell script for starting port forwarding, and save it to C:\Users<User>\Bridge-WslPorts.ps1:

$ports = @(80, 443, 8080, 3000, 3128, 5432);

$wslAddress = bash.exe -c "ifconfig eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'"

if ($wslAddress -match '^(\d{1,3}\.){3}\d{1,3}$') {
  Write-Host "WSL IP address: $wslAddress" -ForegroundColor Green
  Write-Host "Ports: $ports" -ForegroundColor Green
}
else {
  Write-Host "Error: Could not find WSL IP address." -ForegroundColor Red
  exit
}

$listenAddress = '0.0.0.0';

foreach ($port in $ports) {
  Invoke-Expression "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$listenAddress";
  Invoke-Expression "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$listenAddress connectport=$port connectaddress=$wslAddress";
}

$fireWallDisplayName = 'WSL Port Forwarding';
$portsStr = $ports -join ",";

Invoke-Expression "Remove-NetFireWallRule -DisplayName '$fireWallDisplayName'";
Invoke-Expression "New-NetFireWallRule -DisplayName '$fireWallDisplayName' -Direction Outbound -LocalPort $portsStr -Action Allow -Protocol TCP";
Invoke-Expression "New-NetFireWallRule -DisplayName '$fireWallDisplayName' -Direction Inbound -LocalPort $portsStr -Action Allow -Protocol TCP";

Open PowerShell and register a scheduled task to run the script on Windows boot:

$a = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File `"C:\Users\<User>\Bridge-WslPorts.ps1`" -WindowStyle Hidden -ExecutionPolicy Bypass"
$t = New-ScheduledTaskTrigger -AtLogon
$s = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$p = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest
Register-ScheduledTask -TaskName "WSL2PortsBridge" -Action $a -Trigger $t -Settings $s -Principal $p

Now port forwarding will be started each time you start Windows.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows update error 8024200d
  • Как открыть доступ к rdp windows 10
  • Ati radeon 9200 драйвера для windows 7 32 bit
  • Прога для отключения обновления в windows 10
  • Служба беспроводной связи windows не запущена на этом компьютере что делать