Pulling Git Into a Docker Image Without Leaving SSH keys Behind
A code snippet to copy an SSH private key to a Docker image, add it to the ssh-agent and then remove the key and squash the layers created to remove the file and any traces of it from the image.
Join the DZone community and get the full member experience.Join For Free
Adding your code to a docker image is as easy as using an
ADD command into your
Dockerfile. This will essentially copy your code onto the image. However many languages and frameworks will require other steps to be taken from here onwards. For example a
bundle install in a Rails application might want to pull the source of a gem from a private repository, or running
go get on a Go project might require the private SSH keys to a git repository.
The simplest way to address this issue is to add your private SSH key to the docker image. However this is not ideal as you will end up with your private SSH key on a docker image, open to inspection by anyone who has access to it.
I can think of two ways to work around this issue:
- Pull the SSH private key from a secret vault and put it into tmpfs and add that file to the
- Copy the SSH private key to the image, add it to the
ssh-agentand then remove the key and squash the layers created to remove the file and any traces of it from the image.
The first method requires having a hosted secret vault that can serve you with the private key through a
curl command. I will write about the details of this method in near future.
The second method is easier to implement. Here is how it can work:
- Add the private key to the
- Add it to the
- Run the commands that require SSH authentication
- Remove the private key
- Squash the layers
Here Is An Example:
ADD ~/.ssh/mykey /tmp/ RUN ssh-agent /tmp # RUN bundle install or similar command RUN rm /tmp/mykey
Let’s build the image now:
$ docker build -t original .
Now we need to squash the image with something like Docker Squash:
$ docker save original | sudo docker-squash -t squashed | docker load
Original is the image ID of the created image
You can now push the squashed image up to a Docker repository and remove the original image.
$ docker rmi original
It's worth noting that this method works fine with most scenarios, but will add to the build time (squash step).
Published at DZone with permission of Khash Sajadi, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.