打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
适用于Linux的Windows子系统的完整开发人员指南2

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.

本教程演示了如何在具有WSL2的Windows 10 PC上安装,管理和使用完整的Linux环境。 您将运行Linux内核并执行本机应用程序,同时与Windows代码编辑器和浏览器无缝共享文件和服务。

为什么要使用Linux? (Why Use Linux?)

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

您的主机几乎可以肯定使用Linux。 它是快速,开放源代码,并且运行大多数Web软件,包括:

  • servers (Apache, NGINX, LiteSpeed, etc.) 服务器(Apache,NGINX,LiteSpeed等)
  • language runtimes (PHP, Python, Node.js, Ruby, etc.) 语言运行时(PHP,Python,Node.js,Ruby等)
  • utility libraries (image manipulation, ZIP creation, emailers, etc.) 实用程序库(图像处理,ZIP创建,电子邮件程序等)
  • databases (MySQL, MongoDB, Redis, etc.) 数据库(MySQL,MongoDB,Redis等)
  • other dependencies (Elastic Search, RabbitMQ, proxies, etc.) 其他依赖项(弹性搜索,RabbitMQ,代理等)

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.

其中一些依赖项可能在Windows和macOS上可用,但是很难安装和维护相同的版本。 它们通常较慢,并且您可能会遇到细微的差异,直到您进行部署,这些差异才会变得明显。

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:

一些开发人员在其桌面上安装Linux,但是如果您经常需要非Linux软件(例如Microsoft或Adobe产品),则可能不可行。 替代选项:

  1. Use two PCs or dual boot on a single device. Switching between systems can be cumbersome. 在单个设备上使用两台PC或双启动。 系统之间的切换可能很麻烦。
  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. 使用Hyper-V,VirtualBox,Parallels,WMware或Vagrant运行Linux虚拟机(VM)。 这需要大量的OS资源和合理的IT知识。 在系统之间共享文件可能很麻烦。
  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. 在Docker容器中运行Web应用程序。 这是另一个要学习的话题,Docker本身可以在Linux上本地运行。 Windows和macOS版本都在底层使用Linux。

