Setting up an SSH Key for your containers using docker compose

When creating a docker image you would want to have all the necessary requirements to run your application. That would include package dependencies as well as other resources needed for your stack. Typically this is a straightforward process but when you add private repositories or packages in the mix you will need to make sure your containers have the necessary permissions to pull from these resources.

A common solution is to copy an existing SSH key (Bitbucket or GitHub for example) to your image during your image build in order for your application to pull from your private repositories within your container. The code bellow is an example of how it might look in your Dockerfile.

RUN mkdir ~/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > ~/.ssh/id_rsa
RUN chmod 600 ~/.ssh/id_rsa
RUN ssh-keyscan >> ~/.ssh/known_hosts

If you’re unfamiliar with creating SSH keys for your repositories here are links to the resources on how to.

Doing the above is a good solution but there are a some cons to this method.

  1. When setting up, each team member must do their own builds. If you’re pushing to docker hub this can be a redundant process. (don’t share your private keys folks)
  2. If for some reason you need to change your SSH key you will be forced to rebuild your images —
  3. and If you have multiple custom images that requires the same SSH key you would have to rebuild all of them.


An easier solution would be to utilize docker-compose and share your local private key to your container as a volume. The code bellow is an example of how to set this up

context: ./my-custom-build
dockerfile: Dockerfile
— ./:/var/www/html:delegated
— ~/.ssh/id_rsa:/root/.ssh/id_rsa
— mongo
— redis
— my_network
— ${PORT}:80

You can see in the above code that I am forwarding my local SSH key inside my container. This way every time I run a command that requires to pull from a private repository within my container it will reference my local SSH key and will have access to the resources without issue.


If your development process requires a dynamic way to add your SSH key or you have a custom docker build that takes too long to run every time, then adding your SSH key via this method is definitely good practice. And would allow you to not worry about maintaining a docker build with an SSH key that could potential become redundant.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store