首页 > 解决方案 > 如何通过 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?

标签: gitmacosdockersshdocker-compose

解决方案


您不能在构建短语上使用运行时机密。您可以使用多阶段构建将密钥复制到映像中,以便在下一阶段将其丢弃,也可以使用 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

查看文档以获取有关新方法的更多信息:

https://docs.docker.com/develop/develop-images/build_enhancements/#new-docker-build-secret-information


推荐阅读