git - 如何通过 Docker 机密共享 SSH 密钥以访问私有 Github 存储库?
问题描述
我正在使用这篇文章中的建议来实现Docker 机密,以便我可以使用本地 SSH 密钥来验证我的容器对 Github 的访问权限。我在 MacOS 上,没有使用 Docker swarm。这是我的设置:
码头工人-compose.yml
version: '3.1'
services:
[servicename]:
secrets:
- ssh_private_key
[...]
secrets:
ssh_private_key:
file: ~/.ssh/id_rsa
Dockerfile
FROM python:3.7 as intermediate
RUN mkdir /root/.ssh/
RUN ln -s /run/secrets/ssh_private_key /root/.ssh/id_rsa
RUN touch /root/.ssh/known_hosts
RUN ssh-keyscan github.com >> /root/.ssh/known_hosts
COPY requirements_private_repos.txt ./
RUN pip install --no-cache-dir -r requirements_private_repos.txt
当我尝试运行docker-compose build
并使用 SSH 密钥从私有远程存储库中提取时,我收到以下错误:
Permission denied (publickey).
fatal: Could not read from remote repository.
我可以远程访问 docker 映像,并看到秘密正在创建并填充到/run/secrets/ssh_private_key
.
为什么在 Dockerfile 中使用时链接不起作用?如果 docker secrets 不是正确的方法,是否有更好的方法将 SSH 密钥从 MacOS 共享到 Docker?
解决方案
您不能在构建短语上使用运行时机密。您可以使用多阶段构建将密钥复制到映像中,以便在下一阶段将其丢弃,也可以使用 Docker 18.09 中引入的新构建时密钥。
对于多阶段方法,您可以执行以下操作:
FROM python:3.7 as intermediate
COPY id_rsa /root/.ssh/id_rsa # your private key must be on the build context
RUN touch /root/.ssh/known_hosts
RUN ssh-keyscan github.com >> /root/.ssh/known_hosts
COPY requirements_private_repos.txt ./
RUN pip install --no-cache-dir -r requirements_private_repos.txt
FROM python:3.7
COPY --from=intermediate XXXX YYYY # copy your modules, this image won't have the ssh private key
对于新方法,您可以执行以下操作,我自己没有尝试过此方法(需要在主机上运行 ssh-agent):
FROM python:3.7 as intermediate
RUN touch /root/.ssh/known_hosts
RUN ssh-keyscan github.com >> /root/.ssh/known_hosts
COPY requirements_private_repos.txt ./
RUN --mount=type=ssh pip install --no-cache-dir -r requirements_private_repos.txt
然后使用以下命令构建您的图像:
docker build --ssh default . -t myimage
查看文档以获取有关新方法的更多信息:
推荐阅读
- github - 使用 groovy 获取私有仓库的 github 标签
- python - 当 a 和 b 引用相同的数据时,为什么 a.storage() 是 b.storage() 返回 false?
- php - 使用邮递员的 GET 请求有效,而使用 PHP cURL 我得到一个空字符串
- java - 使用 Java 中的批处理请求和 nextPageToken 从 Google Drive Api 获取 1000 多个文件
- wpf - 如何使用相对路径访问不属于任何项目/程序集的图像
- dtexec - DTexec UI 可以加载 .dtsx 文件,但不能加载 DTexec 命令行
- css - CSS Grid:切换两个特定列的顺序
- c# - 你知道如何比较 Sql 中的 Datetime 和 C# 中的 datetimepicker 吗?
- javascript - 从父功能组件调用导航栏子功能
- azure-devops - AzureDevops 流程自定义规则无法更改团队项目