我有一个应用程序,执行各种有趣的东西与Git(像运行Git克隆& Git推送),我试图docker-ize它。
我遇到了一个问题,虽然我需要能够添加一个SSH密钥到容器的容器“用户”使用。
我试着把它复制到/root/。ssh/,更改$HOME,创建一个git ssh包装器,仍然没有运气。
以下是Dockerfile供参考:
#DOCKER-VERSION 0.3.4
from ubuntu:12.04
RUN apt-get update
RUN apt-get install python-software-properties python g++ make git-core openssh-server -y
RUN add-apt-repository ppa:chris-lea/node.js
RUN echo "deb http://archive.ubuntu.com/ubuntu precise universe" >> /etc/apt/sources.list
RUN apt-get update
RUN apt-get install nodejs -y
ADD . /src
ADD ../../home/ubuntu/.ssh/id_rsa /root/.ssh/id_rsa
RUN cd /src; npm install
EXPOSE 808:808
CMD [ "node", "/src/app.js"]
App.js运行git命令,比如git pull
Docker容器应该被视为它们自己的“服务”。为了分离关注点,你应该分离功能:
1)数据应该在数据容器中:使用链接卷将repo克隆到。然后可以将该数据容器链接到需要它的服务。
2)使用一个容器来运行git克隆任务(即它唯一的任务是克隆),当你运行它时将数据容器链接到它。
3) ssh-key也一样:把它作为一个卷(如上所述),当你需要它时链接到git克隆服务
这样,克隆任务和密钥都是临时的,只在需要时才活动。
现在,如果你的应用程序本身是一个git接口,你可能会考虑直接使用github或bitbucket REST api来完成你的工作:这就是它们的设计目的。
一个简单而安全的方法来实现这一点,而不需要将密钥保存在Docker镜像层中,或通过ssh_agent体操:
As one of the steps in your Dockerfile, create a .ssh directory by adding:
RUN mkdir -p /root/.ssh
Below that indicate that you would like to mount the ssh directory as a volume:
VOLUME [ "/root/.ssh" ]
Ensure that your container's ssh_config knows where to find the public keys by adding this line:
RUN echo " IdentityFile /root/.ssh/id_rsa" >> /etc/ssh/ssh_config
Expose you local user's .ssh directory to the container at runtime:
docker run -v ~/.ssh:/root/.ssh -it image_name
Or in your dockerCompose.yml add this under the service's volume key:
- "~/.ssh:/root/.ssh"
你最终的Dockerfile应该包含如下内容:
FROM node:6.9.1
RUN mkdir -p /root/.ssh
RUN echo " IdentityFile /root/.ssh/id_rsa" >> /etc/ssh/ssh_config
VOLUME [ "/root/.ssh" ]
EXPOSE 3000
CMD [ "launch" ]
下面是我如何在使用docker composer构建图像时使用ssh键:
.env
SSH_PRIVATE_KEY=[base64 encoded sshkey]
docker-compose.yml
version: '3'
services:
incatech_crawler:
build:
context: ./
dockerfile: Dockerfile
args:
SSH_PRIVATE_KEY: ${SSH_PRIVATE_KEY}
dockerfile:
...
# Set the working directory to /app
WORKDIR /usr/src/app/
ARG SSH_PRIVATE_KEY
RUN mkdir /root/.ssh/
RUN echo -n ${SSH_PRIVATE_KEY} | base64 --decode > /root/.ssh/id_rsa_wakay_user
正如eczajk已经在Daniel van Flymen的回答中评论的那样,删除键并使用-squash似乎不安全,因为它们仍然会在历史记录中可见(docker history -no-trunc)。
在Docker 18.09中,你可以使用“构建秘密”特性。在我的情况下,我克隆了一个私人git回购使用我的主机SSH密钥与以下在我的Dockerfile:
# syntax=docker/dockerfile:experimental
[...]
RUN --mount=type=ssh git clone [...]
[...]
为了能够使用这个,你需要在运行docker build之前启用新的BuildKit后端:
export DOCKER_BUILDKIT=1
你需要在docker build中添加——ssh default参数。
更多信息请点击:https://medium.com/@tonistiigi/build- secrets.and -ssh- foring-in dock-18-09-ae8161d066