You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Docker WSL2后端运行VS Code Devcontainer时共享SSH密钥失败求助

问题解决方案
  • 确认VS Code的启动入口:必须从已加载ssh-agent环境变量的WSL2 Ubuntu终端执行code .启动项目,如果你直接从Windows桌面/开始菜单启动VS Code再连接WSL2,VS Code进程无法读取WSL2会话内的SSH_AUTH_SOCK环境变量,只会尝试读取Windows系统的ssh-agent。
  • 确认WSL2 ssh-agent的环境变量全局生效:如果你只在单终端会话执行eval "$(ssh-agent -s)"添加密钥,其他WSL会话及VS Code进程无法获取SSH_AUTH_SOCK值。建议将ssh-agent自启配置写入~/.bashrc或~/.zshrc,示例配置:
if [ -z "$SSH_AUTH_SOCK" ]; then
   # Check for a currently running instance of the agent
   RUNNING_AGENT="`ps -ax | grep 'ssh-agent -s' | grep -v grep | wc -l | tr -d '[:space:]'`"
   if [ "$RUNNING_AGENT" = "0" ]; then
        # Launch a new instance of the agent
        ssh-agent -s &> $HOME/.ssh/ssh-agent
   fi
   eval `cat $HOME/.ssh/ssh-agent`
   ssh-add ~/.ssh/id_rsa 2>/dev/null
fi
  • 手动配置devcontainer挂载规则:自动转发失效时可在devcontainer.json中主动添加SSH代理套接字的挂载配置:
"mounts": [
  "source=${localEnv:SSH_AUTH_SOCK},target=/run/host-services/ssh-auth.sock,type=bind,consistency=cached"
],
"containerEnv": {
  "SSH_AUTH_SOCK": "/run/host-services/ssh-auth.sock"
}
  • 确认Docker Desktop WSL集成已开启:进入Docker Desktop设置 > Resources > WSL Integration,确认对应Ubuntu 20.04发行版的集成开关处于开启状态,重启Docker Desktop后生效。
  • 备用方案:如果你不想调整WSL2配置,可启用Windows系统内置的OpenSSH SSH代理服务,将密钥添加到Windows的ssh-agent中,VS Code从任意入口启动均可自动识别并转发代理:
    1. 以管理员身份打开PowerShell,执行Set-Service ssh-agent -StartupType Automatic设置服务自启
    2. 执行Start-Service ssh-agent启动服务
    3. 执行ssh-add C:\Users\你的用户名\.ssh\id_rsa添加对应密钥即可

内容的提问来源于stack exchange,提问作者Tomas Aschan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:45:03