Skip to main content

Windows Subsystem for Linux 2: The Complete Guide

By Craig Buckler

Web

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

This tutorial demonstrates how to install, manage, and use a full Linux environment on your Windows 10 PC with WSL2. You’ll be running a Linux kernel and executing native applications while seamlessly sharing files and services with Windows code editors and browsers.

Why Use Linux?

Your host almost certainly uses Linux. It’s fast, open source, and runs the majority of web software including:

  • servers (Apache, NGINX, LiteSpeed, etc.)
  • language runtimes (PHP, Python, Node.js, Ruby, etc.)
  • utility libraries (image manipulation, ZIP creation, emailers, etc.)
  • databases (MySQL, MongoDB, Redis, etc.)
  • other dependencies (Elastic Search, RabbitMQ, proxies, etc.)

Some of these dependencies may be available on Windows and macOS, but installing and maintaining identical versions is difficult. They’re often slower and you may encounter subtle differences which will not become apparent until you deploy.

Some developers install Linux on their desktop, but that may not be viable if you regularly require non-Linux software such as Microsoft or Adobe products. Alternative options:

  1. Use two PCs or dual boot on a single device. Switching between systems can be cumbersome.
  2. Run a Linux virtual machine (VM) using Hyper-V, VirtualBox, Parallels, WMware, or Vagrant. This requires considerable OS resources and reasonable IT knowledge. Sharing files between systems can be awkward.
  3. Run web applications in Docker containers. It’s another topic to learn and Docker itself runs natively on Linux. Both the Windows and macOS editions use Linux below the surface.

What is the Windows Subsystem for Linux?

The Windows Subsystem for Linux (WSL) lets developers run a Linux environment directly on Windows 10. It’s an unmodified OS, but highly integrated into Windows and without the overhead of a virtual machine.

WSL1 was groundbreaking and translated Linux system calls to Windows equivalents. This could be slow and several features weren’t available. WSL2 uses Hyper-V virtual machine technology so Linux compatibility is excellent and file access is up to 20x faster than before.

Windows 10 Requirements

WSL2 is compatible with the Home, Pro, or Server editions of Windows but not Windows 10 S (although you can often upgrade to the Home edition for free).

The Windows May 2020 update is essential — that’s version 2004 or above. Choose the Settings cog from the Start menu, then select System followed by About. The Windows specifications are shown at the bottom of the panel:

Windows specifications

The update has been slowly rolling out since the end of May 2020. If you have a version below 2004, you may be able to trigger the update by clicking the Check for updates button in Settings, then Update & Security.

If 2004 remains stubbornly unavailable, you may be able to download and install it manually from microsoft.com/software-download/windows10

However, be aware some PCs report that version 2004 is currently unavailable in the Windows Update panel. You won’t be able to upgrade until Microsoft has released a fix for your device.

PC Requirements

WSL2 (and Hyper-V) require hardware virtualization support to be enabled in your BIOS.

WARNING: fiddling with your BIOS settings can trash your PC! Be careful when making changes. Consult your manufacturer’s help pages or search for online advice about your specific make and model.

Hardware virtualization will be active on most devices, but you can check by rebooting, and opening the BIOS panels — typically by hitting the DEL, F2, or F10 key as the system starts. Look for Virtualization Technology, VTx or similar options. Ensure they are enabled, save, and reboot the device.

Finally, ensure your C: drive has at least 1GB of spare disk space — ideally more. You may be able to free up some space in Settings, System, Storage or using the Disk clean-up tool in Windows Administrative Tools.

At the time of writing, WSL2 will install Linux to your C: drive, although it’s possible to move it elsewhere after installation.

Enable WSL2

The Virtual Machine Platform and Windows Subsystem for Linux features must be enabled in Turn Windows features on or off. The panel can be accessed by hitting Start and typing “features” or from the Programs and Features icon in the classic Control Panel.

enable WSL2

Alternatively, you can execute the following commands in a Windows Powershell terminal run as an Administrator:

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

