Docker container add SSH key


This post goes over how to add an SSH key to a Docker container.

Prerequisite

Set up an SSH key set up on your Mac.

Add SSH key to Docker container

Copy your SSH key to the Docker container with docker cp:

docker cp ~/.ssh/id_rsa $CONTAINER_ID:$HOME_PATH/.ssh/id_rsa

Replace $CONTAINER_ID with the Docker container id (or name) and $HOME_PATH with the Docker home path (~).

Enter the Docker container shell:

docker exec -it $CONTAINER_ID bash

Start ssh-agent and add the key to it:

eval $(ssh-agent -s) && ssh-add ~/.ssh/id_rsa

Script

See the full script:

#!/bin/bash

# update variables below
CONTAINER_ID=
HOME_PATH=

docker cp ~/.ssh/id_rsa $CONTAINER_ID:$HOME_PATH/.ssh/id_rsa
docker exec -it $CONTAINER_ID sh -c 'eval $(ssh-agent -s); ssh-add ~/.ssh/id_rsa'


Please support this site and join our Discord!