How to run wsl

How to run wsl

Basic commands for WSL

Install

Install WSL and the Ubuntu distribution of Linux. Learn more.

Install a specific Linux distribution

List available Linux distributions

List installed Linux distributions

Set WSL version to 1 or 2

To designate the version of WSL (1 or 2) that a Linux distribution is running on, replace with the name of the distribution and replace with 1 or 2. Comparing WSL 1 and WSL 2.

Set default WSL version

Set default Linux distribution

To set the default Linux distribution that WSL commands will use to run, replace with the name of your preferred Linux distribution.

Change directory to home

can be used with wsl to start in the user’s home directory. To jump from any directory back to home from within a WSL command prompt, you can use the command: cd

Run a specific Linux distribution from PowerShell or CMD

Update WSL

Check WSL status

See general information about your WSL configuration, such as default distribution type, default distribution, and kernel version.

Help command

See a list of options and commands available with WSL.

Run as a specific user

To run WSL as a specified user, replace with the name of a user that exists in the WSL distribution.

Change the default user for a distribution

Change the default user for your distribution log-in. The user has to already exist inside the distribution in order to become the default user.

This command will not work for imported distributions, because these distributions do not have an executable launcher. You can instead change the default user for imported distributions using the /etc/wsl.conf file. See the Automount options in the Advanced Settings Configuration doc.

Shutdown

Terminate

To terminate the specified distribution, or stop it from running, replace with the name of the targeted distribution.

Export a distribution to a TAR file

Import a new distribution

Unregister or uninstall a Linux distribution

While Linux distributions can be installed through the Microsoft Store, they can’t be uninstalled through the store.

To unregister and uninstall a WSL distribution:

You can also uninstall the Linux distribution app on your Windows machine just like any other store application. To reinstall, find the distribution in the Microsoft Store and select «Launch».

Mount a disk or device

Attach and mount a physical disk in all WSL2 distributions by replacing with the directory\file path where the disk is located. See Mount a Linux disk in WSL 2. Options include:

Advanced settings configuration in WSL

You can configure the settings for your installed Linux distributions that will automatically be applied every time you launch WSL in two ways, by using:

Both file types are used for configuring WSL settings, but the location where the file is stored, the scope of the configuration, and the version of WSL running your distribution all impact which file type to choose.

The version of WSL that you are running will impact the configuration settings. WSL 2 runs as a lightweight virtual machine (VM), so uses virtualization settings that allow you to control the amount of memory or processors used (which may be familiar if you use Hyper-V or VirtualBox).

wsl.conf

.wslconfig

WSL will detect the existence of these files, read the contents, and automatically apply the configuration settings every time you launch WSL. If the file is missing or malformed (improper markup formatting), WSL will continue to launch as normal without the configuration settings applied.

Adjusting per-distribution settings with the wsl.conf file is only available in Windows Build 17093 and later.

The 8 second rule

You must wait until the subsystem running your Linux distribution completely stops running and restarts for configuration setting updates to appear. This typically takes about 8 seconds after closing ALL instances of the distribution shell.

Configuration settings for wsl.conf

Automount settings

Section label: [automount]

Automount options

Setting different mount options for Windows drives (DrvFs) can control how file permissions are calculated for Windows files. The following options are available:

By default, WSL sets the uid and gid to the value of the default user. For example, in Ubuntu, the default user is uid=1000, gid=1000. If this value is used to specify a different gid or uid option, the default user value will be overwritten. Otherwise, the default value will always be appended.

User file-creation mode mask (umask) sets permission for newly created files. The default is 022, only you can write data but anyone can read data. Values can be changed to reflect different permission settings. For example, umask=077 changes permission to be completely private, no other user can read or write data. To further specify permission, fmask (files) and dmask (directories) can also be used.

The permission masks are put through a logical OR operation before being applied to files or directories.

What is DrvFs?

DrvFs is a filesystem plugin to WSL that was designed to support interop between WSL and the Windows filesystem. DrvFs enables WSL to mount drives with supported file systems under /mnt, such as /mnt/c, /mnt/d, etc. For more information about specifying the default case sensitivity behavior when mounting Windows or Linux drives or directories, see the case sensitivity page.

Network settings

Section label: [network]

Interop settings

Section label: [interop]

These options are available in Insider Build 17713 and later.

User settings

Section label: [user]

These options are available in Build 18980 and later.

keyvaluedefaultnotes
defaultstringThe initial username created on first runSetting this key specifies which user to run as when first starting a WSL session.

Boot settings

The Boot setting is only available on Windows 11 and Server 2022.

