SSH keys in Docker
One way that I use docker is to encapsulate all the configuration of a remote site. By using docker-compose and a container that just runs /bin/sh, running commands in a controlled environment is easy as exec. One issue I had is how to use my ssh identity. The most flexible answer is to use secrets with docker-compose.
In the Dockerfile, add the following RUN
RUN mkdir -p .ssh && chmod 700 .ssh && ln -s /run/secrets/user_ssh_key /home/someuser/.ssh/id_rsa
Then in docker-compose.yml
, a few bits:
In your service definition:
service:
some-service:
...
secrets:
- user_ssh_key
Then a secrets section (a top level section):
secrets:
user_ssh_key:
file: ~/.ssh/id_rsa
When the container starts, the content of id_rsa
will appear in /run/secrets/user_ssh_key
with usable permissions, and it will not be part of the image or non-running container.
Then to do ssh using a config that may be only in the container can be done with
docker exec -it some-service ssh [some host]
This kind of container can be useful for a bunch of other things since it can be customized with run-time packages, software, etc that the host system doesn't need to be polluted with.