WSL 2 上的 Docker 远程容器入门Get started with Docker remote containers on WSL 2

此循序渐进指南将帮助你开始使用远程容器进行开发,方法是 使用 WSL 2 (适用于 Linux 的 windows 子系统,版本 2) 来设置用于 Windows 的 Docker 桌面。This step-by-step guide will help you get started developing with remote containers by setting up Docker Desktop for Windows with WSL 2 (Windows Subsystem for Linux, version 2).

适用于 Windows 的 Docker Desktop 免费提供,并提供用于生成、传送和运行 dockerized 应用的开发环境。Docker Desktop for Windows is available for free and provides a development environment for building, shipping, and running dockerized apps. 通过启用基于 WSL 2 的引擎,你可以在同一台计算机上的 Docker Desktop 中同时运行 Linux 和 Windows 容器。By enabling the WSL 2 based engine, you can run both Linux and Windows containers in Docker Desktop on the same machine.

Docker 容器概述Overview of Docker containers

Docker 是一种工具,用于创建、部署和运行应用程序(通过使用容器)。Docker is a tool used to create, deploy, and run applications using containers. 容器使开发人员可以将应用与需要的所有部件(库、框架、依赖项等)打包为一个包一起交付。Containers enable developers to package an app with all of the parts it needs (libraries, frameworks, dependencies, etc) and ship it all out as one package. 使用容器可确保此应用的运行与之前相同,而不受任何自定义设置或运行该应用的计算机上先前安装的库的影响(运行应用的计算机可能与用于编写和测试应用代码的计算机不同)。Using a container ensures that the app will run the same regardless of any customized settings or previously installed libraries on the computer running it that could differ from the machine that was used to write and test the app's code. 这使开发人员可以专注于编写代码,而无需操心将运行代码的系统。This permits developers to focus on writing code without worrying about the system that code will be run on.

Docker 容器与虚拟机类似,但不会创建整个虚拟操作系统。Docker containers are similar to virtual machines, but don't create an entire virtual operating system. 相反,Docker 允许应用使用与运行它的系统相同的 Linux 内核。Instead, Docker enables the app to use the same Linux kernel as the system that it's running on. 这使得应用包能够仅要求主计算机上尚未安装的部件,从而降低包大小以及提高性能。This allows the app package to only require parts not already on the host computer, reducing the package size and improving performance.