Section label: [boot]

Example wsl.conf file

This file can contain the following options that affect the VM that powers any WSL 2 distribution:

Section label: [wsl2]

Entries with the path value must be Windows paths with escaped backslashes, e.g: C:\\Temp\\myCustomKernel

Entries with an * after the value type are only available on Windows 11.

Frequently Asked Questions about Windows Subsystem for Linux

General

What is Windows Subsystem for Linux (WSL)?

The Windows Subsystem for Linux (WSL) is a feature of the Windows operating system that enables you to run a Linux file system, along with Linux command-line tools and GUI apps, directly on Windows, alongside your traditional Windows desktop and apps.

See the about page for more details.

Who is WSL for?

What can I do with WSL?

How to run wsl. Смотреть фото How to run wsl. Смотреть картинку How to run wsl. Картинка про How to run wsl. Фото How to run wsl

You can also access your local machine’s file system from within the Linux Bash shell – you’ll find your local drives mounted under the /mnt folder. For example, your C: drive is mounted under /mnt/c :

How to run wsl. Смотреть фото How to run wsl. Смотреть картинку How to run wsl. Картинка про How to run wsl. Фото How to run wsl

Could you describe a typical development workflow that incorporates WSL?

WSL targets a developer audience with the intent to be used as part of an inner development loop. Let’s say that Sam is creating a CI/CD pipeline (Continuous Integration & Continuous Delivery) and wants to test it first on a local machine (laptop) before deploying it to the cloud. Sam can enable WSL (& WSL 2 to improve speed and performance), and then use a genuine Linux Ubuntu instance locally (on the laptop) with whatever Bash commands and tools they prefer. Once the development pipeline is verified locally, Sam can then push that CI/CD pipeline up to the cloud (ie Azure) by making it into a Docker container and pushing the container to a cloud instance where it runs on a production-ready Ubuntu VM.

What is Bash?

Bash is a popular text-based shell and command-language. It is the default shell included within Ubuntu and other Linux distros, and in macOS. Users type commands into a shell to execute scripts and/or run commands and tools to accomplish many tasks.

How does this work?

Check out this article on the Windows Command Line blog: A Deep Dive Into How WSL Allows Windows to Access Linux Files which goes into detail about the underlying technology.

Why would I use WSL rather than Linux in a VM?

WSL requires fewer resources (CPU, memory, and storage) than a full virtual machine. WSL also allows you to run Linux command-line tools and apps alongside your Windows command-line, desktop and store apps, and to access your Windows files from within Linux. This enables you to use Windows apps and Linux command-line tools on the same set of files if you wish.

Why would I use, for example, Ruby on Linux instead of on Windows?

Some cross-platform tools were built assuming that the environment in which they run behaves like Linux. For example, some tools assume that they are able to access very long file paths or that specific files/folders exist. This often causes problems on Windows which often behaves differently from Linux.

Many languages like Ruby and Node.js are often ported to, and run great, on Windows. However, not all of the Ruby Gem or node/NPM library owners port their libraries to support Windows, and many have Linux-specific dependencies. This can often result in systems built using such tools and libraries suffering from build and sometimes runtime errors or unwanted behaviors on Windows.

These are just some of issues that caused many people to ask Microsoft to improve Windows’ command-line tools and what drove us to partner with Canonical to enable native Bash and Linux command-line tools to run on Windows.

What does this mean for PowerShell?

While working with OSS projects, there are numerous scenarios where it’s immensely useful to drop into Bash from a PowerShell prompt. Bash support is complementary and strengthens the value of the command-line on Windows, allowing PowerShell and the PowerShell community to leverage other popular technologies.

What processors does WSL support?

WSL supports x64 and Arm CPUs.

How do I access my C: drive?

Mount points for hard drives on the local machine are automatically created and provide easy access to the Windows file system.

/mnt/ /

Example usage would be cd /mnt/c to access c:\

How do I set up Git Credential Manager? (How do I use my Windows Git permissions in WSL?)

See the tutorial Get started using Git on Windows Subsystem for Linux, which features a section on setting up Git Credential Manager and storing authentication tokens in Windows Credential Manager.

How do I use a Windows file with a Linux app?

One of the benefits of WSL is being able to access your files via both Windows and Linux apps or tools.

WSL mounts your machine’s fixed drives under the /mnt/ folder in your Linux distros. For example, your C: drive is mounted under /mnt/c/

Are files in the Linux drive different from the mounted Windows drive?

Files under the Linux root (i.e. / ) are controlled by WSL which aligns with Linux behavior, including but not limited to:

