skip to Main Content

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

2

Answers


  1. 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:

    • Dockerfile:
    FROM node:16
    
    WORKDIR /app
    
    RUN --mount=type=secret,id=USERNAME 
        cat /run/secrets/USERNAME > /app/username.txt
    
    • A docker image can be built from this file, with --secret flag using below command:
    DOCKER_BUILDKIT=1 docker build --secret id=USERNAME,src=username.txt -t node:16-secret .
    
    • Now the built docker image contains the contents of 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

    Login or Signup to reply.
  2. 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:

    1. Create a secret file containing the variable you need to authenticate the command:
    echo "mysecretvalue" | docker secret create my_secret_name -
    
    1. Update your Dockerfile to use the secret:
    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.

    1. Build the Docker image with the secret:
    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search