将 Docker 容器与 Kubernetes 等工具结合使用以实现持续可用性是容器普及的另一个原因。Continuous availability, using Docker containers with tools like Kubernetes, is another reason for the popularity of containers. 这样就可以在不同的时间创建应用容器的多个版本。This enables multiple versions of your app container to be created at different times. 并且每个容器(及其特定的微服务)均可以动态更换,而无需停止整个系统进行更新或维护。Rather than needing to take down an entire system for updates or maintenance, each container (and it's specific microservices) can be replaced on the fly. 你可以准备一个包含所有更新的新容器,将该容器设置用于生产,并在新容器准备就绪后直接指向该容器。You can prepare a new container with all of your updates, set up the container for production, and just point to the new container once it's ready. 你还可以使用容器对不同版本的应用进行存档,如有需要,还可将其作为安全回退保持运行。You can also archive different versions of your app using containers and keep them running as a safety fallback if needed.

若要了解详细信息,请查看 Microsoft Learn 上的 Docker 容器简介To learn more, checkout the Introduction to Docker containers on Microsoft Learn.

先决条件Prerequisites

备注

WSL 可以在 WSL 版本1或 WSL 2 模式下运行分发。WSL can run distributions in both WSL version 1 or WSL 2 mode. 可以通过打开 PowerShell 并输入以下内容来进行检查: wsl -l -vYou can check this by opening PowerShell and entering: wsl -l -v. 输入以下内容,确保将分发设置为使用 WSL 2: wsl --set-version <distro> 2Ensure that the your distribution is set to use WSL 2 by entering: wsl --set-version <distro> 2. <distro>用发行版名称替换 (例如 Ubuntu 18.04) 。Replace <distro> with the distro name (e.g. Ubuntu 18.04).

在 WSL 版本1中,由于 Windows 和 Linux 之间的基本差异,Docker 引擎无法直接在 WSL 内运行,因此 Docker 团队开发了使用 Hyper-v Vm 和 LinuxKit 的替代解决方案。In WSL version 1, due to fundamental differences between Windows and Linux, the Docker Engine couldn't run directly inside WSL, so the Docker team developed an alternative solution using Hyper-V VMs and LinuxKit. 但是,因为 WSL 2 现在运行在具有完全系统调用容量的 Linux 内核上,所以 Docker 可以在 WSL 2 中完全运行。However, since WSL 2 now runs on a Linux kernel with full system call capacity, Docker can fully run in WSL 2. 这意味着 Linux 容器可以在无需模拟的情况下运行,从而在 Windows 和 Linux 工具之间实现更好的性能和互操作性。This means that Linux containers can run natively without emulation, resulting in better performance and interoperability between your Windows and Linux tools.

安装 Docker DesktopInstall Docker Desktop

对于 Windows 的 Docker Desktop 中支持 WSL 2 后端,你可以在基于 Linux 的开发环境中工作,并构建基于 Linux 的容器,同时使用 Visual Studio Code 进行代码编辑和调试,以及在 Windows 上的 Microsoft Edge 浏览器中运行容器。With the WSL 2 backend supported in Docker Desktop for Windows, you can work in a Linux-based development environment and build Linux-based containers, while using Visual Studio Code for code editing and debugging, and running your container in the Microsoft Edge browser on Windows.

若要在已 安装 WSL 2) 之后安装 Docker (:To install Docker (after already installing WSL 2):

  1. 下载 Docker Desktop 并按照安装说明进行操作。Download Docker Desktop and follow the installation instructions.

  2. 安装完成后,从 Windows "开始" 菜单启动 Docker Desktop,并从任务栏的 "隐藏的图标" 菜单中选择 "Docker" 图标。Once installed, start Docker Desktop from the Windows Start menu, then select the Docker icon from the hidden icons menu of your taskbar. 右键单击该图标可显示 Docker 命令菜单,并选择 "设置"。Right-click the icon to display the Docker commands menu and select "Settings". Docker 桌面面板图标Docker Desktop dashboard icon

  3. 确保在 "设置" "常规" 中选中 "使用基于 WSL 2 的引擎" > GeneralEnsure that "Use the WSL 2 based engine" is checked in Settings > General. Docker 桌面常规设置Docker Desktop general settings

  4. 转到 "设置 > 资源 > WSL 集成",从已安装的 WSL 2 分发中选择要启用 Docker 集成。Select from your installed WSL 2 distributions which you want to enable Docker integration on by going to: Settings > Resources > WSL Integration. Docker 桌面资源设置Docker Desktop resource settings

  5. 若要确认是否已安装 Docker,请打开 WSL 分发 (例如 Ubuntu) 并通过输入以下内容来显示版本和版本号: docker --versionTo confirm that Docker has been installed, open a WSL distribution (e.g. Ubuntu) and display the version and build number by entering: docker --version

  6. 使用以下方法运行简单的内置 Docker 映像,测试安装是否正常: docker run hello-worldTest that your installation works correctly by running a simple built-in Docker image using: docker run hello-world

提示

下面是一些有用的 Docker 命令,可了解:Here are a few helpful Docker commands to know:

  • 通过输入以下命令列出 Docker CLI 中可用的命令:dockerList the commands available in the Docker CLI by entering: docker
  • 使用以下命令列出特定命令的信息:docker <COMMAND> --helpList information for a specific command with: docker <COMMAND> --help
  • 使用以下命令列出计算机上的 docker 映像(此时仅为 hello-world 映像):docker image ls --allList the docker images on your machine (which is just the hello-world image at this point), with: docker image ls --all
  • 列出计算机上的容器,使用: docker container ls --alldocker ps -a (不包含-a show all 标志,只显示运行的容器) List the containers on your machine, with: docker container ls --all or docker ps -a (without the -a show all flag, only running containers will be displayed)
  • 列出有关 Docker 安装的系统范围内的信息,包括 WSL 2 上下文中可用的统计信息和资源 (CPU & 内存) ,使用: docker infoList system-wide information regarding the Docker installation, including statistics and resources (CPU & memory) available to you in the WSL 2 context, with: docker info

使用 VS Code 在远程容器中进行开发Develop in remote containers using VS Code

若要开始使用 Docker 和 WSL 2 来开发应用,我们建议使用 VS Code,以及 WSL 扩展和 Docker 扩展。To get started developing apps using Docker with WSL 2, we recommend using VS Code, along with the Remote-WSL extension and Docker extension.

  • 安装 VS Code 远程 WSL 扩展Install the VS Code Remote-WSL extension. 此扩展使你能够在 VS Code 中打开在 WSL 上运行的 Linux 项目, (无需担心路径问题、二进制兼容性或) 的其他跨操作系统挑战。This extension enables you to open your Linux project running on WSL in VS Code (no need to worry about pathing issues, binary compatibility, or other cross-OS challenges).

  • 安装 VS code Remote-Containers 扩展Install the VS code Remote-Containers extension. 此扩展使你能够在容器中打开你的项目文件夹或存储库,利用 Visual Studio Code 的完整功能集来完成容器中的开发工作。This extension enables you to open your project folder or repo inside of a container, taking advantage of Visual Studio Code's full feature set to do your development work within the container.

  • 安装 VS Code Docker 扩展Install the VS Code Docker extension. 此扩展添加了从 VS Code 内部生成、管理和部署容器化应用程序的功能。This extension adds the functionality to build, manage, and deploy containerized applications from inside VS Code. (需要 Remote-Container 扩展,才能实际使用容器作为开发环境。 ) (You need the Remote-Container extension to actually use the container as your dev environment.)

让我们使用 Docker 为现有应用程序项目创建一个开发容器。Let's use Docker to create a development container for an existing app project.

  1. 在此示例中,我将使用 my Hello World 教程 中的源代码,以便在 Python 开发环境中安装文档。如果希望使用自己的项目源代码,则可以跳过此步骤。For this example, I'll use the source code from my Hello World tutorial for Django in the Python development environment set up docs. You can skip this step if you prefer to use your own project source code. 若要从 GitHub 下载我的 HelloWorld-Django web 应用,请打开 WSL terminal (Ubuntu,例如) ,并输入: git clone https://github.com/mattwojo/helloworld-django.gitTo download my HelloWorld-Django web app from GitHub, open a WSL terminal (Ubuntu for example) and enter: git clone https://github.com/mattwojo/helloworld-django.git

    备注

    始终将代码存储在使用工具的同一文件系统中。Always store your code in the same file system that you're using tools in. 这将提高文件访问性能。This will result in faster file access performance. 在此示例中,我们使用的是 Linux 发行版 (Ubuntu) 并想要将项目文件存储在 WSL 文件系统上 \\wsl\In this example, we are using a Linux distro (Ubuntu) and want to store our project files on the WSL file system \\wsl\. 使用 WSL 中的 Linux 工具访问这些文件时,在 Windows 文件系统上存储项目文件会显著降低性能。Storing project files on the Windows file system would significantly slow things down when using Linux tools in WSL to access those files.

  2. 在 WSL 终端中,将目录更改为此项目的源代码文件夹:From your WSL terminal, change directories to the source code folder for this project:

    cd helloworld-django
    
  3. 通过输入以下内容在本地 WSL 扩展服务器上运行的 VS Code 中打开项目:Open the project in VS Code running on the local Remote-WSL extension server by entering:

    code .
    

    通过检查 VS Code 实例左下角的绿色远程指示器,确认已连接到 WSL Linux 发行版。Confirm that you are connected to your WSL Linux distro by checking the green remote indicator in the bottom-left corner of your VS Code instance.

    VS Code WSL 远程指示器

  4. 从 VS Code 命令调色板 ("Ctrl + Shift + P) ,输入: 远程容器:在容器中打开文件夹 ... 如果在开始键入此命令时未显示此命令,请检查以确保已安装上面链接的远程容器扩展。From the VS Code command pallette (Ctrl + Shift + P), enter: Remote-Containers: Open Folder in Container... If this command doesn't display as you begin to type it, check to ensure that you've installed the Remote Container extension linked above.

    VS Code 远程容器命令

  5. 选择要容器化的项目文件夹。Select the project folder that you wish to containerize. 在我的示例中,这是 \\wsl\Ubuntu-20.04\home\mattwojo\repos\helloworld-django\In my case, this is \\wsl\Ubuntu-20.04\home\mattwojo\repos\helloworld-django\

    VS Code 远程容器文件夹

  6. 将显示容器定义的列表,因为项目文件夹中没有 DevContainer 配置 (存储库) 。A list of container definitions will appear, since there is no DevContainer configuration in the project folder (repo) yet. 根据项目类型筛选显示的容器配置定义的列表。The list of container configuration definitions that appears is filtered based on your project type. 对于我的 Django 项目,请选择 "Python 3"。For my Django project, I'll select Python 3.

    VS Code 远程容器配置定义

  7. 将打开 VS Code 的新实例,开始生成新映像,完成生成后,将启动容器。A new instance of VS Code will open, begin building our new image, and once the build completed, will start our container. 你会看到,在 .devcontainer 和文件中有一个包含容器配置信息的新文件夹 Dockerfile devcontainer.jsonYou will see that a new .devcontainer folder has appeared with container configuration information inside a Dockerfile and devcontainer.json file.

    VS Code devcontainer 文件夹

  8. 若要确认你的项目仍连接到 WSL 和容器内,请打开 VS Code 集成终端 (Ctrl + Shift + ~) 。To confirm that your project is still connected to both WSL and within a container, open the VS Code integrated terminal (Ctrl + Shift + ~). 通过输入:和 Python 版本来检查操作系统, uname 并提供: python3 --versionCheck the operating system by entering: uname and the Python version with: python3 --version. 你可以看到,uname 恢复为 "Linux",因此你仍连接到 WSL 2 引擎,Python 版本号将基于与 WSL 分发上安装的 Python 版本不同的容器配置。You can see that the uname came back as "Linux", so you are still connected to the WSL 2 engine, and Python version number will be based on the container config that may differ from the Python version installed on your WSL distribution.

  9. 若要使用 Visual Studio Code 在容器中运行和调试应用程序,请先打开 " 运行 " 菜单 (Ctrl + Shift + D,或在最左侧的菜单栏) 上选择选项卡。To run and debug your app inside of the container using Visual Studio Code, first open the Run menu (Ctrl+Shift+D or select the tab on the far left menu bar). 然后选择 " 运行" 和 "调试 " 以选择 "调试" 配置,并选择在我的示例中最佳地套件你的项目 (的配置,这将是 "Django" ) 。Then select Run and Debug to select a debug configuration and choose the configuration that best suites your project (in my example, this will be "Django"). 这会 launch.json 在项目的文件夹中创建一个文件 .vscode ,其中包含有关如何运行你的应用程序的说明。This will create a launch.json file in the .vscode folder of your project with instructions on how to run your app.

    VS Code 运行调试配置

  10. 在 VS Code 中,选择 "运行" " > 开始调试" (或只需按F5键) 。From inside VS Code, select Run > Start debugging (or just press the F5 key). 这会在 VS Code 中打开终端,你应看到如下所示的结果: " http://127.0.0.1:8000/ 使用 CONTROL C 退出服务器"。This will open a terminal inside VS Code and you should see a result saying something like: "Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C." 按住 Ctrl 键并选择显示的用于在默认 web 浏览器中打开应用程序的地址,并查看在其容器内运行的项目。Hold down the Control key and select the address displayed to open your app in your default web browser and see your project running inside of its container.

    运行 docker 容器 VS Code

现在,你已成功配置了使用 Docker Desktop 的远程开发容器,该容器由 WSL 2 后端提供支持,你可以使用 VS Code 进行编码、生成、运行、部署或调试!You have now successfully configured a remote development container using Docker Desktop, powered by the WSL 2 backend, that you can code in, build, run, deploy, or debug using VS Code!

故障排除Troubleshooting

已弃用 WSL docker 上下文WSL docker context deprecated

如果你使用的是 WSL 的早期技术预览版,则可能有一个名为 "WSL" 的 Docker 上下文,该上下文现在已弃用且不再使用。If you were using an early Tech Preview of Docker for WSL, you may have a Docker context called "wsl" that is now deprecated and no longer used. 可以检查命令: docker context lsYou can check with the command: docker context ls. 你可以使用以下命令删除此 "wsl" 上下文,以避免错误: docker context rm wsl 你想要使用 Windows 和 WSL2 的默认上下文。You can remove this "wsl" context to avoid errors with the command: docker context rm wsl as you want to use the default context for both Windows and WSL2.

使用此不推荐使用的 wsl 上下文可能遇到的错误包括: docker wsl open //./pipe/docker_wsl: The system cannot find the file specified.error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_wsl/v1.40/images/json?all=1: open //./pipe/docker_wsl: The system cannot find the file specified.Possible errors you might encounter with this deprecated wsl context include: docker wsl open //./pipe/docker_wsl: The system cannot find the file specified. or error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_wsl/v1.40/images/json?all=1: open //./pipe/docker_wsl: The system cannot find the file specified.

有关此问题的详细信息,请参阅 windows 10 上的如何在适用于 Linux (WSL2) 的 Windows 系统中设置 DockerFor more on this issue, see How to set up Docker within Windows System for Linux (WSL2) on Windows 10.

查找 docker 映像存储文件夹时遇到问题Trouble finding docker image storage folder

Docker 创建了两个用于存储数据的发行版文件夹:Docker creates two distro folders to store data:

  • \wsl $ \docker-desktop\wsl$\docker-desktop
  • \wsl $ \docker-desktop-data\wsl$\docker-desktop-data

可以通过打开 WSL Linux 分发版并输入: explorer.exe . 在 Windows 文件资源管理器中查看文件夹来找到这些文件夹。You can find these folders by opening your WSL Linux distribution and entering: explorer.exe . to view the folder in Windows File Explorer. 输入: \\wsl\<distro name>\mnt\wsl <distro name> 将替换为分发 (的名称。Ubuntu-20.04) 查看这些文件夹。Enter: \\wsl\<distro name>\mnt\wsl replacing <distro name> with the name of your distribution (ie. Ubuntu-20.04) to see these folders.

有关在 WSL 中查找 docker 存储位置的详细信息,请参阅 WSL 存储库中 的此问题 或此 StackOverlow postFind more on locating docker storage locations in WSL, see this issue from the WSL repo or this StackOverlow post.

有关 WSL 中的常规故障排除问题的更多帮助,请参阅 疑难解答 文档。For more help with general troubleshooting issues in WSL, see the Troubleshooting doc.

其他资源Additional resources