Files in mounted drives are controlled by Windows and have the following behaviors:

How do I uninstall a WSL Distribution?

Additionally, you can then uninstall the Linux distro app on your machine just like any other store application.

To learn more about wsl commands, see the article, Basic commands for WSL.

How do I run an OpenSSH server?

OpenSSH ships with Windows as an optional feature. See the Install OpenSSH doc. Administrator privileges in Windows are required to run OpenSSH in WSL. To run an OpenSSH server, run your WSL distribution (ie Ubuntu) or Windows Terminal as an administrator. There are several resources out there covering SSH scenarios with WSL. Check out Scott Hanselman’s blog articles: How to SSH into a Windows 10 Machine from Linux OR Windows OR anywhere, How to SSH into WSL2 on Windows 10 from an external machine, THE EASY WAY how to SSH into Bash and WSL2 on Windows 10 from an external machine, and How to use Windows 10’s built-in OpenSSH to automatically SSH into a remote Linux machine.

How do I change the display language of WSL?

WSL install will try to automatically change the Ubuntu locale to match the locale of your Windows install. If you do not want this behavior you can run this command to change the Ubuntu locale after install completes. You will have to relaunch your WSL distribution for this change to take effect.

The below example changes to locale to en-US:

Why do I not have internet access from WSL?

Some users have reported issues with specific firewall applications blocking internet access in WSL. The firewalls reported are:

In some cases turning off the firewall allows for access. In some cases simply having the firewall installed looks to block access.

How do I access a port from WSL in Windows?

WSL shares the IP address of Windows, as it is running on Windows. As such you can access any ports on localhost e.g. if you had web content on port 1234 you could https://localhost:1234 into your Windows browser. For more information, see Accessing network applications.

How can I back up my WSL distributions, or move them from one drive to another?

Please note that traditional backup services that backup files in your AppData folders (like Windows Backup) will not corrupt your Linux files.

WSL 2

Does WSL 2 use Hyper-V? Will it be available on Windows 10 Home and Windows 11 Home?

WSL 2 is available on all Desktop SKUs where WSL is available, including Windows 10 Home and Windows 11 Home.

The newest version of WSL uses Hyper-V architecture to enable its virtualization. This architecture will be available in the ‘Virtual Machine Platform’ optional component. This optional component will be available on all SKUs. You can expect to see more details about this experience soon as we get closer to the WSL 2 release.

What will happen to WSL 1? Will it be abandoned?

We currently have no plans to deprecate WSL 1. You can run WSL 1 and WSL 2 distros side by side, and can upgrade and downgrade any distro at any time. Adding WSL 2 as a new architecture presents a better platform for the WSL team to deliver features that make WSL an amazing way to run a Linux environment in Windows.

Will I be able to run WSL 2 and other 3rd party virtualization tools such as VMware, or VirtualBox?

Some 3rd party applications cannot work when Hyper-V is in use, which means they will not be able to run when WSL 2 is enabled, such as VMware and VirtualBox. However, recently both VirtualBox and VMware have released versions that support Hyper-V and WSL2. Learn more about VirtualBox’s changes here and VMware’s changes here. For troubleshooting issues, take a look at the VirtualBox issue discussions in the WSL repo on GitHub.

We are consistently working on solutions to support third-party integration of Hyper-V. For example, we expose a set of APIs called Hypervisor Platform that third-party virtualization providers can use to make their software compatible with Hyper-V. This lets applications use the Hyper-V architecture for their emulation such as the Google Android Emulator, and VirtualBox 6 and above which are both now compatible with Hyper-V.

See the WSL issues repo for more background and discussion on WSL 2 issues with VirtualBox 6.1.

*If you’re looking for a Windows virtual machine, VMWare, Hyper-V, VirtualBox, and Parallels VM downloads are available on the Windows Dev Center.

Can I access the GPU in WSL 2? Are there plans to increase hardware support?

We have released support for accessing the GPU inside of WSL 2 distributions! This means you can now use WSL for machine learning, artificial intelligence, and data science scenarios more easily when big data sets are involved. Check out the get started with GPU support tutorial. As of right now WSL 2 does not include serial support, or USB device support. We are investigating the best way to add these features. However, USB support is now available through the USBIPD-WIN project. See Connect USB devices for steps to set up USB device support.

Can WSL 2 use networking applications?

Can I run WSL 2 in a virtual machine?

Yes! You need to make sure that the virtual machine has nested virtualization enabled. This can be enabled in your parent Hyper-V host by running the following command in a PowerShell window with Administrator privileges:

Make sure to replace ‘ ‘ with the name of your virtual machine.

