How to pass local machine's SSH key to docker container?

Michał Szydłowski picture Michał Szydłowski · Aug 7, 2018 · Viewed 18k times · Source

I'm trying to build a docker image from Dockerfile and one of the steps that need to be taken is installing a dependency that is only available via private Gitlab repository. This means the container will need to have access to SSH keys to do the clone. I know this isn't the most secure approach, however this is only going to be an intermediate container that is going to be removed once all of the components necessary to run the app are in place.

The problem is, that I cannot, whatever I try, get ssh agent inside docker to establish the connection. I get:

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.

The same thing happens if I try to simply clone the repository without running npm install. Here is the Dockerfile I use:

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

and the command (I pass the private key as build argument):

docker build -t test  --build-arg SSH_KEY="$(cat ~/.ssh/id_rsa)" .

Answer

JRichardsz picture JRichardsz · Sep 5, 2018

This works for me :

Using this workaround : https://stackoverflow.com/a/47544999/3957754 to pass files as build args

Dockerfile

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

Build

docker build -t some-app --build-arg SSH_KEY="$(cat ~/file/outside/build/context/id_rsa)" .

With this, you can perform git clone [email protected]... (gitlab, or bitbucket) at build stage or at run stage using ENTRYPOINT ["docker-entrypoint.sh"].

Update

This could works if you need to pass any file as parameter to your container