Reputation: 156
Can someone please provide an example of the following command:
DOCKER_BUILDKIT=1 docker build --secret:id=mysecret,src=/local/secret ...
I don't know how to access the variables from secret file after mounting.
For example: I want to set Proxy using the secret passed and run an install command
Upvotes: 5
Views: 11984
Reputation: 152
I spent a lot of time trying to find an easy way to set up this.
This is the easiest way that I found if you want to use an .env file
Considering you have an .env
file like this
SECRET=123
OTHER_SECRET=1234
You can pass all the variables inside .env
using this command
docker build --secret id=my_env,src=.env .
Then to use the variables in your docker file, all you need to do is
# syntax=docker/dockerfile:1
FROM alpine:latest
WORKDIR /app
RUN --mount=type=secret,id=my_env source /run/secrets/my_env; \
echo "$SECRET" >> /app/secrets.txt; \
echo "$OTHER_SECRET" >> /app/secrets.txt;
CMD ["cat","secrets.txt"]
When you run this container it should print your secrets
Make sure to add the # syntax=docker/dockerfile:1
line at the start otherwise it won't work.
Upvotes: 1
Reputation: 1
You can use Docker's secret management feature to mount a secret file in a Docker image build and use a variable from the secret file in the Dockerfile to authenticate a command. Here are the steps to achieve this:
echo "mysecretvalue" | docker secret create my_secret_name -
FROM your_base_image
# Copy the secret file
COPY --from=0 /run/secrets/my_secret_name /my_secret_file
# Use the secret value in a command
RUN my_command --auth $$(cat /my_secret_file)
Note that the --from=0
option copies the secret file from the build context where the secret was added.
docker build --secret my_secret_name .
This will build the Docker image with the secret file mounted and use the secret value in the command my_command
using the --auth
flag.
Upvotes: -2
Reputation: 4911
Your secret would be mounted as /run/secrets/mysecret
which can be accessed using the cat
command. The RUN
command might look something like below:
RUN --mount=type=secret,id=mysecret \
cat /run/secrets/mysecret
A more complete example below:
FROM node:16
WORKDIR /app
RUN --mount=type=secret,id=USERNAME \
cat /run/secrets/USERNAME > /app/username.txt
--secret
flag using below command:DOCKER_BUILDKIT=1 docker build --secret id=USERNAME,src=username.txt -t node:16-secret .
username.txt
secret, which was passed at build time, as the file /app/username.txt
. That can be verified using below command:docker run --rm -it node:16-secret cat username.txt
You can refer this answer for an example of using the mounted secret in a curl command
Upvotes: 8