Can I use wsl.conf in WSL 2?

WSL 2 supports the same wsl.conf file that WSL 1 uses. This means that any configuration options that you had set in a WSL 1 distro, such as automounting Windows drives, enabling or disabling interop, changing the directory where Windows drives will be mounted, etc. will all work inside of WSL 2. You can learn more about the configuration options in WSL in the Distribution Management page. Learn more about support for mounting drives, disks, devices, or virtual hard disks (VHDs) in the Mount a Linux disk in WSL 2 article.

Where can I provide feedback?

If you’d like to stay up to date with the latest WSL news you can do so with:

The Ultimate Guide to Windows Subsystem for Linux (Windows WSL)

Read more tutorials by Chris Blackden!

Table of Contents

The Windows Subsystem for Linux or Windows WSL is a great solution for developers to natively work within Linux right on their Windows 10 version desktop.

If you’ve spent way too much time partitioning hard drives to have several Linux systems installed with Windows, you’re in luck with this article.

The fairy code-mother at Microsoft has decided to give you another option: The Windows Subsystem for Linux (WSL). WSL makes running a Linux system alongside Windows so much easier, and more flexible.

In this tutorial, you’ll learn how to get started with WSL. You’ll learn how to get started to learning how to use some nifty tools making WSL even more versatile than using bash or PowerShell on their own.

Table of Contents

What is WSL?

WSL or C:\Windows\System32\wsl.exe is a Windows tool that allows you to install a Linux distribution as an app from the Windows store.

Since WSL is a simple Windows executable, you can call it from a command prompt or PowerShell terminal. We’ll go deeper into that topic later. For now, it’s important to understand a little more about what WSL is doing under the hood.

How to Enable WSL

To set up and enable WSL involves installing a Linux distribution alongside Windows 10. But in a way that allows the two different operating systems to interact with each other.

Prerequisites

If you’re an IT pro struggling with too many password reset requests in Active Directory, check out Specops uReset, a secure SSPR solution.

To install WSL on Windows, you have one requirement to meet; you must have a Windows 10 64-bit computer Build 18917 or later.

You can find your Windows 10 build by running the winver utility.

How to run wsl. Смотреть фото How to run wsl. Смотреть картинку How to run wsl. Картинка про How to run wsl. Фото How to run wslWindows build 1809

Enabling the WSL Windows Feature

WSL is a cinch to enable; no download required. It’s simply a single Windows feature.

To enable WSL, open up PowerShell as administrator and run the following:

Once complete, restart your computer and you’re done!

Downloading a Linux Distribution for WSL

WSL does not install any Linux distribution on its own. You’ll need to install one. Once Windows 10 comes back up, start setting up your chosen Linux distribution.

First, open up the Microsoft Store and search for ‘WSL’. You should soon see a list of Linux distributions show up.

How to run wsl. Смотреть фото How to run wsl. Смотреть картинку How to run wsl. Картинка про How to run wsl. Фото How to run wsl

Next, choose your distribution of choice and install it. This tutorial will be using Ubuntu 18.04. At the time of this writing, you have a few other distributions available as well such as:

Setting your WSL Version

You might have to enable Linux to work with WSL version 2. If so, you can do so by following the below instructions.

In a PowerShell console:

Starting up WSL

Below you will find a reference to all of the options the wsl.exe provides when starting up.

Once you get comfortable using these switches, you’ll find that running and managing applications through WSL is much easier than managing Linux virtual machines on your own.

When you’re finished, type exit to go back back to the PowerShell terminal.

Sharing Windows/Linux Resources via WSL

One of the best parts of WSL is that it can seamlessly share Windows and Linux resources with each other. At this time, you can share file systems, environment variables, network resources, and command-line tools like cmd and PowerShell.

All examples you will see in this section are via the WSL Ubuntu Linux distro. Your mileage may vary if you’ve chosen to download a different distro.

Sharing File Systems

The file system is one of the most useful things to share with WSL. WSL allows you to work with both file systems as if they were one.

The Windows 10 file system is mounted as a directory in Linux while your Linux file system will be mounted as a folder in Windows.

Finding the Linux File System from Windows with Environment Variables

When you install a Linux distro with WSL, it will sometimes add a Windows environment variable. In the case of the WSL Ubuntu Linux distro, it will create an environment variable called UBUNTU_HOME. This environment variable points to the Linux /home/ubuntu directory from both Windows and WSL Ubuntu.

The path defined in UBUNTU_HOME can be used to run scripts that use resources across them, or set a default location for the Windows terminal (covered later).

