Windows subsystem for linux how to install

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Appearance settings

Last Updated :
04 Dec, 2023

The Windows Subsystem for Linux (WSL) lets developers run a GNU/Linux environment on Windows, without the overhead of a traditional virtual machine or dual boot setup. This incorporates Linux-like functionality on Windows OS without the overhead of running another OS in parallel, therefore, reducing resource consumption. This makes WSL a go-to choice for people wanting to switch between the two Operating Systems or ones who want to get Linux-like functionality in their Windows OS. WSL2 is a new version of the architecture that allows you to use Linux on top of Windows 10 natively and replaces WSL. In this article, you will learn how to install WSL2 on Windows 10. 

Setup of Windows Subsystem for Linux:

Here are some steps to install Windows Subsystem for Linux. We are installing WSL on Windows 10.

Step 1: Open the start menu in Windows by pressing the [Win] key or clicking the bottom right icon of the Windows desktop.

Start menu for Windows Subsystem for Linux

Step 2: Type cmd. A result similar to this would appear.

Opening cmd to install Windows Subsystem for Linux

Step 3: Click on the Run as administrator option on the right side of the taskbar

Windows Subsystem for Linux

Run as administrator cmd

Step 4: A new window would have appeared similar to this

Windows Subsystem for Linux

cmd

Step 5: Type the following command and press Enter to install Windows Subsystem for Linux.

wsl --install
Windows Subsystem for Linux

`wsl — install` command to Install Windows Subsystem for Linux

Step 6: The WSL2 installation process has begun. It will install the Linux Kernel during this process. After the process has been completed the user gets acknowledged that Windows Subsystem for Linux (WSL) has been installed.

Windows Subsystem for Linux

Windows Subsystem for Linux (WSL) has been installed

Step 7: Now WSL has been successfully installed onto the Windows 10 Operating System. Now restart your Operating System. Upon restarting you could use Windows Subsystem for Linux (WSL2). 

Note: By default, the Ubuntu distribution gets installed in Windows Subsystem for Linux (WSL2). If you want any specific distribution, you could get so by replacing the command.

wsl --install
wsl --install -d DIST

Where DIST is the name of the distribution you are wanting to install. 

Enabling Virtual Machine:

As mentioned earlier, WSL2 is a small virtual machine, so Windows has to accommodate it. If this is already enabled, skip the process and restart your PC to make sure it’s ready for installation. The easiest way to do this is with PowerShell. As an administrator, he opens PowerShell and enters the following command:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Now you can reboot your PC and be able to do anything on WSL.

Installing Linux Packages:

You can also install Linux packages here. Popular apt and apt-get commands are available. For example, let’s install the htop package on this version of Linux and see what happens. First, open the Linux terminal and run the following command to update the APT package repository cache.

Step 1: Type the following command:

$ sudo apt update
update apt in Linux

update apt in Linux

Step 2: Now install the htop package using the following command.

$ sudo apt install htop
Installing htop in Linux

Installing htop in Linux

Step 3: After successfully installing the htop package, we can simply run and execute htop by following command:

using htop command

using htop command

Conclusion:

In this article we discussed the installation of Windows Subsystem for Linux (WSL) on Windows 10 streamlines which incorporation of a GNU/Linux environment without the need for virtual machines or dual boot configurations. WSL optimizes resource usage, making it ideal for users transitioning between operating systems or seeking Linux-like functionality on their Windows OS. The article guides users through the straightforward installation of WSL2, the latest version, offering native Linux usage on Windows 10. It emphasizes the simplicity of the process, allowing users to choose specific Linux distributions like Ubuntu during setup. Enabling the Virtual Machine platform using PowerShell ensures a smooth experience. The article also explores installing Linux packages through WSL, showcasing its compatibility and functionality. Following these steps empowers users to seamlessly integrate Linux capabilities into their Windows environment, enhancing their development workflow.

Среда Windows Subsystem for Linux (WSL) позволяет запускать нативные приложения, писать скрипты, выполнять команды и скрипты Linux непосредственно из Windows без использования эмуляторов или развертывания выделенных виртуальных машин. Актуальной версией среды является WSL 2, в которой используется полноценное ядро Linux (версия ядра 5.15) и обеспечивает полную совместимость с системными вызовами. Образ ядра Linux в WSL представляет собой легкую виртуальную машину, для запуска которой не нужно устанавливать полноценную роль Hyper-V.

Содержание:

  • Как установить Windows Subsystem for Linux (WSL2)?
  • WSL: Установка дистрибутива Linux в Windows
  • Команды для управления WSL в Windows
  • Использование Linux в среде WSL

Вы можете запустить WSL 2:

  • Во всех версиях Windows 10, начиная с 1903, а также в Windows 11 и Windows Server 2022;
  • В настройка BIOS/UEFI компьютера должна быть включена поддержка аппаратной виртуализации: Intel VT (Intel Virtualization Technology) или AMD-V (SVM Mode).

