It is easy to link an existing ssh-agent into a docker container, just to add the environment SSH_AUTH_SOCK. But it will be broken if you recreate an ssh-agent from the host, for some big companies, ssh-agent forward only could live for a couple of hours force you to create a one.


Solution: I use symbolic link to solve this problem, add a script to your bashrc to find a existing ssh-agent and create a link from ~/docker_tmp/ssh-agent to /tmp/ssh-oYYYqv4X/agent.12831, Any time when you have a new ssh-agent, trigger this shell to relink them.

  1. function linkSshAgent {
  2. # link ssh-agent for docker container
  3. if [ -d ~/docker_tmp ];then
  4. if [ -f ~/docker_tmp/ssh-agent ];then
  5. rm -f ~/docker_tmp/ssh-agent
  6. fi
  7. mkdir -p ~/docker_tmp/ssh-agent/
  8. # change the dirname of the ssh-agent tmpdir, I don't want to mount host /tmp to container /tmp
  9. # -v /tmp:/host_tmp
  10. socket_name=$(echo $socket_name | sed 's/\/tmp\//\/host_tmp\//')
  11. ln -sf $socket_name ~/docker_tmp/ssh-agent/ssh-agent
  12. fi
  13. }
start docker script
  1. docker run -d -t --name $containerName \
  2. -h "$containerName" \
  3. -v ~/docker_tmp/ssh-agent/:/docker_tmp/ssh-agent/:ro \
  4. -v /tmp:/host_tmp:ro \
  5. -e SSH_AUTH_SOCK=/docker_tmp/ssh-agent/ssh-agent \
  6. $imageName /bin/bash
  • ~/docker_tmp/ssh-agent/:/docker_tmp/ssh-agent/:ro fixed the ssh-agent file name , I create a ssh-agent on host
  • /tmp:/host_tmp:ro, the only way to change the ssh agent temporary dir is change the env TEMPDIR, I don't want to change this env.
  • SSH_AUTH_SOCK=/docker_tmp/ssh-agent/ssh-agent : specific the ssh-agent file path.
You will see this symbolic link on the docker container
  1. ls -la /docker_tmp/ssh-agent/ssh-agent
  2. lrwxrwxrwx 1 64675 users 36 Apr 21 02:16 /docker_tmp/ssh-agent/ssh-agent -> /host_tmp/ssh-oYYenCqa4X/agent.19236

回應 (Leave a comment)