This environment variable shortcut is handy if you want to put everything in the /home/ubuntu directory. But let’s dig a little deeper into how it got there and how else you can reach it.

Finding the Linux File System from Windows via the Microsoft Store Packages Folder

Not every WSL distro is guaranteed to come with an easy way to reference it. It’s important that you learn how to find the Linux file system an alternative way.

Since most WSL Linux distributions will be installed from the Microsoft store, you can look for the Linux file system in the same place as other Windows store apps. Navigate to %USERPROFILE%\AppData\Local\Packages\ to find the directory where your Windows store apps go. Then assume control of the folder as this is usually protected by default.

You will see many subfolders in the packages folder where your Linux distrubution file system may be presented. The WSL Ubuntu distro, for example, was under the CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc folder for me.

If you navigate into the package folder, you will find the Linux file system. For WSL Ubuntu, it’s located in the LocalState\rootfs folder. This is the root directory of your Linux distro.

Finding the Windows File System from Linux

To find the Windows 10 file system from Linux, open up WSL in Windows. WSL will then bring up a bash terminal. This bash terminal will start in your UBUNTU_HOME directory by default.

You can also find the root of your Windows storage volumes as well. Each of your Windows letter drives (C, D, E, etc) is treated as a mounted drive from the WSL Linux file system. You’ll find each volume mounted as /mnt/c, /mnt/d, etc as long as you have root privileges.

The WSL2 Filesystem

Navigating the WSL filesystem is fairly straightforward. Anyone not familiar with a Linux file system structure will appreciate being able to navigate it with the Windows Explorer. Bu if you want to switch to WSL2, it’s going to be a little more complicated.

WSL2 changes how everything works under the hood for sharing file systems. For starters, the filesystem is now a virtual hard disk in vhdx format instead of a directory.

You can find the vhdx file under %USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState for an WSL Ubuntu distro.

You’ll find that VHDX files can be mounted in Windows with the Disk Manager tool. But, the virtual disks cannot be mounted while the WSL distro is registered.

Sharing Environment Variables

Environment variables are a crucial part of any operating system, making it easy to reference binaries and executables anywhere in your applications.

Before Windows 10 build 17063, the only environment variable shared between Windows 10 and WSL Linux was the PATH variable. Since then it is possible to share environment variables by using WSLENV the environment variable.

Using the WSLENV environment variable to share other environment variables can feel a little meta. To share environment variables across platforms, you actually have to set environment variables inside of another environment variable.

Overview

Sharing environment variables is a three-step process below. The only major difference when sharing across Windows/Linux is the switch argument used (full reference below).

Sharing Options

You can make variables available four different ways depending on which platform you’d like the environment variable to show up on using switches (table shown below).

Path Translation

The main reason to share environment variables is for path translation. As you may already know, Windows has user profile folders as Linux has user profile directories, for example. Each user has a predetermined “home folder” like C:\Users\ on Windows and /home/ on Linux.

Using the /p and /l switches, the WSL will translate these folder paths between platforms.

Sharing and Translating Windows Paths with Linux

You can share a single path or multiple paths at once using the /p and /l switches.

At a Windows command prompt and with a Windows environment variable defined called DESKTOP, assign a value of DESKTOP/p to the WSLENV variable. This allows you to access it from WSL Linux. You can see an example below.

The exact same procedure can be performed for multiple paths at once using the /l switch.

Sharing and Translating Linux Paths with Windows

To share and translate Linux path with Windows is the same procedure as it Windows although using Linux-specific commands to set environment variables.

For a deeper look at sharing environment variables, check out, this Microsoft article.

Sharing Network Resources

The networking component is another handy resource to share between Windows and WSL Linux.

Physical vs. Virtualized Network Interfaces

In WSL2, the network interfaces are virtualized. Virtualized network interfaces mean that WSL2 network instances can hold different IP configurations than their Windows 10 counterparts.

At the time of this writing, IP addresses for WSL2 Linux use Network Address Translation (NAT) to access network resources on Windows, though Microsoft has mentioned removing NAT is high on their backlog of issues to fix.

Client DNS Resolution

WSL will still both generate /etc/resolv.conf and /etc/hosts files to allow for DNS resolution. As long as you don’t explicitly override that behavior in /etc/wsl.conf, client DNS resolution will continue to work as expected.

You’ll learn more about the wsl.conf file later in the post.

Using PowerShell and Bash Together

One of the coolest features of WSL is the ability to seamlessly pass information to and from PowerShell and Bash on WSL.

PowerShell –> Bash