Как установить Windows Subsystem for Linux (WSL2)?

Компонент WSL по умолчанию отключен в Windows. Современных дистрибутивах Windows 10 и Windows 11 для установки среды WSL достаточно выполнить команду:

wsl --install

Этак команда автоматически включит все необходимые компоненты Windows, необходимые для работы WSL, установить обновление ядра Linux для WSL2, загрузит дистрибутив Ubuntu (по-умолчанию) и установит его в WSL.

команда для быстрой установки wsl в windows 10 и 11

Осталось перезагрузить компьютер, и вы можете запускать среду WSL!

Вы можете установить для WSL другой дистрибутив Linux. Выведите список доступных дистрибутивов:

wsl --list --online

Укажите имя дистрибутива Linux, который установить в WSL. Например:

wsl --install -d kali-linux

список доступных дистрибутивов Linux для WSL

Если в BIOS/UEFI компьютера не включена виртуализация, при установке WSL вы получите ошибку:

Installation failed with error 0x80070003 or error 0x80370102” it means that Bios Level Virtualization is not enabled on your computer.

Вы можете установить WSL2 в Windows вручную. Для этого придется вручную последовательно выполнить все этапы, который команда wsl —install запускала автоматически:

  1. Установить WSL
  2. Включить компонент виртуалзации VirtualMachinePlatform
  3. Установить ядро WSL 2
  4. Скачать и установить дистрибутив Linux для WSL

Сначала установите следующие компоненты Windows:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform

установить компонент wsl в windows вручную

Перезагрузите компьютер.

Скачаем и установим обновление ядра Linux для WSL2 (WSL2 Linux kernel update package for x64 machines — https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi). Можете скачать пакет вручную или с помощью PowerShell:

Invoke-WebRequest -Uri https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi -OutFile "$($env:userprofile)\Downloads\wsl_update_x64.msi" -UseBasicParsing
Invoke-Item "$($env:userprofile)\Downloads\wsl_update_x64.msi"
rm "$($env:userprofile)\Downloads\wsl_update_x64.msi"

windows subsyste for linux update setup

Еще раз перезагрузите компьютер и назначьте версию WSL 2 в качестве среды по-умолчанию:

wsl --set-default-version 2

wsl2 назначить по умолчанию

WSL: Установка дистрибутива Linux в Windows

После того, как ядро WSL установлено в Windows, вы можете установить один или несколько дистрибутивов Linux на компьютер.

Можно установить пакет с дистрибутивом Linux через Microsoft Store. Доступны следующие дистрибутивы:

  • Ubuntu
  • Debian
  • Kali Linux
  • OpenSUSE
  • Oracle Linux
  • SUSE Linux Enterprise Server
  • Fedora

Найдите нужную версию дистрибутива в Store и установите ее, нажав кнопку Получить (Get).

скачать образ linux для wsl из microsoft store

Если у вас отключен Windows Store, вы хотите установить дистрибутив WSL в Core редакции Windows Server или вам нужно установить WSL на Изолированном от интернета компьютере (оффлайн), вы можете скачать дистрибутив Ubuntu с помощью PowerShell командлета Invoke-WebRequest:

Invoke-WebRequest https://aka.ms/wslubuntu2204 -OutFile ubuntu-2204.appx –UseBasicParsing

Установите пакет для WSL с помощью:

Add-AppxPackage .\ubuntu-2204.appx

После окончания установки появится окно, в котором вам будет предложено указать имя пользователя и пароль для вашего дистрибутива.

задать пароль для wsl

После установки вы можете в меню Пуск появится отдельная программа для запуска Linux.

Также вы можете запустить ваш Linux из отдельной вкладки Windows Terminal или с помощью команды
wsl
.

Команды для управления WSL в Windows

Рассмотрим основные команды для управления ядром и дистрибутивами Linux в WSL.

Проверить текущую версию ядра WSL:

wsl --version

версия wsl в windows

Обновить ядро WSL вручную:

wsl --update

Откатится к предыдущему ядру WSL:

wsl --update rollback

Вывести список установленных версий Linux:

wsl --list

Вывести дистрибутив Linux, который используется по-умолчанию:

wsl --status

Дистрибутив Linux по-умолчанию в WSL можно изменить:

wsl --setdefault Ubuntu

Запустить определенный дистрибутив в WSL:

wsl -d kali-linux

Завершить среду WSL:

wsl --shutdown

Можно войти в WSL Ubuntu под root и сбросить пароль:
ubuntu config --default-user root
Passwd

Вернуть пользователя по умолчанию
ubuntu config --default-user your_username

