Fix ‘Host key verification failed’ inside Dockerfile

Marius Radčenka
2 min readJul 8, 2022

--

When doing SSH work inside a Dockerfile (eg., downloading a private repository via ssh+git) you will come across this error:

SSH works by scanning the public key of the host machine upon first connection. The key is stored and later checked by the SSH client to ensure that any further connections are not tampered with. If you’ve worked with SSH before, you will recognize this message:

Public key prompt upon first connection

The fingerprint is basically a shortened public key string that you can check manually. A reputable SSH host will ensure that all of their fingerprints are available publicly, most often on their website (Bitbucket example).

First, any Docker container is an isolated machine, it knows the bare minimum about the outside world. So the public key must be scanned and saved beforehand. Second, the docker build process is not interactive, therefore the command in our Dockerfile cannot prompt us for a decision on whether to accept the public key. So it just throws an error.

ssh-keyscan is made exactly for this issue as it is non-interactive. It outputs the public key to stdout and we just need to add (append) it to the known_hosts file. We resolve the problem with a separate command above the offending build step:

RUN ssh-keyscan your-host.com >> /root/.ssh/known_hosts

Run docker build and voila! The issue has been resolved the proper way without any compromises in security.

--

--

Marius Radčenka

Node.js freelance developer. I mostly write about technical solutions. :)