Search code examples
dockerdocker-composedockerfilessh-keysdocker-image

SSH agent forwarding during docker build


While building up a docker image through a dockerfile, I have to clone a github repo. I added my public ssh keys to my git hub account and I am able to clone the repo from my docker host. While I see that I can use docker host's ssh key by mapping $SSH_AUTH_SOCK env variable at the time of docker run like

docker run --rm -it --name container_name \
  -v $(dirname $SSH_AUTH_SOCK):$(dirname $SSH_AUTH_SOCK) \
  -e SSH_AUTH_SOCK=$SSH_AUTH_SOCK my_image

How can I do the same during a docker build?


Solution

  • For Docker 18.09 and newer

    You can use new features of Docker to forward your existing SSH agent connection or a key to the builder. This enables for example to clone your private repositories during build.

    Steps:

    First set environment variable to use new BuildKit

    export DOCKER_BUILDKIT=1
    

    Then create Dockerfile with new (experimental) syntax:

    # syntax=docker/dockerfile:experimental
    
    FROM alpine
    
    # install ssh client and git
    RUN apk add --no-cache openssh-client git
    
    # download public key for github.com
    RUN mkdir -p -m 0600 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts
    
    # clone our private repository
    RUN --mount=type=ssh git clone git@github.com:myorg/myproject.git myproject
    

    And build image with

    docker build --ssh default .
    

    Read more about it here: https://medium.com/@tonistiigi/build-secrets-and-ssh-forwarding-in-docker-18-09-ae8161d066