Sometimes, one may want to download code from a private repo
when building a docker image based on a Dockerfile.
However, the process building the docker image doesn’t have
the same privilege as the host running docker build
. Fortunately,
the newer version docker has provided the capability for us to
pass git secrets to the image-building process. Let’s see how.
Step 1: add an ssh key to github account
Follow this post to generate and add ssh key to your github account, and this github account should contain the private repo to access from Dockerfile.
Let’s say the ssh key local file is at ~/.ssh/id_rsa_github
.
For more info, see this link.
Step 2: add the ssh key to ssh agent
Use the following command
|
|
Step 3: use –mount=type=ssh in Dockerfile to access the added ssh key
Let’s say you have a RUN
command needing to access a private repo in the
above mentioned github account, you can use the following command:
|
|
Save the Dockerfile
.
Step 4: build the image
|
|
Note that I used github as the id for the secret in step 3 and 4, you can change it into anything as long as you use the same value all the time.
I hope that this helps you to build a great docker image.
Happy programming 😄
Reference
- More about accessing secrets from Docker file: https://docs.docker.com/reference/dockerfile/#run---mounttypesecret
Last modified on 2024-03-03