How to pass local machine's SSH key to docker container?
我正在尝试从DockerFile构建Docker映像,需要采取的步骤之一是安装一个依赖项,该依赖项只能通过专用Gitlab存储库提供。这意味着容器需要访问ssh密钥才能进行克隆。我知道这不是最安全的方法,但是这只是一个中间容器,一旦运行应用程序所需的所有组件都就位,这个容器就会被移除。
问题是,无论我尝试什么,我都无法在Docker内获取ssh代理来建立连接。我得到:
1 2 3 4 5 | npm ERR! Host key verification failed. npm ERR! fatal: Could not read from remote repository. npm ERR! npm ERR! Please make sure you have the correct access rights npm ERR! and the repository exists. |
如果我尝试在不运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | FROM risingstack/alpine:3.4-v6.9.4-4.2.0 RUN apk update RUN apk add openssh ARG SSH_KEY # Authorize SSH Host RUN mkdir -p /root/.ssh && \ chmod 700 /root/.ssh && \ ssh-keyscan github.com > /root/.ssh/known_hosts # Add the keys and set permissions RUN echo"$SSH_KEY"> /root/.ssh/id_rsa && \ chmod 700 /root/.ssh/id_rsa && \ RUN eval"$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa && ssh -o StrictHostKeyChecking=no [email protected] || true && npm install |
命令(我将私钥作为构建参数传递):
1 | docker build -t test --build-arg SSH_KEY="$(cat ~/.ssh/id_rsa)" . |
这对我很有用:
使用此解决方法:https://stackoverflow.com/a/47544999/3957754将文件作为构建参数传递
文档文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ARG SSH_KEY ENV SSH_KEY=$SSH_KEY # Make ssh dir RUN mkdir /root/.ssh/ # Create id_rsa from string arg, and set permissions RUN echo"$SSH_KEY"> /root/.ssh/id_rsa RUN chmod 600 /root/.ssh/id_rsa # Create known_hosts RUN touch /root/.ssh/known_hosts # Add git providers to known_hosts RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts RUN ssh-keyscan github.com >> /root/.ssh/known_hosts RUN ssh-keyscan gitlab.com >> /root/.ssh/known_hosts |
建造
1 | docker build -t some-app --build-arg SSH_KEY="$(cat ~/file/outside/build/context/id_rsa)" . |
有了这个,您可以执行git clone [email protected]…(Gitlab或BitBucket)在构建阶段或使用Docker入口点技术。
在运行
如果您真的需要在映像中使用私钥(您已经确认这是危险的),那么您应该能够将它放在默认位置