什么是Linux的Windows子系统? (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.

Windows Linux子系统(WSL)使开发人员可以在Windows 10上直接运行Linux环境。这是未经修改的OS,但高度集成到Windows中,并且没有虚拟机的开销。

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.

WSL1具有开创性,并将Linux系统调用转换为Windows等效项。 这可能很慢,并且某些功能不可用。 WSL2使用Hyper-V虚拟机技术,因此Linux兼容性出色,文件访问速度比以前快20倍。

Windows 10要求 (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).

WSL2与Windows的Home,Pro或Server版本兼容,但与Windows 10 S 兼容(尽管您通常可以免费升级到Home版本)。

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 2020年5月更新非常重要-版本2004或更高版本。 从开始菜单中选择设置齿轮,然后选择系统 ,然后选择关于Windows规格显示在面板底部:

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.

更新自2020年五月的结束已经慢慢铺开如果你有2004下方的版本,您可以通过点击设置 检查更新按钮,则更新和安全触发更新。

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

如果2004年仍然无法使用,则可以从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报告Windows Update面板中当前不提供2004版。 在Microsoft为您的设备发布修复程序之前,您将无法升级。

电脑要求 (PC Requirements)

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

WSL2(和Hyper-V)要求在您的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.

警告: 摆弄BIOS设置可能会损坏您的PC! 进行更改时要小心。 请查阅制造商的帮助页面,或搜索有关特定品牌和型号的在线建议。

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.

硬件虚拟化将在大多数设备上处于活动状态,但是您可以通过重新启动并打开BIOS面板进行检查-通常在系统启动时按DELF2F10键。 寻找虚拟化技术VTx或类似选项。 确保已启用它们,保存并重新启动设备。

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.

最后,确保您的C:驱动器至少有1GB的备用磁盘空间,最好是更多。 您可能可以释放“设置” ,“ 系统” ,“ 存储 ”中的某些空间,或者使用Windows管理工具中的“ 磁盘清理”工具释放空间。

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

在撰写本文时,WSL2会将Linux安装到您的C:驱动器,尽管可以在安装后将其移动到其他位置

启用WSL2 (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.

必须在“ 打开或关闭Windows功能”中启用适用于Linux虚拟机平台Windows子系统功能。 可以通过单击开始并键入“功能”或从经典控制面板中的“ 程序和功能”图标来访问该面板。

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

或者,您可以在以管理员身份运行的Windows Powershell终端中执行以下命令:

  1. dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  2. 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:

重新启动Windows 10,然后在Windows Powershell或命令提示符中输入以下命令,将WSL2设置为默认值:

wsl --set-default-version 2

下载Linux (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安装任何数量的Linux发行版。 其中包括Ubuntu,Debian,SUSE,Kali和Alpine。 在搜索框中输入“ Linux”

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.

除非您有特定要求,否则Ubuntu是一个不错的选择。 如果单击“ 获取”按钮后的Ubuntu图标,将安装最新版本。

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

下载可能需要一段时间,具体取决于您的网络速度。

启动Linux (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.

下载后,单击Microsoft Store应用程序上的“ 启动”按钮,或单击“开始”菜单中的新Ubuntu图标。 这将完成安装过程,可能需要几分钟。

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.

注意:第一次启动WSL2发行版时,您可能会在终端中看到有关内核更新的消息。 将链接复制到浏览器中,然后下载并安装更新。 您将需要再次启动Ubuntu才能继续安装。

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管理的凭据: 它们与Windows用户名和密码完全分开 (尽管选择相同的用户名和密码是可行的)。

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

Linux最终将准备就绪,您的终端将显示类似以下内容:

  1. Installing, this may take a few minutes...
  2. Please create a default UNIX user account. The username does not need to match your Windows username.
  3. For more information visit: https://aka.ms/wslusers
  4. Enter new UNIX username: ******
  5. New password:
  6. Retype new password:
  7. passwd: password updated successfully
  8. Installation successful!
  9. To run a command as administrator (user 'root'), use 'sudo <command>'.
  10. See 'man sudo_root' for details.
  11. Welcome to Ubuntu 20.04 LTS (GNU/Linux 4.19.104-microsoft-standard x86_64)
  12. * Documentation: https://help.ubuntu.com
  13. * Management: https://landscape.canonical.com
  14. * Support: https://ubuntu.com/advantage
  15. System information as of Mon Jul 6 12:07:38 BST 2020
  16. System load: 0.27 Processes: 8
  17. Usage of /: 0.4% of 250.98GB Users logged in: 0
  18. Memory usage: 0% IPv4 address for eth0: 172.21.232.173
  19. Swap usage: 0%
  20. 0 updates can be installed immediately.
  21. 0 of these updates are security updates.
  22. The list of available updates is more than a week old.
  23. To check for new updates run: sudo apt update

更新Linux (Update Linux)

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

可能会有几个Linux更新。 要更新Ubuntu,请在Linux终端中输入以下命令:

  1. sudo apt-get update
  2. sudo apt-get upgrade
  3. sudo apt-get dist-upgrade
  4. sudo apt-get autoremove

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

其他Linux发行版将具有类似的过程,但请查看文档以获取帮助。

在WSL1和WSL2之间切换 (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:

现有的WSL1发行版可以转换为WSL2。 在Windows Powershell终端中输入以下命令以显示已安装的Linux发行版及其WSL版本:

  1. PS C:\> wsl --list --verbose
  2. NAME STATE VERSION
  3. * Ubuntu Running 1

(The * asterisk highlights the default Linux installation.)

(*号突出显示了默认的Linux安装。)

To switch Ubuntu to WSL2, enter:

要将Ubuntu切换到WSL2,请输入:

wsl --set-version Ubuntu 2

Similarly, to switch back to WSL1, enter:

同样,要切换回WSL1,请输入:

wsl --set-version Ubuntu 1

设置默认的Linux发行版 (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.

当您安装了多个Linux发行版时,必须将其设置为默认发行版。 在Windows Powershell终端中输入wsl时将使用它。

To set the default distro, list your installations:

要设置默认发行版,请列出您的安装:

wsl --list

and set a default with:

并设置默认值:

wsl --setdefault <DistributionName>

Ubuntu example: wsl --setdefault Ubuntu.

Ubuntu示例: wsl --setdefault Ubuntu

以特定用户身份运行Linux (Run Linux as a Specific User)

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

要以特定用户身份运行默认分发,请在Windows Powershell终端中输入以下命令:

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!

在安装过程中定义了一个默认用户,您可以创建其他用户。 还创建了一个root用户,但在正常情况下应避免使用它。 输入危险命令太容易了!

移动您的Linux磁盘映像 (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.

Linux磁盘映像安装在C:驱动器上。 (可选)您可以将其移动到另一个驱动器以释放空间。 以下说明假定您将其移至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:

在Windows Powershell终端( 不是 Ubuntu终端)中,输入wsl --list以查看您的Linux发行版,然后按名称将其导出到备份的.tar文件,例如D:\backup\ubuntu.tar

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

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

注销相同的发行版以将其从C:驱动器中删除:

wsl --unregister Ubuntu

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

输入wsl --list以确认分发已删除。

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

将备份导入另一个位置的新WSL2发行版,例如D:\wsl

  1. mkdir D:\wsl
  2. 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.

通过输入wsl --list并从“开始”菜单启动Ubuntu应用程序,验证它已成功创建。

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

不幸的是,Ubuntu现在将使用root作为默认用户。 要使用您自己的帐户,请输入以下命令:

ubuntu config --default-user <yourname>

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

其中<yourname>是您在安装过程中定义的用户名。

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

假设一切顺利,您可以安全地删除备份文件( D:\backup\ubuntu.tar )。

安装Windows Terminal (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 ~.

要启动Linux终端,可以使用Ubuntu图标,在Powershell中输入wslbash ,或使用任何第三方选项,例如CmderConEmuHyper 。 可以定义配置文件以启动%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 ,它也可以从Microsoft Store或其github.com/microsoft/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.

Windows Terminal会自动添加您的WSL2 Linux发行版,并提供高度可配置的选项范围,包括选项卡,拆分视图,主题,透明度和键绑定。

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.

选项在定义settings.json设置菜单或Ctrl +,(逗号)访问的文件。 可以在defaults.json查看默认值和主题设置,方法是在单击“ 设置”菜单的同时按住Alt键进行访问。

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

如果您想获得有关安装,配置和使用Windows Terminal的完整的深入指南,我们将帮助您。

The Complete Guide to Windows Terminal

➤Windows 终端机完整指南

从Windows访问Linux文件 (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.

可以在网络路径\\wsl$\访问Linux文件。 可以在“文件资源管理器”地址栏中或任何文件打开对话框中输入。

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:

列出了已安装的Linux发行版,因此您可以访问\\wsl$\Ubuntu的Ubuntu根目录。 您的个人Linux文件通常存储在:

\\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:

最好将其用作Windows Terminal中的起始文件夹。 打开“ 设置” ,然后将以下配置行添加到Ubuntu配置文件:

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

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

其中<yourname>是您在安装过程中定义的用户名。

映射网络驱动器 (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….

您可以通过在文件资源管理器中打开\\wsl$\ ,将网络驱动器安装到\\wsl$\Ubuntu\ ,右键单击Ubuntu文件夹,然后选择Map network drive…

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

不幸的是,当前无法映射更深的子目录。 您可能还会在某些应用程序中遇到映射驱动器问题。

从Linux访问Windows文件 (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:

Windows驱动器安装在Linux /mnt/目录中。 例如,您的个人用户文件夹C:\Users\<yourname>可在以下位置找到:

/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\:

为了便于访问,您可以从Ubuntu终端创建指向任何Windows文件夹的符号链接,例如C:\projects\code\

  1. cd ~
  2. 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\.

code文件夹将出现在您的主目录中。 使用cd ~/code导航到它,您实际上将位于/mnt/c/projects/code/ ,它直接映射到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 ~).

从Linux访问Windows文件比使用本机Linux文件系统要慢得多。 尽可能在Linux文件空间中创建项目,通常在您的主文件夹( /home/<yourname>/~ )中创建项目。

从Windows运行Linux命令 (Running Linux Commands from Windows)

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

可以使用wsl从Windows Powershell或命令行终端运行任何Linux(bash)shell命令:

wsl <linux-command>

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

例如: wsl ls -la列出Windows文件夹中文件的全部内容和详细信息。

从Linux运行Windows应用程序 (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:

可以从Linux启动任何Windows可执行文件(通常需要指定.exe扩展名)。 例如,要在文件资源管理器中打开当前的Linux目录,请输入:

explorer.exe .

or edit .bashrc in Notepad:

或在记事本中编辑.bashrc

notepad.exe ~/.bashrc

or open the a specific project directory in VS Code:

或在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:

从Windows或Linux使用Git可能是实际的。 Windows版本是通过下载可执行文件来安装的,而Ubuntu上的Git是使用以下命令安装的:

  1. sudo apt-get update
  2. 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:

同样,您可能要在Windows和Linux中测试Node.js应用程序。 同样, Windows有一个安装程序 ,但是使用以下命令在Ubuntu中安装了Node.js 14.x:

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

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

gitnodenpm命令现在将在两种环境中npm使用。

安装Docker (Installing Docker)

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

“两次安装”规则的一个例外是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在隔离的Linux容器中运行应用程序,这些容器在概念上类似于具有OS,单个应用程序及其依存关系的轻型虚拟机。 使用Docker进行Web开发可提供一致的环境,该环境易于安装并且可在任何设备上运行。

Docker Desktop for Windows is fully WSL2-enabled:

适用于Windows的Docker桌面完全支持WSL2:

  • there’s no need to use Hyper-V, so Docker can be installed on Windows Home 无需使用Hyper-V,因此Docker可以安装在Windows Home上
  • Docker starts and runs considerably faster when configured to use WSL2 配置为使用WSL2时,Docker启动并运行得更快
  • installing Docker Desktop on Windows enables docker and docker-compose in both Windows and Linux.

    在Windows上安装Docker Desktop可以在Windows和Linux中启用dockerdocker-compose

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 Desktop建议您在WSL2首次启动时使用它。 或者,您可以从Docker系统任务栏图标菜单中选择设置 ,然后选择常规选项卡,选中使用基于WSL 2的引擎 ,然后点击Apply&Restart

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.

Docker将使用默认的Linux发行版,但是您也可以在其他已安装的发行版中,从“ 设置”中的 WSL集成”面板,然后单击 资源 ”中启用它。

使用Docker启动Apache和PHP应用程序 (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.

可以直接在WSL2 Linux环境中安装Web依赖项,例如Apache和PHP。 但是,Docker更安全,更快捷,更可配置:它允许您在同一设备上同时运行不同版本PHP。

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:

在此示例中,您将创建一个小PHP文件,并在Docker容器中使用最新版本PHP 7.4运行它。 确保已经安装了适用于Windows的Docker桌面并启用了WSL2模式,然后在Linux环境中使用index.php文件创建一个文件夹。 例如:

  1. mkdir ~/php
  2. cd ~/php
  3. touch index.php

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

编辑index.php ,也许使用记事本或VS Code,如上所示 。 添加以下内容,输出PHP状态信息:

  1. <?php
  2. 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命令以在容器中启动启用PHP 7.4的Apache Web服务器,该服务器将主机目录中的文件安装到容器中的/var/www/html

  1. docker run \
  2. -it --rm -p 8080:80 --name php \
  3. -v '$PWD':/var/www/html \
  4. 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/.

注意:此命令在Windows中也可以使用,尽管对$PWD的引用需要用Linux表示法中的完整文件路径替换,例如/c/php/

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

在任何Windows Web浏览器中打开https://localhost:8080/以查看您PHP文件生成的输出:

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

要完成操作,请在Docker终端中按Ctrl + C以停止并删除容器。

WSL2和localhost (WSL2 and localhost)

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

始终从localhost127.0.0.1访问在Windows,WSL2 Linux和Docker容器上运行的应用程序。

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:

上面PHP示例暴露了端口8080 ,该端口已映射到容器中的端口80 。 同样,如果您在Linux中安装了Node.js,则可以cd到任何目录并启动静态文件服务器:

npx small-static-server

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

在浏览器中打开http://localhost:8888/以查看该目录中的文件(默认返回index.html )。

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).

请注意,一个操作系统中可用的端口可能在另一操作系统中不可用。 端口80通常由Windows 10 Skype应用程序保留,并且无法更改(尽管经典的桌面版允许使用)。

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.

使用mkcert之类的工具进行自我签名或本地信任的SSL证书可以在Windows和Linux环境中互换使用。

VS Code WSL2集成 (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:

通过按Ctrl + Shift + P并键入/选择Terminal,可以将WSL2 shell选作默认的VS Code终端:选择Default Shell ,然后选择WSL Bash

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:

与其他应用程序一样,VS Code可以直接访问\\wsl$\ Linux文件以及在localhost运行的调试器。 不需要进一步扩展,但是以下选项使Linux和Docker文件管理更加轻松:

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

安装Remote – WSL之后 ,可以导航到任何Linux目录并启动与WSL连接的VS Code实例:

  1. cd ~/myproject
  2. code .

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

或者,单击应用程序左下方的远程窗口图标,然后选择一个连接选项:

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:

或使用活动栏中的新的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.

VS Code的远程实例具有单独的一组扩展名和设置供Linux使用。 这允许进行WSL2代码调试,并且在两种操作系统中都安装了多种语言运行时,一个系统中没有扩展名或需要不同的OS设置时非常实用。

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

扩展面板允许您在远程实例中启用和配置扩展:

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

设置存储在~/.vscode-server目录中。

摘要 (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.

WSL2将彻底改变您的Web开发。 它使使用Windows工具编写代码然后在Linux环境中运行代码变得容易。 虽然以前使用虚拟机和Samba文件夹共享是可能的,但WSL2提供了更简单,更快和高度集成的体验。

Further resources:

更多资源:

翻译自: https://www.sitepoint.com/wsl2/

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Using Android binary package with Eclipse
最近在执行文件剪切复制工作时,提示explorer.exe应用程序错误
DIY微型XPE系统教程
Camicri Cube: 可离线的便携包管理系统
新鲜特性出炉:VS2019 v16.5 预览版2 更新一览
用arm-linux-gdb调试ARM上的应用程序
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服