5.2.1.5 BuildKit SSH Mounts
A focused guide to BuildKit SSH Mounts, connecting core concepts with practical Docker and container operations.
BuildKit SSH mounts let a Dockerfile access the host's SSH agent during a build, enabling build steps that need to authenticate over SSH — cloning a private Git repository, for example — without copying any private SSH key into the image itself.
Why This Is Useful
Cloning a private repository during a build traditionally required either embedding an SSH key directly in the image (a serious security risk) or relying on HTTPS with an embedded token (which carries similar risks). SSH mounts instead forward access to the host's already-running SSH agent for the duration of a specific build step.
RUN --mount=type=ssh git clone git@github.com:example/private-repo.git
docker build --ssh default -t myapp .
The SSH agent's available keys are forwarded only for this specific instruction's execution, and no private key material is ever written into the resulting image.
Verifying SSH Access Is Forwarded Correctly
Confirming the SSH agent forwarding actually works as expected before relying on it in a larger build helps catch configuration issues early.
ssh-add -l
docker build --ssh default -t myapp .
Listing currently loaded SSH identities confirms what will actually be available for forwarding during the build.
Why a Private Key Should Never Be Copied Directly
Copying a private SSH key into an image, even temporarily within a multi-stage build, risks that key persisting in an intermediate layer or being unintentionally retained in the final image if not handled with extreme care — SSH mounts avoid this risk entirely by never writing the key into any layer in the first place.
COPY id_rsa /root/.ssh/id_rsa
RUN --mount=type=ssh git clone git@github.com:example/private-repo.git
The second approach achieves the same goal without ever risking the key's persistence in the image.
Why SSH Mounts Matter
SSH mounts provide a clean, secure mechanism for build steps that genuinely need SSH-based authentication, eliminating a previously common and risky workaround involving directly embedding private keys into a Dockerfile or build context.