When building in Docker, it is often we need to access private repos using authorized SSH key. However, since Docker builds are isolated from build agent, the keys remain outside of a container being built. Historically, people came up with many workarounds including passing the key to the container via ARG, forwarding SSH_AUTH_SOCK and other risky tricks.
To solve this long-standing problem, Docker 18.09 got an experimental feature that passes an available ssh key loaded to ssh-agent to the docker build. This key can be used in any of the RUN steps of Dockerfile.
To use it in Teamcity, other build system or even locally:
- Add a Build feature “SSH Agent” and chose a key you want to load to a local ssh-agent running at a build agent.
For using it locally, you need to run ssh-agent and supply it with a private key for authentication.
- Set environment variable DOCKER_BUILDKIT=1. It can be done either via env.DOCKER_BUILDKIT as TC build parameter or simply run
export DOCKER_BUILDKIT=1as the first build step.
- Update docker build command in your Dockerfile to:
docker build --ssh default Dockerfile .
–ssh default will make the ssh key available within Docker build.
- Update the very first Dockerfile line with
- (Optional) Ensure that a private repo (i.e. hosted on Github) is accessible via SSH. Something in line with this in your Dockerfile:
RUN mkdir -p ~/.ssh && chmod 700 ~/.ssh && git config --globalurl."ssh://email@example.com/".insteadOf "https://github.com/" \
&& ssh-keyscan github.com >> ~/.ssh/known_hosts && chmod 644 ~/.ssh/known_hosts
- Finally, pass the key to RUN command in your Dockerfile:
RUN --mount=type=ssh git pull firstname.lastname@example.org:awesomeprivaterepo.git
Here, –mount=type=ssh will use the default key from ssh-agent for authentication with the private repo.