Git 在 docker 容器中克隆私人仓库

Git clone private repo inside a docker container

我有一个 docker 容器,在这个 docker 容器中,我有一个 shell 脚本,它从私人仓库执行 git 克隆。脚本如下:

eval $(ssh-agent) > /dev/null
# add the ssh key
ssh-add /root/.ssh/id_rsa

kill $SSH_AGENT_PID

git clone ssh://git@bitbucket.org/project/repo.git 

但是当 docker 是 运行 时它给出了一个错误

Cloning into 'repo'...
Host key verification failed.

fatal: Could not read from remote repository.

当我在本地机器上测试时,我可以毫无故障地克隆存储库,所以我知道我的 ssh 密钥没有问题。

问题是,当您在本地计算机上进行这样的设置时,您可以访问 SSH 终端,将密钥添加到 known_hosts 询问

The authenticity of host 'server-name (***)' can't be established.
RSA key fingerprint is XXXXXXX.
Are you sure you want to continue connecting (yes/no)?

你基本上可以交互,然后输入 yes 和 ssh-agent 为你添加到 known_hosts 的连接。但是,在这种情况下,事情发生在 docker 容器内,您基本上无法与此提示进行交互。解决方案是在 ssh 配置中添加 StrictHostKeyChecking no 标志,git 命令有多种方法,您可以检查它们 here.

所以基本上,下面是解决这个问题的优雅方法,只需制作 .ssh/config 文件并添加我们想要的 ssh 选项。

eval $(ssh-agent) > /dev/null
# add the ssh key
ssh-add /root/.ssh/id_rsa

kill $SSH_AGENT_PID

echo "Host bitbucket.org" > /root/.ssh/config
echo "User git" >> /root/.ssh/config
echo "IdentityFile /root/.ssh/id_rsa" >> /root/.ssh/config
echo "StrictHostKeyChecking no" >> /root/.ssh/config

git clone ssh://git@bitbucket.org/project/repo.git 

StrictHostKeyChecking no选项只是放弃提示,直接在known_hosts上添加连接,之后基本上就可以git clone.