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

在Docker中结合ssh-agent使用多SSH密钥的问题

解决Docker构建时使用多个SSH部署密钥访问GitHub私有仓库的问题

问题根源

你配置的IdentityFile ~/.ssh/akamai会让容器尝试读取本地路径的私钥文件,但使用--mount=type=ssh时,Docker是将宿主机的SSH Agent连接挂载到容器内,而非复制私钥文件到容器,所以容器里根本不存在/root/.ssh/akamai这个文件,导致认证失败。

正确配置步骤

1. 宿主机添加多个部署密钥到SSH Agent

先把两个仓库的部署密钥都添加到宿主机的SSH Agent中:

ssh-add ~/.ssh/akamai
ssh-add ~/.ssh/second-repo-key  # 替换为第二个仓库的密钥文件路径

执行ssh-add -l确认两个密钥都已成功加载。

2. 修改Dockerfile的SSH配置

不需要指定IdentityFile(因为密钥由SSH Agent管理),只需要为每个仓库配置独立的Host别名,确保SSH使用Agent中的密钥:

RUN mkdir -p -m 0600 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts
RUN touch ~/.ssh/config

# 为第一个仓库配置Host别名
RUN echo "\nHost akamai-repo\nHostName github.com\nIdentitiesOnly yes\n" >> ~/.ssh/config
# 为第二个仓库配置Host别名
RUN echo "\nHost second-repo\nHostName github.com\nIdentitiesOnly yes\n" >> ~/.ssh/config

# 使用别名克隆对应仓库
RUN --mount=type=ssh git clone git@akamai-repo:SolarSystems-Software/akamai
RUN --mount=type=ssh git clone git@second-repo:Your-Org/your-second-repo.git  # 替换为实际仓库路径
  • IdentitiesOnly yes:强制SSH只使用SSH Agent提供的密钥,避免容器内其他无关密钥干扰认证。
  • Host别名可自定义,只要克隆时对应即可。

3. 执行Docker构建

保持原构建命令不变,--ssh default会自动将宿主机的SSH Agent挂载到容器:

docker build --ssh default .

可选验证步骤

可以在Dockerfile中添加测试命令,提前确认SSH认证是否成功:

RUN --mount=type=ssh ssh -T git@akamai-repo
RUN --mount=type=ssh ssh -T git@second-repo

如果输出类似Hi SolarSystems-Software/akamai! You've successfully authenticated, but GitHub does not provide shell access.的信息,说明认证正常。

内容的提问来源于stack exchange,提问作者Levi Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:35:49