Docker:无法在运行时克隆一个github私有的rebo

我创build了一个带有.sh脚本的容器作为条目文件。 另外,dockerfile会创build一个新的用户,并将其作为工作目录。 .sh脚本本身位于新用户的工作目录中。

在运行时( docker run ),我可以看到容器执行.sh,所以构build成功。

我的问题是,这个容器需要克隆一个私人的github回购。

在closures/投票closures/标记为重复的这个问题之前,让我问你的帮助,因为我GOOGLE了一下,读了50多个关于这个问题的SO问题,但我还没有find一个工作的例子。 我的问题是关于解决问题的方法以及如何实施

我的问题是, git clone命令告诉我:

 Cloning into 'tools'... Host key verification failed. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. 

我认为我应该创build一个私钥并将其添加到我的密钥到我的Githubconfiguration文件,但我不能在每次运行时手动添加一个新的ssh密钥。 对?

也许,我应该build立一个新的关键,并将其添加到我的github回购。 图像将永远是私人的,所以从这方面没有安全问题。 但如何做到这一点?

有没有其他的方法来完成这个任务?

例如我试图在运行时复制我的工作专用RSA密钥:

 docker run -it --rm my_image:git_cloning -v ~/.ssh/id_rsa:/realtebo/.ssh/id_rsa:ro 

无论如何,我得到这个:

 Cloning into 'tools'... The authenticity of host 'github.com (192.30.253.113)' can't be established. RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'github.com,192.30.253.113' (RSA) to the list of known hosts. Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. 

在构build时,我避免了做一个github keyscan的“添加关键问题”

 RUN mkdir ~/.ssh \ && echo >> ~/.ssh/known_hosts \ && ssh-keyscan github.com >> ~/.ssh/known_hosts 

但无论如何,我在运行时得到这个:

 Cloning into 'tools'... Warning: Permanently added the RSA host key for IP address '192.30.253.113' to the list of known hosts. Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. 

我终于解决了。

我将包含我的最终Dockerfile一步一步的解释

 FROM <base_image> 

在这种情况下,我从一个自定义的图像开始,但是起源于官方的ubuntu:16_04

 RUN useradd -ms /bin/bash realtebo 

作为第一个行动,我创build了新的非root用户; 读者应该记住,在基本操作系统映像没有任何修改的情况下,容器将只有root用户。

 COPY id_rsa /home/realtebo/.ssh/ COPY id_rsa.pub /home/realtebo/.ssh/ 

我将公钥和私钥复制到Dockerfile文件夹中。 Witht这些命令我有效地安装它们为新用户

请记住: COPY仅与Dockerfile的相同目录(上下文)中的文件/目录一起使用!

另外:公钥必须添加到您的Github SSH密钥钱包

 RUN chown realtebo:realtebo /home/realtebo \ && chown realtebo:realtebo /home/realtebo/.ssh \ && chown realtebo:realtebo /home/realtebo/.ssh/* 

系统将需要作为新用户访问这些密钥,所以我需要这些chown命令(仅使用1层)。

 USER realtebo 

从这一点,我继续使用新用户的行动

 RUN echo >> ~/.ssh/known_hosts \ && ssh-keyscan github.com >> ~/.ssh/known_hosts \ && cd /home/realtebo \ && git clone git@github.com:realtebo/my-private-tool.git tools 

第一行创build一个空的known_hosts文件(如果不存在),或者如果它已经存在,则不附加任何内容。 这个文件将从git中使用,当clonegithub.com retreiving主机ip。 这个主机名实际上是从他们的DNS系统绑定到多个IP。

第二行将所有已知的主机公钥导入到我们的known_hosts文件中。

第三行更改工作目录到用户的家中。

第四行最后把我的工具真正的克隆到tools subdir中

我build议使用部署密钥而不是用户密钥,所以如果可能的话,您可以控制容器访问存储库而不暴露自己的密钥。

我做了一些类似的共享ssh-agent套接字:

docker运行\
 --volume $ SSH_AUTH_SOCK:/ ssh-agent \
 --env SSH_AUTH_SOCK = / ssh-agent