Reboot Windows 10, then enable WSL2 as the default by entering the following command in a Windows Powershell or command prompt:

wsl --set-default-version 2

Download Linux

You can install any number of Linux distros from the Microsoft Store accessed in the Start menu. This includes Ubuntu, Debian, SUSE, Kali, and Alpine. Enter “Linux” in the search box:

Microsoft Store

Ubuntu is a good choice unless you have specific requirements. The latest edition will be installed if you click the Ubuntu icon followed the Get button.

The download could take a while depending on your network speed.

Launch Linux

Following download, click the Launch button on the Microsoft Store app, or the new Ubuntu icon in the Start menu. This will complete the installation process and can take several minutes.

Note: the first time you launch a WSL2 distro, you may see a message in the terminal about a kernel update. Copy the link into your browser, then download and install the update. You will need to launch Ubuntu again to continue with the installation.

You’ll be prompted to enter a username and password. These are the credentials for Linux administration: they are completely separate from your Windows username and password (although choosing the same ones may be practical).

Linux will eventually be ready and your terminal will show content similar to this:

Installing, this may take a few minutes...
Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms/wslusers
Enter new UNIX username: ******
New password:
Retype new password:
passwd: password updated successfully
Installation successful!
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

Welcome to Ubuntu 20.04 LTS (GNU/Linux 4.19.104-microsoft-standard x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon Jul 6 12:07:38 BST 2020

  System load:  0.27               Processes:             8
  Usage of /:   0.4% of 250.98GB   Users logged in:       0
  Memory usage: 0%                 IPv4 address for eth0: 172.21.232.173
  Swap usage:   0%

0 updates can be installed immediately.
0 of these updates are security updates.

The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Update Linux

There are likely to be several Linux updates. To update Ubuntu, enter the following commands in the Linux terminal:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get autoremove

Other Linux distros will have a similar process, but check the documentation for assistance.

Switch Between WSL1 and WSL2

Existing WSL1 distros can be converted to WSL2. Entering the following command in a Windows Powershell terminal to display the installed Linux distros and their WSL version:

PS C:\> wsl --list --verbose

  NAME    STATE    VERSION
* Ubuntu  Running  1

(The * asterisk highlights the default Linux installation.)

To switch Ubuntu to WSL2, enter:

wsl --set-version Ubuntu 2

Similarly, to switch back to WSL1, enter:

wsl --set-version Ubuntu 1

Set a Default Linux Distribution

When you have multiple Linux distributions installed, one must be set as the default. It will be used when wsl is entered in a Windows Powershell terminal.

To set the default distro, list your installations:

wsl --list

and set a default with:

wsl --setdefault <DistributionName>

Ubuntu example: wsl --setdefault Ubuntu.

Run Linux as a Specific User

To run your default distribution as a specific user, enter the following command in a Windows Powershell terminal:

wsl --user <username>

A default user is defined during installation and you can create others. A root user is also created, but you should avoid using it under normal circumstances. It’s too easy to enter a dangerous command!

Move Your Linux Disk Image

The Linux disk image is installed on your C: drive. Optionally, you can move it to another drive to free up space. The following instructions presume you’ll move it to D:\wsl.

In a Windows Powershell terminal (not the Ubuntu terminal), enter wsl --list to view your Linux distributions, then export one by name to a back-up .tar file, e.g. D:\backup\ubuntu.tar:

mkdir D:\backup
wsl --export Ubuntu D:\backup\ubuntu.tar

Unregister the same distribution to remove it from the C: drive:

wsl --unregister Ubuntu

Enter wsl --list to verify the distribution has been removed.

Import the backup into a new WSL2 distribution at another location, such as D:\wsl:

mkdir D:\wsl
wsl --import Ubuntu D:\wsl\ D:\backup\ubuntu.tar

Verify it has been successfully created by entering wsl --list and launching the Ubuntu app from the Start menu.

Unfortunately, Ubuntu will now use root as the default user. To use your own account, enter the following command:

ubuntu config --default-user <yourname>

where <yourname> is the username you defined during installation.

Presuming all has gone well, you can safely delete the backup file (D:\backup\ubuntu.tar).

Install Windows Terminal

To launch the Linux terminal, you can use the Ubuntu icon, enter wsl or bash in Powershell, or use any third-party option such as Cmder, ConEmu, or Hyper. Profiles can be defined to launch %windir%\system32\bash.exe ~.

Another option is Windows Terminal, which is also available from the Microsoft Store or its repository at github.com/microsoft/terminal/.

Windows Terminal

Windows Terminal will automatically add your WSL2 Linux distros and offers a highly configurable range of options including tabs, split views, themes, transparency, and key bindings.

Options are defined in the settings.json file accessed from the Settings menu or Ctrl + , (comma). Default values and theme settings can be viewed in defaults.json, accessed by holding down Alt while clicking the Settings menu.

If you want the complete in-depth guide to installing, configuring, and using Windows Terminal, we’ve got you covered.

The Complete Guide to Windows Terminal

Accessing Linux Files from Windows

Linux files can be accessed at the network path \\wsl$\. This can be entered in the File Explorer address bar or any file open dialog.

Your installed Linux distros are listed, so you can access the Ubuntu root directory at \\wsl$\Ubuntu. Your personal Linux files will typically be stored at:

\\wsl$\Ubuntu\home\<yourname>

It’s best to use this as the starting folder in Windows Terminal. Open the Settings, and add the following configuration line to the Ubuntu profile:

"startingDirectory": "//wsl$/Ubuntu/home/<yourname>/",

where <yourname> is the username you defined during installation.

Map a Network Drive

You can mount a network drive to \\wsl$\Ubuntu\ by opening \\wsl$\ in File Explorer, right-clicking the Ubuntu folder, and choosing Map network drive….

map Linux drive

Unfortunately, it’s not currently possible to map deeper subdirectories. You may also encounter mapped-drive issues with some applications.

Accessing Windows Files from Linux

Windows drives are mounted in the Linux /mnt/ directory. For example, your personal Users folder at C:\Users\<yourname> is available at:

/mnt/c/Users/<yourname>

For ease of access, you can create a symbolic link to any Windows folder from the Ubuntu terminal, e.g. for C:\projects\code\:

cd ~
ln -s /mnt/c/projects/code/

A code folder will appear in your home directory. Navigate to it using cd ~/code and you will actually be in /mnt/c/projects/code/, which maps directly to C:\projects\code\.

Accessing Windows files from Linux is considerably slower than using the native Linux file system. Where possible, create projects within the Linux file space, typically within your home folder (/home/<yourname>/ or ~).

Running Linux Commands from Windows

Any Linux (bash) shell command can be run from a Windows Powershell or command line terminal using wsl:

wsl <linux-command>

For example: wsl ls -la lists the full contents and details of files in a Windows folder.

Running Windows Applications from Linux

Any Windows executable can be launched from Linux (it’s normally necessary to specify the .exe extension). For example, to open the current Linux directory in File Explorer, enter:

explorer.exe .

or edit .bashrc in Notepad:

notepad.exe ~/.bashrc

or open the a specific project directory in VS Code:

code ~/projects/mywebsite

Installing Applications

Always remember you’re running two operating systems. They may be highly integrated, but there are situations when you want an application installed in one or both.

It may be practical to use Git from either Windows or Linux. The Windows edition is installed by downloading an executable, but Git on Ubuntu is installed using:

sudo apt-get update
sudo apt-get install git-all

Similarly, you may want to test Node.js applications in both Windows and Linux. Again, Windows has an installer, but Node.js 14.x is installed in Ubuntu using the commands:

sudo apt-get install build-essential
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

git, node and npm commands will now work in either environment.

Installing Docker

One exception to the “install twice” rule is Docker!

Docker runs applications in isolated Linux containers which are conceptually similar to lightweight virtual machines with an OS, single application, and its dependencies. Using Docker for web development provides a consistent environment which is easy to install and works on any device.

Docker Desktop for Windows is fully WSL2-enabled:

  • there’s no need to use Hyper-V, so Docker can be installed on Windows Home
  • Docker starts and runs considerably faster when configured to use WSL2
  • installing Docker Desktop on Windows enables docker and docker-compose in both Windows and Linux.

Docker Desktop suggests you use WSL2 when it’s first launched. Alternatively, you can select Settings from the Docker system tray icon menu, then choose the General tab, check Use the WSL 2 based engine, and hit Apply & Restart.

Docker WSL2 engine

Docker will use the default Linux distro, but you can also enable it in other installed distros from the WSL Integration panel in Settings, then Resources.

Launching Apache and PHP Applications Using Docker

It’s possible to install web dependencies such as Apache and PHP directly in your WSL2 Linux environment. However, Docker is safer, quicker, and more configurable: it allows you to run different versions of PHP on the same device at the same time.

In this example, you’ll create a small PHP file and run it using the latest release of PHP 7.4 in a Docker container. Ensure you’ve installed Docker Desktop for Windows and enabled WSL2 mode, then create a folder in your Linux environment with an index.php file. For example:

mkdir ~/php
cd ~/php
touch index.php

Edit index.php, perhaps using Notepad or VS Code as shown above. Add the following content which outputs PHP status information:

<?php
phpinfo();

Run the following docker command to start a PHP 7.4-enabled Apache web server in a container which mounts files in the host directory to /var/www/html in the container:

docker run \
  -it --rm -p 8080:80 --name php \
  -v "$PWD":/var/www/html \
  php:7.4-apache

Note: this command would also work in Windows, although the reference to $PWD would need to be replaced by the full file path in Linux notation, e.g. /c/php/.

Open https://localhost:8080/ in any Windows web browser to view the output generated by your PHP file:

Docker container running Apache and PHP

To finish, press Ctrl + C in your Docker terminal to stop and delete the container.

WSL2 and localhost

Applications running on Windows, WSL2 Linux, and Docker containers are always accessed from localhost or 127.0.0.1.

The PHP example above exposed port 8080, which was mapped to port 80 in the container. Similarly, if you have Node.js installed in Linux, you can cd to any directory and start a static file server:

npx small-static-server

Open http://localhost:8888/ in a browser to view files in that directory (index.html is returned by default).

Be aware that ports available in one OS may be unavailable in the other. Port 80 is often reserved by the Windows 10 Skype App and it cannot be changed (although the classic Desktop edition does permit it).

SSL certificates that are either self-signed or locally trusted using tools such as mkcert can be used interchangeably in both Windows and Linux environments.

VS Code WSL2 Integration

The WSL2 shell can be chosen as the default VS Code terminal by pressing Ctrl + Shift + P and typing/choosing Terminal: Select Default Shell, then selecting WSL Bash:

VS Code default terminal shell

Like other applications, VS Code can directly access Linux files at \\wsl$\ and debuggers running on localhost. There’s no need for further extensions but the following options permit easier Linux and Docker file management:

After installing Remote – WSL, you can navigate to any Linux directory and launch a WSL-connected instance of VS Code:

cd ~/myproject
code .

Alternatively, click the remote window icon in the bottom left of the application, then choose a connection option:

VS Code remote window icon

Or use the new Remote Explorer icon in the Activity Bar. This allows you to choose a target type from the drop-down and connect accordingly:

VS Code Remote Explorer

The remote instance of VS Code has a separate set of extensions and settings for Linux use. This permits WSL2 code debugging and is practical when you have a mix of language runtimes installed in either OS, an extension isn’t available in one system, or it requires different OS settings.

The Extensions panel allows you to enable and configure extensions in the remote instance:

VS Code extensions

The settings are stored in your Linux ~/.vscode-server directory.

Summary

WSL2 will revolutionize your web development. It makes it easy to write code using Windows tools then run it in a Linux environment. While it was previously possible with virtual machines and Samba folder shares, WSL2 offers a simpler, faster, and highly integrated experience.

Further resources:

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?