在 Windows 上使用 WSL2 和 VS code 容器进行 SSH 转发

dan*_*ane 1 docker visual-studio-code windows-subsystem-for-linux

我在 Windows 上的 WSL2 下运行 Ubuntu。在 Ubuntu 中,我克隆了我的存储库,该存储库设置为运行 docker。当我docker-compose up在项目内部运行时,它成功启动,并且我可以在 Windows 上从 VS code 打开容器。

当我尝试使用 VS Code 内部的任何 git 功能时,就会出现问题。我刚得到一个permission denied (publickey). 如果我在 VS code 中打开终端(连接到容器),则在运行git pull.

如果我docker-compose run web bash从 Ubuntu 终端运行,我可以成功运行git pull. 因此代理被转发到容器,它在 VS Code 中不起作用。

我缺少一些设置吗?

Mat*_*ser 6

要让 VS Code 使用在 WSL2 后端运行的 Docker 容器内的 WSL2 实例中的 SSH 密钥,您需要告诉 WSL2在启动时创建一个 ssh 代理,并将您的 ssh 密钥添加到代理中。当 VS Code 附加到在 WSL2 后端运行的容器时,它将自动获取正在运行的 ssh-agent,并允许您使用容器内的 WSL2 SSH 密钥进行身份验证。

对于任何一种方法,您都需要socat安装 WSL2

sudo apt install socat
Run Code Online (Sandbox Code Playgroud)

方法 1 - 手动 Bash 脚本

要告诉您的 WSL2 发行版在启动时启动其 ssh-agent,您需要将这些行添加到 ~/.bash_profile 或 ~/.zprofile (对于 Zsh),以便 ssh-agent 在 WSL2 启动时启动:

sudo apt install socat
Run Code Online (Sandbox Code Playgroud)

方法 2 - 钥匙扣

钥匙串基本上与上面的功能相同,但只需一个简单的命令。默认情况下不安装它,因此您必须使用发行版的包管理器或从源代码安装它。

sudo apt install keychain
Run Code Online (Sandbox Code Playgroud)

安装钥匙串后,将以下内容添加到您的~/.bash_profile~/.zprofile

# keychain will start the ssh agent and add the keys, or reuse the ssh agent
# if it is already running
eval `keychain --eval --agents ssh id_rsa`

# ...
Run Code Online (Sandbox Code Playgroud)

您还可以使用钥匙串来设置 GPG 密钥(如果有)。

如果~/.bash profile尚不存在(WSL2 上默认安装的 Ubuntu 并不存在),那么您需要将以下行添加到您的文件末尾,~/.bash_profile以便~/.bashrc在使用 bash.txt 时正确获取源代码。

# run the .bashrc file if it exists (this is the default on WSL2 if this does not already exist)
# these lines may already exist if .bash_profile already exists
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi
Run Code Online (Sandbox Code Playgroud)

参考

https://code.visualstudio.com/remote/advancedcontainers/sharing-git-credentials#_using-ssh-keys

https://github.com/microsoft/vscode-remote-release/issues/2925#issuecomment-652558889