Для настройки параметров WSL и дистрибутивов Linux используются конфиг файлы:

  • wsl.conf – файл с настройками конкретного дистрибутива Linux (находится в директории /etc)
  • .wslconfig – глобальные настройки WSL, которые применяются ко всем дистрибутовам (находится в профиле пользователя в
    %UserProfile%
    )

Например, если вы хотите ограничить использование оперативной памяти и CPU компьютера дистрибутивами Linux в WSL, создайте такой файл
%UserProfile%\.wslconfig
:

[wsl2]
memory=2GB
processors=2

Использование Linux в среде WSL

Дистрибутив Linux, установленный в WSL является полноценной операционной системой. Поэтому после установки рекомендуется выполнить обновление пакетов. Для Ubuntu выполните команду:

$ sudo apt-get update && sudo apt-get upgrade -y

обновление пакетов в ubuntu wsl

Файловая система вашего дистрибутива Linux хранится в профиле пользователя в виде VHDX файла. Например, виртуальный диск Ubuntu хранится в папке
%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState

файл vhdx образа диска в linux wsl

Файловая система Linux в WSL монтируется в виде сетевой папки прямо в проводник Windows.

Также для прямого доступа к файлам WSL из Windows можно использовать UNC путь. Например:

notepad \\wsl$\Ubuntu\sysops\home\1122.txt

В свою очередь локальные диски Windows монтируются в WSL в папку mnt. Вывести список файлов папок на диске C:

wsl
ls /mnt
ls/mnt/c

просмот файлов на диске windows из wsl

Другие примеры запуска Linux команд из Windows:
dir | wsl grep Sa
wsl ls ‑la > 123.txt
wsl ls ‑la /proc/cpuinfo
wsl ls ‑la “/mnt/c/Program Files”

Вы можете установить любые пакеты в Linux. Например, установите файловый менеджер Midnight Commander:

$ sudo apt-get install mc

В современной версии WSL 2 вы можете запускать из Windows любые приложения Linux с графическим интерфейсом (X11 и Wayland). Например, установите графический редактор:

$ sudo apt install gimp -y

Чтобы запустить его из Windows просто выполните команду:

wsl gimp

Recently Microsoft added a list of new features to the well-received WSL (Windows Subsystem for Linux) named “WSL 2”. This new version of WSL enables features such as increased file IO performance and full system call compatibility and is not enabled by default.

In this guide, we will install, configure WSL2 on our Windows 10 workstation, as well as install a Linux distribution on it.

Prerequisites

To install WSL 2, you must be running Windows 10. The following versions and builds are supported:

  • For x64 systems: Version 1903 or higher, with Build 18362 or higher.
  • For ARM64 systems: Version 2004 or higher, with Build 19041 or higher.
  • Builds lower than 18362 do not support WSL 2. Use the Windows Update Assistant to update your version of Windows.

Step #1 — Enable the “Windows Subsystem for Linux” feature

To install WSL (any version) to Windows 10 we must first enable the “Windows Subsystem for Linux” feature in Windows 10. This can be done in two ways:

using Powershell

To enable the “Windows Subsystem for Linux” open Powershell and type the below command:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

using GUI

Go to Control Panel -> Programs & Features -> Turn Windows features on or off, then find and enable “Windows Subsystem for Linux” like the below screenshot:

Windows features #1

Step #2 — Enable the “Virtual Machine Platform” feature

Next, we need to enable the “Virtual Machine Platform” feature. This can be done in two ways:

Powershell

To enable the “Virtual Machine Platform” open Powershell and type the below command:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

GUI

Go to Control Panel -> Programs & Features -> Turn Windows features on or off, then find and enable “Virtual Machine Platform” like the below screenshot:

Windows features #2

Step #3 — Download the “Linux kernel update” package

Microsoft provides the Linux kernel update package, which is needed to support the added feature set of WSL 2. You can find the package at the following links:

WSL2 Linux kernel update package for x64 machines

WSL2 Linux kernel update package for Arm64 machines

If you’re not sure what kind of machine you have, open Command Prompt or PowerShell and enter:

systeminfo | find "System Type".

After downloading the package for your machine kind, run the update package downloaded in the previous step. (Double-click to run — you will be prompted for elevated permissions, select ‘yes’ to approve this installation.)

Once the installation is complete, restart your machine to complete the WSL install and update to WSL 2.

Step #4 — Set WSL 2 as your default version

As you can have both versions of WSL installed, it is always nice to set the default version of newly installed distributions to WSL2. To do so, open Powershell and type:

wsl --set-default-version 2

This will ensure that the extra features are enabled on the Linux distributions you’re going to download and install in the future, but what about the already installed distros?

If you have recently updated WSL to WSL2, chances are your already installed distributions are using WSL 1 features. To check, open a Powershell window and type:

wsl --list --verbose

