Using SSH keys inside docker container

2019-01-03 07:35发布

I have an app that executes various fun stuff with Git (like running git clone & git push) and I'm trying to docker-ize it.

I'm running into an issue though where I need to be able to add an SSH key to the container for the container 'user' to use.

I tried copying it into /root/.ssh/, changing $HOME, creating a git ssh wrapper, and still no luck.

Here is the Dockerfile for reference:

#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 runs the git commands like git pull

22条回答
欢心
2楼-- · 2019-01-03 08:18

In order to inject you ssh key, within a container, you have multiple solutions:

  1. Using a Dockerfile with the ADD instruction, you can inject it during your build process

  2. Simply doing something like cat id_rsa | docker run -i <image> sh -c 'cat > /root/.ssh/id_rsa'

  3. Using the docker cp command which allows you to inject files while a container is running.

查看更多
该账号已被封号
3楼-- · 2019-01-03 08:19

Simplest way, get a launchpad account and use: ssh-import-id

查看更多
男人必须洒脱
4楼-- · 2019-01-03 08:19

Late to the party admittedly, how about this which will make your host operating system keys available to root inside the container, on the fly:

docker run -v ~/.ssh:/mnt -it my_image /bin/bash -c "ln -s /mnt /root/.ssh; ssh user@10.20.30.40"

I'm not in favour of using Dockerfile to install keys since iterations of your container may leave private keys behind.

查看更多
我只想做你的唯一
5楼-- · 2019-01-03 08:21

'you can selectively let remote servers access your local ssh-agent as if it was running on the server'

https://developer.github.com/guides/using-ssh-agent-forwarding/

查看更多
登录 后发表回答