Issue
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)" .
Solution
I'd clone it on the host, using the ssh-agent you already have running, before you run docker build
.
If you really have to have the private key in the image (which you've acknowledged is dangerous) then you should be able to have it at its default location $HOME/.ssh/id_rsa
where you have it in your code; don't try to launch an ssh-agent. You could also inject a $HOME/.ssh/config
file if your problem is aggressive host key checking, or a $HOME/.ssh/known_hosts
file that has the host key already. Since all of these are files you might find it easier to have them in the Docker build tree and COPY
them into $HOME/.ssh
.
Answered By - David Maze Answer Checked By - Senaida (WPSolving Volunteer)