Since the WSL executable accepts input from the pipeline, you can call the wsl.exe command inside of PowerShell and accept stdin. This allows you to use WSL to pass entire objects from PowerShell into the WSL which then get processed with the bash terminal. You can see an example below.

Bash –> PowerShell/Cmd

You can also pass information from bash in the WSL to PowerShell and cmd just as easily. Below you can see an example of executing the Linux ls command and passing the output to the PowerShell Select-Object cmdlet via the pipeline.

You can also call some Windows cmd utilities from the WSL and pass the output back to Linux as long as both commands are in the system path.

Remember that the WSL knows what the system path is on both sides because it has access to the Windows PATH variable by default

Below you can see that you can run ipconfig, which is a Windows command, from within the WSL and pass that output to the Linux grep command. You can also see the opposite of calling the Linux command which and passing output to the Windows ipconfig command.

Translation Issues

There are some caveats to passing command output back and forth between bash and PowerShell.

One big problem is how PowerShell and bash return information. PowerShell is an object-oriented programming language while bash is a string manipulation tool. Any PowerShell objects piped to bash will flattened as a string. Conversely, any bash output piped to PowerShell will be converted to a string object.

You can get around the behavior somewhat by converting or explicitly casting object types in PowerShell like in the example below. But if you are expecting to pass objects between PowerShell and WSL without any extra work, you’re going to be disappointed.

By casting the bash date as the [datetime] class in PowerShell, now we have a valid PowerShell object that we can use in our script. If you are writing scripts that need to go from Windows to WSL and back again, it’s possible to do with a little massaging to the code.

Install a Windows Subsystem for Linux GUI with Xfce4

When command-line tools aren’t enough, it’s time to break out the GUIs. If you need to run a graphical utility on WSL, explore a custom distro, or you’re not familiar with bash yet, you can install a Linux GUI.

Linux has many available desktop environments. One of the most common ones to set up for WSL is called Xfce. At the time of this writing, Xfce is at version 4. Other desktop environments are available but in this article, you’ll learn how to get Xfce4 set up.

When you have a Linux desktop environment set up, you’ll need a service that understands the RDP protocol. In this article, we’ll focus on the xRDP server. xRDP is an open source RDP server for Linux that allows you to use RDP clients to connect to Linux just as if you can Windows hosts.

Setting Up

To access a Linux GUI from Windows with Xfce4 and xRDP, follow the instructions below. In a WSL terminal:

At this point, you should be able to open an RDP session from Windows 10. Open up remote desktop connection window using mstsc and provide the Linux IP address found in step #5.

If all goes well, you can open an RDP connection to the Linux distro that’s running on your Windows operating system as shown below.

Tips and Tricks

Now that you know the basics of WSL and how to use it, what’s next? Fortunately there are a lot of tools that are either built for or work well with WSL.

Setting WSL Configuration Items at Bootup with wsl.conf

A configuration file exists in the WSL at /etc/wsl.conf. This file contains configuration settings that run every time the WSL distro is started. When the wsl.conf file exists, WSL will ingest any setting in this file every time the Linux distro is started.

There are a few different sections inside of the wsl.conf file you can configure.

For more details on the wsl.conf file, check out the Microsoft Set WSL Launch Settings page.

Developing on WSL with Visual Studio Code (VS Code)

VS Code seemingly integrates with everything and WSL is no exception. From within VS Code, you can set up a workspace on your WSL Distro but manipulate it completely with VS Code on Windows. You don’t even need to have a terminal running!

To set up VS Code on Windows to work with WSL, you’ll first obviously need VS Code for Windows installed. Also be sure you have the Remote – WSL VS Code extension installed.

Confirm it worked by noticing the WSL connection icon in the lower left corner of VS Code. You should see that it has the name of your WSL distro.

You can even use the built-in terminal to interact directly with the WSL workspace. There’s no need to run a separate window for git bash commands.

Adding Windows Subsystem for Linux to the Windows Terminal

Another useful use-case of WSL is to add the WSL console it to the Windows Terminal.

From within Windows Terminal, you add each WSL distro in it’s own tab. You can also customize the look of each tab so you don’t get lost.

If you’re using a WSL distro that sets an environment variable for the user directory like UBUNTU_HOME, you can also set that as the starting directory for your terminal.

If you’d like a complete video walkthrough on setting up WSL to work with the Windows Terminal, check out the TechSnips how-to video below.

Closing Thoughts

If you’re an IT pro struggling with too many password reset requests in Active Directory, check out Specops uReset, a secure SSPR solution.

Microsoft released the WSL to allow Linux developers the ability to develop on Windows. So far, the WSL has been a step in the right direction.

