【问题标题】:How to share SSH key through Docker secrets to access private Github repos?如何通过 Docker 机密共享 SSH 密钥以访问私有 Github 存储库?
【发布时间】:2019-09-30 13:33:43
【问题描述】:

我正在使用来自 this post 的建议来实现 Docker secrets,以便我可以使用本地 SSH 密钥来验证我的容器对 Github 的访问。我在 MacOS 上,没有使用 Docker swarm。这是我的设置:

docker-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?

【问题讨论】:

    标签: git macos docker ssh docker-compose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 1970-01-01
      • 2014-02-19
      • 2019-04-23
      • 2021-09-07
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多