How to enable wsl
How to enable wsl
Manual installation steps for older versions of WSL
You must first enable the «Windows Subsystem for Linux» optional feature before installing any Linux distributions on Windows.
Open PowerShell as Administrator (Start menu > PowerShell > right-click > Run as Administrator) and enter this command:
To update to WSL 2, you must be running Windows 10.
Builds lower than 18362 do not support WSL 2. Use the Windows Update Assistant to update your version of Windows.
To check your version and build number, select Windows logo key + R, type winver, select OK. Update to the latest Windows version in the Settings menu.
Before installing WSL 2, you must enable the Virtual Machine Platform optional feature. Your machine will require virtualization capabilities to use this feature.
Open PowerShell as Administrator and run:
Restart your machine to complete the WSL install and update to WSL 2.
Download the latest package:
Open PowerShell and run this command to set WSL 2 as the default version when installing a new Linux distribution:
Open the Microsoft Store and select your favorite Linux distribution.
The following links will open the Microsoft store page for each distribution:
From the distribution’s page, select «Get».
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.
CONGRATULATIONS! You’ve successfully installed and set up a Linux distribution that is completely integrated with your Windows operating system!
Troubleshooting installation
If you run into an issue during the install process, check the installation section of the troubleshooting guide.
Downloading distributions
There are some scenarios in which you may not be able (or want) to, install WSL Linux distributions using the Microsoft Store. You may be running a Windows Server or Long-Term Servicing (LTSC) desktop OS SKU that doesn’t support Microsoft Store, or your corporate network policies and/or admins do not permit Microsoft Store usage in your environment. In these cases, while WSL itself is available, you may need to download Linux distributions directly.
If the Microsoft Store app is not available, you can download and manually install Linux distributions using these links:
If you prefer, you can also download your preferred distribution(s) via the command line, you can use PowerShell with the Invoke-WebRequest cmdlet. For example, to download Ubuntu 20.04:
You also have the option to use the curl command-line utility for downloading. To download Ubuntu 20.04 with curl:
In this example, curl.exe is executed (not just curl ) to ensure that, in PowerShell, the real curl executable is invoked, not the PowerShell curl alias for Invoke-WebRequest.
Once your distribution is installed, follow the instructions to create a user account and password for your new Linux distribution.
Install Windows Terminal (optional)
Using Windows Terminal enables you to open multiple tabs or window panes to display and quickly switch between multiple Linux distributions or other command lines (PowerShell, Command Prompt, Azure CLI, etc). You can fully customize your terminal with unique color schemes, font styles, sizes, background images, and custom keyboard shortcuts. Learn more.
Установка Linux на Windows с помощью WSL
В этом руководстве показано, как установить дистрибутив Linux (например, Ubuntu, OpenSUSE, Kali, Debian, Arch Linux и другие) с помощью подсистемы Windows для Linux. WSL позволяет использовать такие средства Linux, как Bash или Grep, полностью интегрированные с такими инструментами Windows, как PowerShell или Visual Studio Code, не выполняя двойную загрузку.
Предварительные требования
Вам следует использовать Windows 10 версии 2004 и выше (сборка 19041 и выше) или Windows 11.
Чтобы проверить версию и номер сборки Windows, нажмите клавиши WINDOWS+R, введите winver и щелкните ОК. Вы можете выполнить обновление до последней версии Windows, выбрав Пуск>Параметры>Центр обновления Windows>Проверить наличие обновлений.
Команда установки WSL
Теперь вы можете установить все необходимые компоненты для запуска подсистемы Windows для Linux (WSL), введя эту команду в PowerShell от имени администратора или командной строке Windows, а затем перезапустив компьютер.
При первом запуске недавно установленного дистрибутива Linux откроется окно консоли. Вам будет предложено подождать, пока файлы будут распакованы и сохранены на компьютере. Все будущие запуски должны занимать меньше секунды.
Изменение установленного дистрибутива Linux по умолчанию
Если во время установки возникла проблема, см. раздел Установка руководства по устранению неполадок.
Настройка сведений о пользователе Linux
После установки WSL необходимо создать учетную запись пользователя и пароль для установленного дистрибутива Linux. Дополнительные сведения см. в статье Рекомендации по настройке среды разработки WSL.
Советы и рекомендации
Мы рекомендуем использовать наше пошаговое руководство Рекомендации по настройке среды разработки WSL. В нем описано, как настроить имя пользователя и пароль для установленных дистрибутивов Linux, использовать основные команды WSL, установить и настроить Терминал Windows, настроить управление версиями Git, отредактировать код и выполнить отладку с помощью удаленного сервера VS Code. Кроме того, в руководстве приведены рекомендации по хранению файлов, настройке базы данных, подключению внешнего диска, настройке ускорения GPU и пр.
Проверьте, какая версия WSL запущена
Дополнительные сведения см. в руководстве по основным командам для WSL.
Обновление версии WSL 1 до WSL 2
Список команд WSL см. в справочнике по командам для WSL; рекомендации по использованию одной из версий в рабочем сценарии см. в статье со сравнением WSL 1 и WSL 2; для получения общих сведений о настройке надлежащего рабочего процесса разработки с помощью WSL ознакомьтесь с рекомендациями по настройке среды разработки WSL.
Способы запуска нескольких распределений Linux с помощью WSL
WSL поддерживает запуск неограниченного количества различных распределений Linux. Сюда входит выбор распределений из Microsoft Store, импорт настраиваемого распределенияили создание собственного пользовательского распределения.
Существует несколько способов запуска распределений Linux после их установки:
Хотите испытать новейшие предварительные версии функций WSL?
Чтобы поработать с самыми последними функциями или обновлениями для WSL, присоединитесь к Программе предварительной оценки Windows. Когда вы присоединитесь к участникам Программы предварительной оценки Windows, вы сможете выбрать канал для получения предварительных сборок в меню параметров Windows и будете автоматически получать предварительные версии функций и обновления для WSL, связанные с этой сборкой. Можно выбрать одно из следующих значений.
Install Linux on Windows with WSL
This guide will show you how to install a Linux distribution (such as Ubuntu, OpenSUSE, Kali, Debian, Arch Linux, and more) using the Windows Subsystem for Linux. WSL enables you to use Linux tools, like Bash or Grep, completely integrated with Windows tools, like PowerShell or Visual Studio Code, with no need to dual-boot.
Prerequisites
You must be running Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11.
To check your Windows version and build number, select Windows logo key + R, type winver, select OK. You can update to the latest Windows version by selecting Start > Settings > Windows Update > Check for updates.
If you’re running an older build, or just prefer not to use the install command and would like step-by-step directions, see WSL manual installation steps for older versions.
Install WSL command
You can now install everything you need to run Windows Subsystem for Linux (WSL) by entering this command in an administrator PowerShell or Windows Command Prompt and then restarting your machine.
This command will enable the features necessary to run WSL and install the Ubuntu distribution of Linux. (This default distribution can be changed).
The first time you launch a newly installed Linux distribution, a console window will open and you’ll be asked to wait for files to de-compress and be stored on your machine. All future launches should take less than a second.
Change the default Linux distribution installed
If you run into an issue during the install process, check the installation section of the troubleshooting guide.
Set up your Linux user info
Once you have installed WSL, you will need to create a user account and password for your newly installed Linux distribution. See the Best practices for setting up a WSL development environment guide to learn more.
Set up and best practices
We recommend following our Best practices for setting up a WSL development environment guide for a step-by-step walk-through of how to set up a user name and password for your installed Linux distribution(s), using basic WSL commands, installing and customizing Windows Terminal, set up for Git version control, code editing and debugging using the VS Code remote server, good practices for file storage, setting up a database, mounting an external drive, setting up GPU acceleration, and more.
Check which version of WSL you are running
Learn more in the guide to Basic commands for WSL.
Upgrade version from WSL 1 to WSL 2
To learn more, see the Command reference for WSL for a list of WSL commands, Comparing WSL 1 and WSL 2 for guidance on which to use for your work scenario, or Best practices for setting up a WSL development environment for general guidance on setting up a good development workflow with WSL.
Ways to run multiple Linux distributions with WSL
WSL supports running as many different Linux distributions as you would like to install. This can include choosing distributions from the Microsoft Store, importing a custom distribution, or building your own custom distribution.
There are several ways to run your Linux distributions once installed:
Want to try the latest WSL preview features?
Try the most recent features or updates to WSL by joining the Windows Insiders Program. Once you have joined Windows Insiders, you can choose the channel you would like to receive preview builds from inside the Windows settings menu to automatically receive any WSL updates or preview features associated with that build. You can choose from:
Действия по установке для старых версий WSL вручную
Шаг 1. Включение подсистемы Windows для Linux
Перед установкой дистрибутивов Linux в Windows необходимо включить дополнительный компонент «Подсистема Windows для Linux».
Запустите PowerShell от имени администратора (меню «Пуск» > PowerShell > щелкните правой кнопкой мыши > Запуск от имени администратора) и введите эту команду:
Теперь перейдите к шагу 2 и выполните обновление до WSL 2. Если вы хотите установить только WSL 1, вы можете перезагрузить компьютер и перейти к разделу Шаг 6. Установка дистрибутива Linux по выбору. Чтобы выполнить обновление до WSL 2, дождитесь перезагрузки компьютера и перейдите к следующему шагу.
Шаг 2. Проверка требований для запуска WSL 2
Для обновления до WSL 2 требуется Windows 10.
Либо Windows 11.
Сборки ниже 18362 не поддерживают WSL 2. Для обновления версии Windows используйте помощник по обновлению Windows.
Чтобы проверить версию и номер сборки, нажмите клавиши Windows+R, введите winver и нажмите кнопку ОК. В меню «Параметры» выполните обновление до последней версии Windows.
Если вы используете Windows 10 версии 1903 или 1909, в меню Windows откройте меню «Параметры», перейдите к разделу «Обновления и безопасность» и выберите «Проверить наличие обновлений». Номер сборки должен быть 18362.1049 и выше или 18363.1049 и выше с номером дополнительной сборки не ниже 1049. Подробнее: поддержка WSL 2 вскоре будет реализована в Windows 10 версий 1903 и 1909.
Шаг 3. Включение компонента виртуальных машин
Перед установкой WSL 2 необходимо включить необязательный компонент Платформа виртуальных машин. Для использования этой функции на компьютере потребуются возможности виртуализации.
Запустите PowerShell с правами администратора и выполните следующую команду.
Перезапустите компьютер, чтобы завершить установку и обновление WSL до WSL 2.
Шаг 4. Скачивание пакета обновления ядра Linux
Скачайте пакет последней версии:
Запустите пакет обновления, скачанный на предыдущем этапе. (Для запуска щелкните дважды. Появится запрос на повышение уровня разрешений. Нажмите кнопку «Да», чтобы утвердить эту установку.)
Когда установка завершится, перейдите к следующему шагу — выбору WSL 2 в качестве версии по умолчанию при установке новых дистрибутивов Linux. (Пропустите этот шаг, если вы хотите, чтобы новые дистрибутивы Linux были установлены в WSL 1).
Шаг 5. Выбор WSL 2 в качестве версии по умолчанию
Откройте PowerShell и выполните следующую команду, чтобы задать WSL 2 в качестве версии по умолчанию при установке нового дистрибутива Linux:
Шаг 6. Установка дистрибутива Linux по выбору
Откройте Microsoft Store и выберите предпочтительный дистрибутив Linux.
Ниже приведены ссылки на страницы Microsoft Store для каждого дистрибутива:
На странице дистрибутива щелкните «Получить».
При первом запуске недавно установленного дистрибутива Linux откроется окно консоли, и вам будет предложено подождать минуту или две, чтобы файлы распаковались и сохранились на компьютере. Все будущие запуски должны занимать меньше секунды.
ПОЗДРАВЛЯЕМ! Вы успешно установили и настроили дистрибутив Linux, который полностью интегрирован с операционной системой Windows.
Устранение неполадок установки
Если во время установки возникла проблема, см. раздел Установка руководства по устранению неполадок.
Скачивание дистрибутивов
Бывают сценарии, когда вы не можете (или не хотите) устанавливать дистрибутивы WSL Linux с помощью Microsoft Store. Вы можете использовать номер SKU классической ОС Windows Server или Long-Term Servicing (LTSC), который не поддерживает Microsoft Store, или политики корпоративной сети и административные параметры запрещают использовать Microsoft Store в вашей среде. В таких случаях, хотя WSL можно использовать, возможно, потребуется загрузить дистрибутивы Linux напрямую.
Если приложение Microsoft Store недоступно, вы можете скачать и вручную установить дистрибутивы Linux, используя следующие ссылки:
Кроме того, при желании вы можете скачать предпочтительные дистрибутивы с помощью командной строки, используя командлет PowerShell Invoke-WebRequest. Например, для скачивания Ubuntu 20.04:
Кроме того, вы можете использовать служебную программу командной строки для скачивания. Чтобы скачать Ubuntu 20.04 с помощью curl:
В этом примере выполняется curl.exe (а не только curl ), чтобы в PowerShell вызывался реальный исполняемый файл curl, а не его псевдоним для Invoke-WebRequest в PowerShell.
После скачивания дистрибутива перейдите к папке со скачанным файлом и выполните следующую команду в этом каталоге, где app-name — имя APPX-файла дистрибутива Linux.
Установка Терминала Windows (необязательно)
С помощью Терминала Windows можно открыть несколько вкладок или областей окна для просмотра нескольких распределений Linux или других командных строк (PowerShell, командная строка, Azure CLI и т. д.), а также быстрого переключения между ними. Вы можете полностью настроить терминал, используя уникальные цветовые схемы, стили шрифтов, размеры, фоновые изображения и пользовательские сочетания клавиш. Подробнее.
Set up a WSL development environment
A step-by-step guide to the best practices for setting up a WSL development environment. Learn how to run the command to install the default Bash shell that uses Ubuntu or can be set to install other Linux distributions, use basic WSL commands, set up Visual Studio Code or Visual Studio, Git, Windows Credential Manager, databases like MongoDB, Postgres, or MySQL, set up GPU acceleration, run GUI apps, and more.
Get started
Windows Subsystem for Linux comes with the Windows operating system, but you must enable it and install a Linux distribution before you can begin using it.
If you prefer to install a Linux distribution other than Ubuntu, or would prefer to complete these steps manually, see the WSL installation page for more details.
Open PowerShell (or Windows Command Prompt) and enter:
You will need to restart your machine during this installation process.
Check the troubleshooting installation article if you run into any issues.
Set up your Linux username and password
Once the process of installing your Linux distribution with WSL is complete, open the distribution (Ubuntu by default) using the Start menu. You will be asked to create a User Name and Password for your Linux distribution.
This User Name and Password is specific to each separate Linux distribution that you install and has no bearing on your Windows user name.
Please note that whilst entering the Password, nothing will appear on screen. This is called blind typing. You won’t see what you are typing, this is completely normal.
Once you create a User Name and Password, the account will be your default user for the distribution and automatically sign-in on launch.
This account will be considered the Linux administrator, with the ability to run sudo (Super User Do) administrative commands.
Each Linux distribution running on WSL has its own Linux user accounts and passwords. You will have to configure a Linux user account every time you add a distribution, reinstall, or reset.
Linux distributions installed with WSL are a per-user installation and can’t be shared with other Windows user accounts. Encountering a username error? StackExchange: What characters should I use or not use in usernames on Linux?
If you forgot the password for your Linux distribution:
Once your WSL distribution has been opened at the root level inside PowerShell, you can use this command to update your password: passwd where is the username of the account in the distribution whose password you’ve forgotten.
Update and upgrade packages
We recommend that you regularly update and upgrade your packages using the preferred package manager for the distribution. For Ubuntu or Debian, use the command:
Windows does not automatically update or upgrade your Linux distribution(s). This is a task that most Linux users prefer to control themselves.
Add additional distributions
Set up Windows Terminal
Windows Terminal can run any application with a command line interface. Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to create your own themes and customize text, colors, backgrounds, and shortcuts.
Whenever a new WSL Linux distribution is installed, a new instance will be created for it inside the Windows Terminal that can be customized to your preferences.
We recommend using WSL with Windows Terminal, especially if you plan to work with multiple command lines. See the Windows Terminal docs for help with setting it up and customizing your preferences, including:
File storage
Store your project files on the same operating system as the tools you plan to use.
For the fastest performance speed, store your files in the WSL file system if you are working on them with Linux tools in a Linux command line (Ubuntu, OpenSUSE, etc). If you’re working in a Windows command line (PowerShell, Command Prompt) with Windows tools, store your files in the Windows file system. Files can be accessed across the operating systems, but it may significantly slow down performance.
For example, when storing your WSL project files:
Set up your favorite code editor
We recommend using Visual Studio Code or Visual Studio, as they directly support remote development and debugging with WSL. Visual Studio Code allows you to use WSL as a full-featured development environment. Visual Studio offers native WSL support for C++ cross-platform development.
Use Visual Studio Code
Follow this step-by-step guide to Get started using Visual Studio Code with WSL, which includes installing the Remote Development extension pack. This extension enables you to run WSL, SSH, or a remote container for editing and debugging with the full set of Visual Studio Code features. Quickly swap between different, separate development environments and make updates without worrying about impacting your local machine.
Be sure to add the period at the end of the command to open the current directory.
Use Visual Studio
Follow this step-by-step guide to Get started using Visual Studio with WSL for C++ cross-platform development. Visual Studio 2022 enables you to build and debug CMake projects on Windows, WSL distributions, and SSH connections from the same instance of Visual Studio.
Set up version management with Git
Follow this step-by-step guide to Get started using Git on WSL and connect your project to the Git version control system, along with using the credential manager for authentication, using Git Ignore files, understanding Git line endings, and using the Git commands built-in to VS Code.
Set up remote development containers with Docker
Follow this step-by-step guide to Get started with Docker remote containers on WSL 2 and connect your project to a remote development container with Docker Desktop for Windows.
Set up a database
Follow this step-by-step guide to Get started with databases on WSL and connect your project to a database in the WSL environment. Get started with MySQL, PostgreSQL, MongoDB, Redis, Microsoft SQL Server, or SQLite.
Set up GPU acceleration for faster performance
Follow this step-by-step guide to set up GPU accelerated machine learning training in WSL and leverage your computer’s GPU (graphics processing unit) to accelerate performance heavy workloads.
Basic WSL commands
The Linux distributions that you install via WSL are best managed using PowerShell or Windows Command Prompt (CMD). See the WSL command reference guide for a list of basic commands to be familiar with when using WSL.
In addition, many commands are interoperable between Windows and Linux. Here are a couple of examples:
Mount an external drive or USB
Run Linux GUI apps
Follow this tutorial to learn how to set up and run Linux GUI apps on WSL.