It appears that the WSL is going to be a crucial component of Microsoft’s new open-source friendly strategy. If Microsoft is going to take on Apple to be the devices that developers write their code on, it’s going to be an uphill battle. But WSL is a strong card to play.

WSL brings about many many welcome benefits to developers like:

WSL just turns on and runs so we can all code happily ever after.

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

More from ATA Learning & Partners

Recommended Resources!

Recommended Resources for Training, Information Security, Automation, and more!

Get Paid to Write!

ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?

ATA Learning Guidebooks

ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!

Опыт настройки и использования WSL (подсистемы Linux в Windows 10)

К написанию данной статьи меня побудил вопрос на Тостере, связанный с WSL. Я, после нескольких лет использования систем на ядре Linux, около полугода назад перешел к использованию Windows 10 на домашнем ПК. Зависимость от терминала и Linux окружения в моей работе практически сразу привели меня к вопросу: или ставить виртуалку или попробовать WSL. Я выбрал второе, и остался вполне доволен.

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

How to run wsl. Смотреть фото How to run wsl. Смотреть картинку How to run wsl. Картинка про How to run wsl. Фото How to run wsl

Никогда не думал, что однажды вернусь на Windows, но повод попробовать мне дали стечения обстоятельств: жена, далекая от IT, дергала почти каждый раз, когда у нее возникала необходимость воспользоваться компом; проснулась ностальгия по одной игре, но она никак не хотела адекватно работать под wine; а тут еще мне подарили коробочную Windows 10 Pro. WSL я поставил чуть ли не сразу после установки системы, поигрался несколько вечеров, понял, что продукт для моих задач годный, но хочется более привычный терминал и вообще некоторых удобств.

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

Сразу оговорюсь, в интернете можно найти описание установки с помощью выполнения команды lxrun /install в командной строке или консоли PowerShell. Данный способ больше не работает (после выхода WSL в стабильный релиз). Насколько мне известно, сейчас WSL можно установить только из Microsoft Store вместе с предпочитаемым дистрибутивом.

Так же отмечу, что когда установку производил я, на выбор были доступны дистрибутивы OpenSUSE, SUSE Linux Enterprise и Ubuntu 16.04 — последний я и установил. Сейчас также доступны Ubuntu 18.04, Debian 9 и Kali Linux, возможно появятся и другие дистрибутивы. Действия по установке могут отличаться. Так же, часть проблем описанных в статье может быть уже исправлена.

Находим в магазине желаемый дистрибутив и устанавливаем. Установка пройдет быстро, так как скачает только эмулятор ядра Linux и утилиту для запуска подсистемы, которая окажется в системной папке в трех экземплярах: wsl.exe, bash.exe и ubuntu.exe (вместо ubuntu будет имя Вашего дистрибутива). Все они равнозначны и делают одно и то же — запускают собственный эмулятор терминала, в нем linux’овый bash работающий под эмулятором ядра. При первом же запуске нас попросят придумать логин и пароль для пользователя по умолчанию, а после произойдет непосредственно установка дистрибутива. В качестве пользователя по умолчанию указываем root без пароля — это потребуется для дальнейших шагов. Безопасность не пострадает, кроме того при подготовке материалов к статье, в англоязычном туториале, я наткнулся на информацию, что новые версии WSL теперь делают пользователем по умолчанию root без пароля без лишних вопросов.

Дожидаемся установки. Далее первым делом стоит обновить зеркала apt на ближайшие. Для этого понадобится CLI текстовый редактор. В комплекте только vi, я же больше предпочитаю nano, поэтому ставлю его:

sudo вводить не требуется, так как мы уже под root’ом. Отредактируем файл /etc/apt/sources.list:

У меня лучше всего работают зеркала Яндекса, поэтому мой файл выглядит так:

Нажимаем Ctrl+O для сохранения и Ctrl+X для выхода. Теперь можно обновить систему до актуального состояния:

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

Далее переходим в папку юзера, зайдем под ним, установим пароль и отредактируем файл

Все, подсистема готова к использованию… почти.

Установка X-сервера, Xfce и прочих GUI’шных приложений

Первая же проблема, на которую я натолкнулся — bash-completion в предлагаемом эмуляторе терминала работал, мягко говоря, некорректно. Кроме того, данный эмулятор не умеет вкладки, а каждый его экземпляр запускает все в новом пространстве процессов, с отдельным init’ом (который кстати не заменить). Мне захотелось нормальный эмулятор терминала, некоторых других GUI приложений, а так же панельку, чтоб это все быстро запускать.