This will return with a list of installed distributions, along with the Version of WSL enabled on those. To update your installed distributions to the newer feature set, open a Powershell window and type:

wsl --set-version <distribution name> <versionNumber>

Step #5 — Install your Linux distribution of choice

Now after we’ve set-up all the needed dependencies for WSL 2 and enabled its feature set by default it is time to download and use your distribution of choice.

The following lists all compatible and available distributions in the Microsoft store at the time of writing:

  • Ubuntu 16.04 LTS
  • Ubuntu 18.04 LTS
  • Ubuntu 20.04 LTS
  • openSUSE Leap 15.1
  • SUSE Linux Enterprise Server 12 SP5
  • SUSE Linux Enterprise Server 15 SP1
  • Kali Linux
  • Debian GNU/Linux
  • Fedora Remix for WSL
  • Pengwin
  • Pengwin Enterprise
  • Alpine WSL

To install any of those, go to the Win10 app store “Microsoft Store” and search for them. After you find your selected distribution, click on “Get” to start the download.

The first time you launch a newly installed Linux distribution, a console window will open and you’ll be asked to wait for a minute or two for files to de-compress and be stored on your PC. All future launches should take less than a second.

You will then need to create a user account and password for your new Linux distribution.

CONGRATULATIONS! You’ve successfully installed and set up a Linux distribution that is completely integrated with your Windows operating system!

Now if you like to test things out and restore the distribution to its original settings, you can uninstall it completely from the Settings -> Apps -> Apps & Features and re-install.

Thank you for reading! Be sure to share this post if you found it helpful and don’t hesitate to chat with me about it!

This post was first published on Stathis’ log book by Stathis Athanasiadis aka StatAth

How to Install WSL2 (Windows Subsystem for Linux 2) on Windows 10

Linux is a widely used operating system and is quite important for developers.

There are times when you might need to have both operating systems – Windows and Linux – either for work, study, or even just experimentation.

Luckily, Windows provides a convenient utility for using Linux along side Windows. This utility is called WSL (Windows Subsystem for Linux). Its recent version is WSL2 and in this guide we’ll discuss it in detail.

We will cover:

  • What is WSL2 and what are its advantages?
  • How to install WSL2 on Windows 10 with default settings.
  • How to install WSL2 with a specific Linux distro.

What is WSL2?

Windows Subsystem for Linux provides a compatibility layer that lets you run Linux binary executables natively on Windows.

WSL2 (Windows Subsystem for Linux version 2) is the latest version of WSL. WSL2 architecture replaces WSL’s architecture by using a lightweight virtual machine. In the new version, you can run an actual Linux kernel which improves overall performance.

Advantages of using WSL

There are some advantages of WSL over a traditional VM setup:

  • The setup for WSL is simple and not time consuming.
  • It is light weight compared to VMs where you have to allocate resources from the host machine.
  • You don’t need to install any ISO or virtual disc image for Linux machines which tend to be heavy files.
  • You can use Windows and Linux side by side.

First, enable the windows subsystem for Linux option in settings.

  • Go to Start. Search for «Turn Windows features on or off.»
  • Check the option Windows Subsystem for Linux.

Image

Turn Windows features on or off.

Next, open your command prompt and provide the installation commands.

  • Open Command Prompt as an administrator.

Image

  • Run the command below:
wsl --install

Image

Note: By default, Ubuntu will be installed. But you can install any distro of your choice. We’ll see later how.

Once installation is complete, you’ll need to reboot your Windows machine. So, restart your Windows machine.

Image

After restarting, you might see a window like this:

Image

Once installation of Ubuntu is complete, you’ll be prompted to enter your username and password.

Image

And, that’s it! You are ready to use Ubuntu.

Launch Ubuntu by searching from the start menu.

Image

And here we have our Ubuntu instance launched.

Image

Ubuntu launched via WSL2

How to Install a Specific Linux Distro

If you use the default method as shown above, Ubuntu will be installed. You can find the available list of distros by running the below command on the Windows command prompt:

wsl --list --online

Image

List the online available Linux distros

To install a specific distro, use the command below:

wsl --install -d DISTRO-NAME

For example, to install Debian, the command would be modified as follows:

wsl --install -d Debian

Follow the prompts and the specific distribution will be installed.

Tip: You can also look for updates as shown below:

wsl --update

Check the status by launching Windows PowerShell.

Image

Check status of WSL

Wrapping up

WSL is a great utility to use Linux on a native Windows machine. It gives room for learning specially to those who are just starting out. I hope you found this article helpful.

Let’s connect on Twitter!

Read my other posts here.

Let’s chat on Discord.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Обои windows 11 обои для телефона
  • Как установить виртуальную машину на windows 10 домашняя
  • Виртуальный джойстик на планшете windows
  • Запуск dos игр на windows 10
  • Настройка nfs клиента windows