SSH agent forwarding during docker build

Unfortunately, you cannot forward your ssh socket to the build container since build time volume mounts are currently not supported in Docker.

This has been a topic of discussion for quite a while now, see the following issues on GitHub for reference:

  • https://github.com/moby/moby/issues/6396
  • https://github.com/moby/moby/issues/14080

As you can see this feature has been requested multiple times for different use cases. So far the maintainers have been hesitant to address this issue because they feel that volume mounts during build would break portability:

the result of a build should be independent of the underlying host

As outlined in this discussion.


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 [email protected]: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