Когда я гуглил этот вопрос, я наткнулся на множество проблем, вроде необходимости перевода dbus на tcp протокол. На данный момент всех этих проблем нет. В подсистеме нормально работают unix-domain-socket’ы и все спокойно общается через них.

Первым делом нам понадобится X-сервер, притом установленный в основную систему (в Windows). Лично я использую для этих целей VcXsrv — порт X11 на Windows. Официальный сайт указанный в about самой утилиты его сейчас не предоставляет, поэтому гуглим установщик и устанавливаем все по умолчанию.

Пока идет установка возвращаемся в терминал WSL, командой exit выходим обратно в root’а. Первым делом настроим русские локали:

Далее установим некоторые компоненты Xfce. Можно конечно установить его целиком из мета-пакета, но большинство компонентов нам не понадобится, а модульная архитектура Xfce позволяет нам поставить только необходимое:

Запускать каждый раз окружение руками не очень удобно, поэтому я автоматизировал данный процесс. Для этого в основной системе создадим в удобном для нас месте папку, а в ней 3 файла для запуска:

x-run.vbs — WSL всегда запускается со своим эмулятором терминала, если его закрыть — завершатся все его дочерние процессы. Чтоб данное окно не мозолило глаза, неплохо его запускать скрытым. К счастью в Windows встроен интерпретатор VBScript, который позволяет это сделать в одну строчку:

Далее можем запустить наш start.bat и настроить панель Xfce под себя. Замечу, что здесь я наткнулся на еще одну проблему — панель прекрасно отображается поверх всех окон, но вот выделить себе место, как панель на рабочем столе Windows она не может. Если кто знает решение данной проблемы, поделитесь в комментариях.

Ну и под конец данной части, скриншот моего рабочего стола:

How to run wsl. Смотреть фото How to run wsl. Смотреть картинку How to run wsl. Картинка про How to run wsl. Фото How to run wsl

Взаимодействие окружения Windows и окружения подсистемы Linux

Из Linux так же можно запускать Windows приложения. Просто запускаем exe-шник и он выполнится в основной системе.

Сетевой стек у подсистемы общий с Windows. Сервер поднятый в Linux будет доступен на localhost в Windows и наоборот. Однако unix-domain-socket для Windows будет просто пустым файлом, работать с этим можно только внутри Linux. Выход во внешнюю сеть у Linux так же есть, в том числе можно слушать порты, если этого не запрещает фаервол.
ifconfig в Linux и ipconfig в Windows выдают одинаковую информацию о сетевых интерфейсах.

Из диспетчера задач Windows можно спокойно прибить процесс внутри подсистемы Linux. Однако Linux увидит только свои процессы.

Особенности, ограничения и подводные камни

Ядро Linux в WSL не настоящее. Это всего лишь прослойка-эмулятор, которая часть Linux-специфичных задач выполняет сама, а часть проксирует напрямую в ядро winNT. Большая часть api в нем реализована, но не все. Свое ядро собрать не получится, как и не получится подключить модули ядра (.ko, Kernel Object).

Init процесс у WSL тоже свой и заменить его, например, на system.d не выйдет. У меня давно есть желание написать менеджер демонов на go, который бы работал с файлами юнитов system.d и предоставлял бы схожий интерфейс, да все руки не доходят.

Нет поддержки openFUSE, соответственно примонтировать виртуальную или удаленную файловую систему не получится. Так же нельзя сделать mount из файла, mount вообще ничего кроме bind здесь, похоже, не умеет.

Так же нет никакой возможности разбить файловую систему Linux на несколько разделов/дисков.

Прямой доступ к железу практически отсутствует. Все таки мы находимся в песочнице Windows, а не в полноценном Linux. /dev и /sys заметно пустуют, в них лишь проц да виртуальные устройства. Доступ к GPU — только через X-сервер, напрямую — никак, так что нейросети обучать придется в Windows.

В JS разработке столкнулся с тем, что electron.js отказался запускаться в WSL, пришлось дублировать окружение node.js в Windows.

Итоги

Статья получилась довольно длинной, надеюсь, что она окажется еще и полезной.
WSL для меня лично оказался инструментом вполне юзабельным, решающим мои задачи fullstack backend разработчика. Виртуалка с Linux за полгода так и не понадобилась. По общим ощущениям Windows+WSL намного функциональнее, чем Linux+Wine.

Пока писал статью, обнаружил, что в Microsoft Store появилась сборка WSL с Debian 9.3, данный дистрибутив мне более симпатичен, чем Ubuntu, поэтому буду пробовать ставить.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *